]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/intrinsic.rs
Rollup merge of #54257 - alexcrichton:wasm-math-symbols, r=TimNN
[rust.git] / src / librustc_codegen_llvm / 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 attributes;
14 use intrinsics::{self, Intrinsic};
15 use llvm::{self, TypeKind};
16 use abi::{Abi, FnType, LlvmType, PassMode};
17 use mir::place::PlaceRef;
18 use mir::operand::{OperandRef, OperandValue};
19 use base::*;
20 use common::*;
21 use declare;
22 use glue;
23 use type_::Type;
24 use type_of::LayoutLlvmExt;
25 use rustc::ty::{self, Ty};
26 use rustc::ty::layout::{HasDataLayout, LayoutOf};
27 use rustc::hir;
28 use syntax::ast;
29 use syntax::symbol::Symbol;
30 use builder::Builder;
31 use value::Value;
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(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
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(cx.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_codegen_llvm/context.rs
89 pub fn codegen_intrinsic_call(
90     bx: &Builder<'a, 'll, 'tcx>,
91     callee_ty: Ty<'tcx>,
92     fn_ty: &FnType<'tcx, Ty<'tcx>>,
93     args: &[OperandRef<'ll, 'tcx>],
94     llresult: &'ll Value,
95     span: Span,
96 ) {
97     let cx = bx.cx;
98     let tcx = cx.tcx;
99
100     let (def_id, substs) = match callee_ty.sty {
101         ty::FnDef(def_id, substs) => (def_id, substs),
102         _ => bug!("expected fn item type, found {}", callee_ty)
103     };
104
105     let sig = callee_ty.fn_sig(tcx);
106     let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
107     let arg_tys = sig.inputs();
108     let ret_ty = sig.output();
109     let name = &*tcx.item_name(def_id).as_str();
110
111     let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
112     let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
113
114     let simple = get_simple_intrinsic(cx, name);
115     let llval = match name {
116         _ if simple.is_some() => {
117             bx.call(simple.unwrap(),
118                      &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
119                      None)
120         }
121         "unreachable" => {
122             return;
123         },
124         "likely" => {
125             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
126             bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None)
127         }
128         "unlikely" => {
129             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
130             bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None)
131         }
132         "try" => {
133             try_intrinsic(bx, cx,
134                           args[0].immediate(),
135                           args[1].immediate(),
136                           args[2].immediate(),
137                           llresult);
138             return;
139         }
140         "breakpoint" => {
141             let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
142             bx.call(llfn, &[], None)
143         }
144         "size_of" => {
145             let tp_ty = substs.type_at(0);
146             C_usize(cx, cx.size_of(tp_ty).bytes())
147         }
148         "size_of_val" => {
149             let tp_ty = substs.type_at(0);
150             if let OperandValue::Pair(_, meta) = args[0].val {
151                 let (llsize, _) =
152                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
153                 llsize
154             } else {
155                 C_usize(cx, cx.size_of(tp_ty).bytes())
156             }
157         }
158         "min_align_of" => {
159             let tp_ty = substs.type_at(0);
160             C_usize(cx, cx.align_of(tp_ty).abi())
161         }
162         "min_align_of_val" => {
163             let tp_ty = substs.type_at(0);
164             if let OperandValue::Pair(_, meta) = args[0].val {
165                 let (_, llalign) =
166                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
167                 llalign
168             } else {
169                 C_usize(cx, cx.align_of(tp_ty).abi())
170             }
171         }
172         "pref_align_of" => {
173             let tp_ty = substs.type_at(0);
174             C_usize(cx, cx.align_of(tp_ty).pref())
175         }
176         "type_name" => {
177             let tp_ty = substs.type_at(0);
178             let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
179             C_str_slice(cx, ty_name)
180         }
181         "type_id" => {
182             C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0)))
183         }
184         "init" => {
185             let ty = substs.type_at(0);
186             if !cx.layout_of(ty).is_zst() {
187                 // Just zero out the stack slot.
188                 // If we store a zero constant, LLVM will drown in vreg allocation for large data
189                 // structures, and the generated code will be awful. (A telltale sign of this is
190                 // large quantities of `mov [byte ptr foo],0` in the generated code.)
191                 memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1));
192             }
193             return;
194         }
195         // Effectively no-ops
196         "uninit" => {
197             return;
198         }
199         "needs_drop" => {
200             let tp_ty = substs.type_at(0);
201
202             C_bool(cx, bx.cx.type_needs_drop(tp_ty))
203         }
204         "offset" => {
205             let ptr = args[0].immediate();
206             let offset = args[1].immediate();
207             bx.inbounds_gep(ptr, &[offset])
208         }
209         "arith_offset" => {
210             let ptr = args[0].immediate();
211             let offset = args[1].immediate();
212             bx.gep(ptr, &[offset])
213         }
214
215         "copy_nonoverlapping" => {
216             copy_intrinsic(bx, false, false, substs.type_at(0),
217                            args[1].immediate(), args[0].immediate(), args[2].immediate())
218         }
219         "copy" => {
220             copy_intrinsic(bx, true, false, substs.type_at(0),
221                            args[1].immediate(), args[0].immediate(), args[2].immediate())
222         }
223         "write_bytes" => {
224             memset_intrinsic(bx, false, substs.type_at(0),
225                              args[0].immediate(), args[1].immediate(), args[2].immediate())
226         }
227
228         "volatile_copy_nonoverlapping_memory" => {
229             copy_intrinsic(bx, false, true, substs.type_at(0),
230                            args[0].immediate(), args[1].immediate(), args[2].immediate())
231         }
232         "volatile_copy_memory" => {
233             copy_intrinsic(bx, true, true, substs.type_at(0),
234                            args[0].immediate(), args[1].immediate(), args[2].immediate())
235         }
236         "volatile_set_memory" => {
237             memset_intrinsic(bx, true, substs.type_at(0),
238                              args[0].immediate(), args[1].immediate(), args[2].immediate())
239         }
240         "volatile_load" | "unaligned_volatile_load" => {
241             let tp_ty = substs.type_at(0);
242             let mut ptr = args[0].immediate();
243             if let PassMode::Cast(ty) = fn_ty.ret.mode {
244                 ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to());
245             }
246             let load = bx.volatile_load(ptr);
247             let align = if name == "unaligned_volatile_load" {
248                 1
249             } else {
250                 cx.align_of(tp_ty).abi() as u32
251             };
252             unsafe {
253                 llvm::LLVMSetAlignment(load, align);
254             }
255             to_immediate(bx, load, cx.layout_of(tp_ty))
256         },
257         "volatile_store" => {
258             let dst = args[0].deref(bx.cx);
259             args[1].val.volatile_store(bx, dst);
260             return;
261         },
262         "unaligned_volatile_store" => {
263             let dst = args[0].deref(bx.cx);
264             args[1].val.unaligned_volatile_store(bx, dst);
265             return;
266         },
267         "prefetch_read_data" | "prefetch_write_data" |
268         "prefetch_read_instruction" | "prefetch_write_instruction" => {
269             let expect = cx.get_intrinsic(&("llvm.prefetch"));
270             let (rw, cache_type) = match name {
271                 "prefetch_read_data" => (0, 1),
272                 "prefetch_write_data" => (1, 1),
273                 "prefetch_read_instruction" => (0, 0),
274                 "prefetch_write_instruction" => (1, 0),
275                 _ => bug!()
276             };
277             bx.call(expect, &[
278                 args[0].immediate(),
279                 C_i32(cx, rw),
280                 args[1].immediate(),
281                 C_i32(cx, cache_type)
282             ], None)
283         },
284         "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
285         "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
286         "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
287         "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" => {
288             let ty = arg_tys[0];
289             match int_type_width_signed(ty, cx) {
290                 Some((width, signed)) =>
291                     match name {
292                         "ctlz" | "cttz" => {
293                             let y = C_bool(bx.cx, false);
294                             let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
295                             bx.call(llfn, &[args[0].immediate(), y], None)
296                         }
297                         "ctlz_nonzero" | "cttz_nonzero" => {
298                             let y = C_bool(bx.cx, true);
299                             let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
300                             let llfn = cx.get_intrinsic(llvm_name);
301                             bx.call(llfn, &[args[0].immediate(), y], None)
302                         }
303                         "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
304                                         &[args[0].immediate()], None),
305                         "bswap" => {
306                             if width == 8 {
307                                 args[0].immediate() // byte swap a u8/i8 is just a no-op
308                             } else {
309                                 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
310                                         &[args[0].immediate()], None)
311                             }
312                         }
313                         "bitreverse" => {
314                             bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
315                                 &[args[0].immediate()], None)
316                         }
317                         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
318                             let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
319                                                     if signed { 's' } else { 'u' },
320                                                     &name[..3], width);
321                             let llfn = bx.cx.get_intrinsic(&intrinsic);
322
323                             // Convert `i1` to a `bool`, and write it to the out parameter
324                             let pair = bx.call(llfn, &[
325                                 args[0].immediate(),
326                                 args[1].immediate()
327                             ], None);
328                             let val = bx.extract_value(pair, 0);
329                             let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx));
330
331                             let dest = result.project_field(bx, 0);
332                             bx.store(val, dest.llval, dest.align);
333                             let dest = result.project_field(bx, 1);
334                             bx.store(overflow, dest.llval, dest.align);
335
336                             return;
337                         },
338                         "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
339                         "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
340                         "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
341                         "exact_div" =>
342                             if signed {
343                                 bx.exactsdiv(args[0].immediate(), args[1].immediate())
344                             } else {
345                                 bx.exactudiv(args[0].immediate(), args[1].immediate())
346                             },
347                         "unchecked_div" =>
348                             if signed {
349                                 bx.sdiv(args[0].immediate(), args[1].immediate())
350                             } else {
351                                 bx.udiv(args[0].immediate(), args[1].immediate())
352                             },
353                         "unchecked_rem" =>
354                             if signed {
355                                 bx.srem(args[0].immediate(), args[1].immediate())
356                             } else {
357                                 bx.urem(args[0].immediate(), args[1].immediate())
358                             },
359                         "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
360                         "unchecked_shr" =>
361                             if signed {
362                                 bx.ashr(args[0].immediate(), args[1].immediate())
363                             } else {
364                                 bx.lshr(args[0].immediate(), args[1].immediate())
365                             },
366                         _ => bug!(),
367                     },
368                 None => {
369                     span_invalid_monomorphization_error(
370                         tcx.sess, span,
371                         &format!("invalid monomorphization of `{}` intrinsic: \
372                                   expected basic integer type, found `{}`", name, ty));
373                     return;
374                 }
375             }
376
377         },
378         "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
379             let sty = &arg_tys[0].sty;
380             match float_type_width(sty) {
381                 Some(_width) =>
382                     match name {
383                         "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
384                         "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
385                         "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
386                         "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
387                         "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
388                         _ => bug!(),
389                     },
390                 None => {
391                     span_invalid_monomorphization_error(
392                         tcx.sess, span,
393                         &format!("invalid monomorphization of `{}` intrinsic: \
394                                   expected basic float type, found `{}`", name, sty));
395                     return;
396                 }
397             }
398
399         },
400
401         "discriminant_value" => {
402             args[0].deref(bx.cx).codegen_get_discr(bx, ret_ty)
403         }
404
405         name if name.starts_with("simd_") => {
406             match generic_simd_intrinsic(bx, name,
407                                          callee_ty,
408                                          args,
409                                          ret_ty, llret_ty,
410                                          span) {
411                 Ok(llval) => llval,
412                 Err(()) => return
413             }
414         }
415         // This requires that atomic intrinsics follow a specific naming pattern:
416         // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
417         name if name.starts_with("atomic_") => {
418             use llvm::AtomicOrdering::*;
419
420             let split: Vec<&str> = name.split('_').collect();
421
422             let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
423             let (order, failorder) = match split.len() {
424                 2 => (SequentiallyConsistent, SequentiallyConsistent),
425                 3 => match split[2] {
426                     "unordered" => (Unordered, Unordered),
427                     "relaxed" => (Monotonic, Monotonic),
428                     "acq"     => (Acquire, Acquire),
429                     "rel"     => (Release, Monotonic),
430                     "acqrel"  => (AcquireRelease, Acquire),
431                     "failrelaxed" if is_cxchg =>
432                         (SequentiallyConsistent, Monotonic),
433                     "failacq" if is_cxchg =>
434                         (SequentiallyConsistent, Acquire),
435                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
436                 },
437                 4 => match (split[2], split[3]) {
438                     ("acq", "failrelaxed") if is_cxchg =>
439                         (Acquire, Monotonic),
440                     ("acqrel", "failrelaxed") if is_cxchg =>
441                         (AcquireRelease, Monotonic),
442                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
443                 },
444                 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
445             };
446
447             let invalid_monomorphization = |ty| {
448                 span_invalid_monomorphization_error(tcx.sess, span,
449                     &format!("invalid monomorphization of `{}` intrinsic: \
450                               expected basic integer type, found `{}`", name, ty));
451             };
452
453             match split[1] {
454                 "cxchg" | "cxchgweak" => {
455                     let ty = substs.type_at(0);
456                     if int_type_width_signed(ty, cx).is_some() {
457                         let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
458                         let pair = bx.atomic_cmpxchg(
459                             args[0].immediate(),
460                             args[1].immediate(),
461                             args[2].immediate(),
462                             order,
463                             failorder,
464                             weak);
465                         let val = bx.extract_value(pair, 0);
466                         let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx));
467
468                         let dest = result.project_field(bx, 0);
469                         bx.store(val, dest.llval, dest.align);
470                         let dest = result.project_field(bx, 1);
471                         bx.store(success, dest.llval, dest.align);
472                         return;
473                     } else {
474                         return invalid_monomorphization(ty);
475                     }
476                 }
477
478                 "load" => {
479                     let ty = substs.type_at(0);
480                     if int_type_width_signed(ty, cx).is_some() {
481                         let align = cx.align_of(ty);
482                         bx.atomic_load(args[0].immediate(), order, align)
483                     } else {
484                         return invalid_monomorphization(ty);
485                     }
486                 }
487
488                 "store" => {
489                     let ty = substs.type_at(0);
490                     if int_type_width_signed(ty, cx).is_some() {
491                         let align = cx.align_of(ty);
492                         bx.atomic_store(args[1].immediate(), args[0].immediate(), order, align);
493                         return;
494                     } else {
495                         return invalid_monomorphization(ty);
496                     }
497                 }
498
499                 "fence" => {
500                     bx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
501                     return;
502                 }
503
504                 "singlethreadfence" => {
505                     bx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
506                     return;
507                 }
508
509                 // These are all AtomicRMW ops
510                 op => {
511                     let atom_op = match op {
512                         "xchg"  => llvm::AtomicXchg,
513                         "xadd"  => llvm::AtomicAdd,
514                         "xsub"  => llvm::AtomicSub,
515                         "and"   => llvm::AtomicAnd,
516                         "nand"  => llvm::AtomicNand,
517                         "or"    => llvm::AtomicOr,
518                         "xor"   => llvm::AtomicXor,
519                         "max"   => llvm::AtomicMax,
520                         "min"   => llvm::AtomicMin,
521                         "umax"  => llvm::AtomicUMax,
522                         "umin"  => llvm::AtomicUMin,
523                         _ => cx.sess().fatal("unknown atomic operation")
524                     };
525
526                     let ty = substs.type_at(0);
527                     if int_type_width_signed(ty, cx).is_some() {
528                         bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
529                     } else {
530                         return invalid_monomorphization(ty);
531                     }
532                 }
533             }
534         }
535
536         "nontemporal_store" => {
537             let dst = args[0].deref(bx.cx);
538             args[1].val.nontemporal_store(bx, dst);
539             return;
540         }
541
542         _ => {
543             let intr = match Intrinsic::find(&name) {
544                 Some(intr) => intr,
545                 None => bug!("unknown intrinsic '{}'", name),
546             };
547             fn one<T>(x: Vec<T>) -> T {
548                 assert_eq!(x.len(), 1);
549                 x.into_iter().next().unwrap()
550             }
551             fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
552                 use intrinsics::Type::*;
553                 match *t {
554                     Void => vec![Type::void(cx)],
555                     Integer(_signed, _width, llvm_width) => {
556                         vec![Type::ix(cx, llvm_width as u64)]
557                     }
558                     Float(x) => {
559                         match x {
560                             32 => vec![Type::f32(cx)],
561                             64 => vec![Type::f64(cx)],
562                             _ => bug!()
563                         }
564                     }
565                     Pointer(ref t, ref llvm_elem, _const) => {
566                         let t = llvm_elem.as_ref().unwrap_or(t);
567                         let elem = one(ty_to_type(cx, t));
568                         vec![elem.ptr_to()]
569                     }
570                     Vector(ref t, ref llvm_elem, length) => {
571                         let t = llvm_elem.as_ref().unwrap_or(t);
572                         let elem = one(ty_to_type(cx, t));
573                         vec![Type::vector(elem, length as u64)]
574                     }
575                     Aggregate(false, ref contents) => {
576                         let elems = contents.iter()
577                                             .map(|t| one(ty_to_type(cx, t)))
578                                             .collect::<Vec<_>>();
579                         vec![Type::struct_(cx, &elems, false)]
580                     }
581                     Aggregate(true, ref contents) => {
582                         contents.iter()
583                                 .flat_map(|t| ty_to_type(cx, t))
584                                 .collect()
585                     }
586                 }
587             }
588
589             // This allows an argument list like `foo, (bar, baz),
590             // qux` to be converted into `foo, bar, baz, qux`, integer
591             // arguments to be truncated as needed and pointers to be
592             // cast.
593             fn modify_as_needed(
594                 bx: &Builder<'a, 'll, 'tcx>,
595                 t: &intrinsics::Type,
596                 arg: &OperandRef<'ll, 'tcx>,
597             ) -> Vec<&'ll Value> {
598                 match *t {
599                     intrinsics::Type::Aggregate(true, ref contents) => {
600                         // We found a tuple that needs squishing! So
601                         // run over the tuple and load each field.
602                         //
603                         // This assumes the type is "simple", i.e. no
604                         // destructors, and the contents are SIMD
605                         // etc.
606                         assert!(!bx.cx.type_needs_drop(arg.layout.ty));
607                         let (ptr, align) = match arg.val {
608                             OperandValue::Ref(ptr, None, align) => (ptr, align),
609                             _ => bug!()
610                         };
611                         let arg = PlaceRef::new_sized(ptr, arg.layout, align);
612                         (0..contents.len()).map(|i| {
613                             arg.project_field(bx, i).load(bx).immediate()
614                         }).collect()
615                     }
616                     intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
617                         let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
618                         vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())]
619                     }
620                     intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
621                         let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
622                         vec![bx.bitcast(arg.immediate(), Type::vector(llvm_elem, length as u64))]
623                     }
624                     intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
625                         // the LLVM intrinsic uses a smaller integer
626                         // size than the C intrinsic's signature, so
627                         // we have to trim it down here.
628                         vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))]
629                     }
630                     _ => vec![arg.immediate()],
631                 }
632             }
633
634
635             let inputs = intr.inputs.iter()
636                                     .flat_map(|t| ty_to_type(cx, t))
637                                     .collect::<Vec<_>>();
638
639             let outputs = one(ty_to_type(cx, &intr.output));
640
641             let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
642                 modify_as_needed(bx, t, arg)
643             }).collect();
644             assert_eq!(inputs.len(), llargs.len());
645
646             let val = match intr.definition {
647                 intrinsics::IntrinsicDef::Named(name) => {
648                     let f = declare::declare_cfn(cx,
649                                                  name,
650                                                  Type::func(&inputs, outputs));
651                     bx.call(f, &llargs, None)
652                 }
653             };
654
655             match *intr.output {
656                 intrinsics::Type::Aggregate(flatten, ref elems) => {
657                     // the output is a tuple so we need to munge it properly
658                     assert!(!flatten);
659
660                     for i in 0..elems.len() {
661                         let dest = result.project_field(bx, i);
662                         let val = bx.extract_value(val, i as u64);
663                         bx.store(val, dest.llval, dest.align);
664                     }
665                     return;
666                 }
667                 _ => val,
668             }
669         }
670     };
671
672     if !fn_ty.ret.is_ignore() {
673         if let PassMode::Cast(ty) = fn_ty.ret.mode {
674             let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to());
675             bx.store(llval, ptr, result.align);
676         } else {
677             OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
678                 .val.store(bx, result);
679         }
680     }
681 }
682
683 fn copy_intrinsic(
684     bx: &Builder<'a, 'll, 'tcx>,
685     allow_overlap: bool,
686     volatile: bool,
687     ty: Ty<'tcx>,
688     dst: &'ll Value,
689     src: &'ll Value,
690     count: &'ll Value,
691 ) -> &'ll Value {
692     let cx = bx.cx;
693     let (size, align) = cx.size_and_align_of(ty);
694     let size = C_usize(cx, size.bytes());
695     let align = C_i32(cx, align.abi() as i32);
696
697     let operation = if allow_overlap {
698         "memmove"
699     } else {
700         "memcpy"
701     };
702
703     let name = format!("llvm.{}.p0i8.p0i8.i{}", operation,
704                        cx.data_layout().pointer_size.bits());
705
706     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
707     let src_ptr = bx.pointercast(src, Type::i8p(cx));
708     let llfn = cx.get_intrinsic(&name);
709
710     bx.call(llfn,
711         &[dst_ptr,
712         src_ptr,
713         bx.mul(size, count),
714         align,
715         C_bool(cx, volatile)],
716         None)
717 }
718
719 fn memset_intrinsic(
720     bx: &Builder<'a, 'll, 'tcx>,
721     volatile: bool,
722     ty: Ty<'tcx>,
723     dst: &'ll Value,
724     val: &'ll Value,
725     count: &'ll Value
726 ) -> &'ll Value {
727     let cx = bx.cx;
728     let (size, align) = cx.size_and_align_of(ty);
729     let size = C_usize(cx, size.bytes());
730     let align = C_i32(cx, align.abi() as i32);
731     let dst = bx.pointercast(dst, Type::i8p(cx));
732     call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
733 }
734
735 fn try_intrinsic(
736     bx: &Builder<'a, 'll, 'tcx>,
737     cx: &CodegenCx<'ll, 'tcx>,
738     func: &'ll Value,
739     data: &'ll Value,
740     local_ptr: &'ll Value,
741     dest: &'ll Value,
742 ) {
743     if bx.sess().no_landing_pads() {
744         bx.call(func, &[data], None);
745         let ptr_align = bx.tcx().data_layout.pointer_align;
746         bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align);
747     } else if wants_msvc_seh(bx.sess()) {
748         codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
749     } else {
750         codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
751     }
752 }
753
754 // MSVC's definition of the `rust_try` function.
755 //
756 // This implementation uses the new exception handling instructions in LLVM
757 // which have support in LLVM for SEH on MSVC targets. Although these
758 // instructions are meant to work for all targets, as of the time of this
759 // writing, however, LLVM does not recommend the usage of these new instructions
760 // as the old ones are still more optimized.
761 fn codegen_msvc_try(
762     bx: &Builder<'a, 'll, 'tcx>,
763     cx: &CodegenCx<'ll, 'tcx>,
764     func: &'ll Value,
765     data: &'ll Value,
766     local_ptr: &'ll Value,
767     dest: &'ll Value,
768 ) {
769     let llfn = get_rust_try_fn(cx, &mut |bx| {
770         let cx = bx.cx;
771
772         bx.set_personality_fn(bx.cx.eh_personality());
773
774         let normal = bx.build_sibling_block("normal");
775         let catchswitch = bx.build_sibling_block("catchswitch");
776         let catchpad = bx.build_sibling_block("catchpad");
777         let caught = bx.build_sibling_block("caught");
778
779         let func = llvm::get_param(bx.llfn(), 0);
780         let data = llvm::get_param(bx.llfn(), 1);
781         let local_ptr = llvm::get_param(bx.llfn(), 2);
782
783         // We're generating an IR snippet that looks like:
784         //
785         //   declare i32 @rust_try(%func, %data, %ptr) {
786         //      %slot = alloca i64*
787         //      invoke %func(%data) to label %normal unwind label %catchswitch
788         //
789         //   normal:
790         //      ret i32 0
791         //
792         //   catchswitch:
793         //      %cs = catchswitch within none [%catchpad] unwind to caller
794         //
795         //   catchpad:
796         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
797         //      %ptr[0] = %slot[0]
798         //      %ptr[1] = %slot[1]
799         //      catchret from %tok to label %caught
800         //
801         //   caught:
802         //      ret i32 1
803         //   }
804         //
805         // This structure follows the basic usage of throw/try/catch in LLVM.
806         // For example, compile this C++ snippet to see what LLVM generates:
807         //
808         //      #include <stdint.h>
809         //
810         //      int bar(void (*foo)(void), uint64_t *ret) {
811         //          try {
812         //              foo();
813         //              return 0;
814         //          } catch(uint64_t a[2]) {
815         //              ret[0] = a[0];
816         //              ret[1] = a[1];
817         //              return 1;
818         //          }
819         //      }
820         //
821         // More information can be found in libstd's seh.rs implementation.
822         let i64p = Type::i64(cx).ptr_to();
823         let ptr_align = bx.tcx().data_layout.pointer_align;
824         let slot = bx.alloca(i64p, "slot", ptr_align);
825         bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
826             None);
827
828         normal.ret(C_i32(cx, 0));
829
830         let cs = catchswitch.catch_switch(None, None, 1);
831         catchswitch.add_handler(cs, catchpad.llbb());
832
833         let tcx = cx.tcx;
834         let tydesc = match tcx.lang_items().msvc_try_filter() {
835             Some(did) => ::consts::get_static(cx, did),
836             None => bug!("msvc_try_filter not defined"),
837         };
838         let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]);
839         let addr = catchpad.load(slot, ptr_align);
840
841         let i64_align = bx.tcx().data_layout.i64_align;
842         let arg1 = catchpad.load(addr, i64_align);
843         let val1 = C_i32(cx, 1);
844         let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
845         let local_ptr = catchpad.bitcast(local_ptr, i64p);
846         catchpad.store(arg1, local_ptr, i64_align);
847         catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
848         catchpad.catch_ret(tok, caught.llbb());
849
850         caught.ret(C_i32(cx, 1));
851     });
852
853     // Note that no invoke is used here because by definition this function
854     // can't panic (that's what it's catching).
855     let ret = bx.call(llfn, &[func, data, local_ptr], None);
856     let i32_align = bx.tcx().data_layout.i32_align;
857     bx.store(ret, dest, i32_align);
858 }
859
860 // Definition of the standard "try" function for Rust using the GNU-like model
861 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
862 // instructions).
863 //
864 // This codegen is a little surprising because we always call a shim
865 // function instead of inlining the call to `invoke` manually here. This is done
866 // because in LLVM we're only allowed to have one personality per function
867 // definition. The call to the `try` intrinsic is being inlined into the
868 // function calling it, and that function may already have other personality
869 // functions in play. By calling a shim we're guaranteed that our shim will have
870 // the right personality function.
871 fn codegen_gnu_try(
872     bx: &Builder<'a, 'll, 'tcx>,
873     cx: &CodegenCx<'ll, 'tcx>,
874     func: &'ll Value,
875     data: &'ll Value,
876     local_ptr: &'ll Value,
877     dest: &'ll Value,
878 ) {
879     let llfn = get_rust_try_fn(cx, &mut |bx| {
880         let cx = bx.cx;
881
882         // Codegens the shims described above:
883         //
884         //   bx:
885         //      invoke %func(%args...) normal %normal unwind %catch
886         //
887         //   normal:
888         //      ret 0
889         //
890         //   catch:
891         //      (ptr, _) = landingpad
892         //      store ptr, %local_ptr
893         //      ret 1
894         //
895         // Note that the `local_ptr` data passed into the `try` intrinsic is
896         // expected to be `*mut *mut u8` for this to actually work, but that's
897         // managed by the standard library.
898
899         let then = bx.build_sibling_block("then");
900         let catch = bx.build_sibling_block("catch");
901
902         let func = llvm::get_param(bx.llfn(), 0);
903         let data = llvm::get_param(bx.llfn(), 1);
904         let local_ptr = llvm::get_param(bx.llfn(), 2);
905         bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
906         then.ret(C_i32(cx, 0));
907
908         // Type indicator for the exception being thrown.
909         //
910         // The first value in this tuple is a pointer to the exception object
911         // being thrown.  The second value is a "selector" indicating which of
912         // the landing pad clauses the exception's type had been matched to.
913         // rust_try ignores the selector.
914         let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)],
915                                     false);
916         let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1);
917         catch.add_clause(vals, C_null(Type::i8p(cx)));
918         let ptr = catch.extract_value(vals, 0);
919         let ptr_align = bx.tcx().data_layout.pointer_align;
920         catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align);
921         catch.ret(C_i32(cx, 1));
922     });
923
924     // Note that no invoke is used here because by definition this function
925     // can't panic (that's what it's catching).
926     let ret = bx.call(llfn, &[func, data, local_ptr], None);
927     let i32_align = bx.tcx().data_layout.i32_align;
928     bx.store(ret, dest, i32_align);
929 }
930
931 // Helper function to give a Block to a closure to codegen a shim function.
932 // This is currently primarily used for the `try` intrinsic functions above.
933 fn gen_fn<'ll, 'tcx>(
934     cx: &CodegenCx<'ll, 'tcx>,
935     name: &str,
936     inputs: Vec<Ty<'tcx>>,
937     output: Ty<'tcx>,
938     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
939 ) -> &'ll Value {
940     let rust_fn_ty = cx.tcx.mk_fn_ptr(ty::Binder::bind(cx.tcx.mk_fn_sig(
941         inputs.into_iter(),
942         output,
943         false,
944         hir::Unsafety::Unsafe,
945         Abi::Rust
946     )));
947     let llfn = declare::define_internal_fn(cx, name, rust_fn_ty);
948     attributes::from_fn_attrs(cx, llfn, None);
949     let bx = Builder::new_block(cx, llfn, "entry-block");
950     codegen(bx);
951     llfn
952 }
953
954 // Helper function used to get a handle to the `__rust_try` function used to
955 // catch exceptions.
956 //
957 // This function is only generated once and is then cached.
958 fn get_rust_try_fn<'ll, 'tcx>(
959     cx: &CodegenCx<'ll, 'tcx>,
960     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
961 ) -> &'ll Value {
962     if let Some(llfn) = cx.rust_try_fn.get() {
963         return llfn;
964     }
965
966     // Define the type up front for the signature of the rust_try function.
967     let tcx = cx.tcx;
968     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
969     let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
970         iter::once(i8p),
971         tcx.mk_unit(),
972         false,
973         hir::Unsafety::Unsafe,
974         Abi::Rust
975     )));
976     let output = tcx.types.i32;
977     let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
978     cx.rust_try_fn.set(Some(rust_try));
979     return rust_try
980 }
981
982 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
983     span_err!(a, b, E0511, "{}", c);
984 }
985
986 fn generic_simd_intrinsic(
987     bx: &Builder<'a, 'll, 'tcx>,
988     name: &str,
989     callee_ty: Ty<'tcx>,
990     args: &[OperandRef<'ll, 'tcx>],
991     ret_ty: Ty<'tcx>,
992     llret_ty: &'ll Type,
993     span: Span
994 ) -> Result<&'ll Value, ()> {
995     // macros for error handling:
996     macro_rules! emit_error {
997         ($msg: tt) => {
998             emit_error!($msg, )
999         };
1000         ($msg: tt, $($fmt: tt)*) => {
1001             span_invalid_monomorphization_error(
1002                 bx.sess(), span,
1003                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
1004                                  $msg),
1005                          name, $($fmt)*));
1006         }
1007     }
1008     macro_rules! return_error {
1009         ($($fmt: tt)*) => {
1010             {
1011                 emit_error!($($fmt)*);
1012                 return Err(());
1013             }
1014         }
1015     }
1016
1017     macro_rules! require {
1018         ($cond: expr, $($fmt: tt)*) => {
1019             if !$cond {
1020                 return_error!($($fmt)*);
1021             }
1022         };
1023     }
1024     macro_rules! require_simd {
1025         ($ty: expr, $position: expr) => {
1026             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1027         }
1028     }
1029
1030
1031
1032     let tcx = bx.tcx();
1033     let sig = tcx.normalize_erasing_late_bound_regions(
1034         ty::ParamEnv::reveal_all(),
1035         &callee_ty.fn_sig(tcx),
1036     );
1037     let arg_tys = sig.inputs();
1038
1039     // every intrinsic takes a SIMD vector as its first argument
1040     require_simd!(arg_tys[0], "input");
1041     let in_ty = arg_tys[0];
1042     let in_elem = arg_tys[0].simd_type(tcx);
1043     let in_len = arg_tys[0].simd_size(tcx);
1044
1045     let comparison = match name {
1046         "simd_eq" => Some(hir::BinOpKind::Eq),
1047         "simd_ne" => Some(hir::BinOpKind::Ne),
1048         "simd_lt" => Some(hir::BinOpKind::Lt),
1049         "simd_le" => Some(hir::BinOpKind::Le),
1050         "simd_gt" => Some(hir::BinOpKind::Gt),
1051         "simd_ge" => Some(hir::BinOpKind::Ge),
1052         _ => None
1053     };
1054
1055     if let Some(cmp_op) = comparison {
1056         require_simd!(ret_ty, "return");
1057
1058         let out_len = ret_ty.simd_size(tcx);
1059         require!(in_len == out_len,
1060                  "expected return type with length {} (same as input type `{}`), \
1061                   found `{}` with length {}",
1062                  in_len, in_ty,
1063                  ret_ty, out_len);
1064         require!(llret_ty.element_type().kind() == TypeKind::Integer,
1065                  "expected return type with integer elements, found `{}` with non-integer `{}`",
1066                  ret_ty,
1067                  ret_ty.simd_type(tcx));
1068
1069         return Ok(compare_simd_types(bx,
1070                                      args[0].immediate(),
1071                                      args[1].immediate(),
1072                                      in_elem,
1073                                      llret_ty,
1074                                      cmp_op))
1075     }
1076
1077     if name.starts_with("simd_shuffle") {
1078         let n: usize = match name["simd_shuffle".len()..].parse() {
1079             Ok(n) => n,
1080             Err(_) => span_bug!(span,
1081                                 "bad `simd_shuffle` instruction only caught in codegen?")
1082         };
1083
1084         require_simd!(ret_ty, "return");
1085
1086         let out_len = ret_ty.simd_size(tcx);
1087         require!(out_len == n,
1088                  "expected return type of length {}, found `{}` with length {}",
1089                  n, ret_ty, out_len);
1090         require!(in_elem == ret_ty.simd_type(tcx),
1091                  "expected return element type `{}` (element of input `{}`), \
1092                   found `{}` with element type `{}`",
1093                  in_elem, in_ty,
1094                  ret_ty, ret_ty.simd_type(tcx));
1095
1096         let total_len = in_len as u128 * 2;
1097
1098         let vector = args[2].immediate();
1099
1100         let indices: Option<Vec<_>> = (0..n)
1101             .map(|i| {
1102                 let arg_idx = i;
1103                 let val = const_get_elt(vector, i as u64);
1104                 match const_to_opt_u128(val, true) {
1105                     None => {
1106                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1107                         None
1108                     }
1109                     Some(idx) if idx >= total_len => {
1110                         emit_error!("shuffle index #{} is out of bounds (limit {})",
1111                                     arg_idx, total_len);
1112                         None
1113                     }
1114                     Some(idx) => Some(C_i32(bx.cx, idx as i32)),
1115                 }
1116             })
1117             .collect();
1118         let indices = match indices {
1119             Some(i) => i,
1120             None => return Ok(C_null(llret_ty))
1121         };
1122
1123         return Ok(bx.shuffle_vector(args[0].immediate(),
1124                                      args[1].immediate(),
1125                                      C_vector(&indices)))
1126     }
1127
1128     if name == "simd_insert" {
1129         require!(in_elem == arg_tys[2],
1130                  "expected inserted type `{}` (element of input `{}`), found `{}`",
1131                  in_elem, in_ty, arg_tys[2]);
1132         return Ok(bx.insert_element(args[0].immediate(),
1133                                      args[2].immediate(),
1134                                      args[1].immediate()))
1135     }
1136     if name == "simd_extract" {
1137         require!(ret_ty == in_elem,
1138                  "expected return type `{}` (element of input `{}`), found `{}`",
1139                  in_elem, in_ty, ret_ty);
1140         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1141     }
1142
1143     if name == "simd_select" {
1144         let m_elem_ty = in_elem;
1145         let m_len = in_len;
1146         let v_len = arg_tys[1].simd_size(tcx);
1147         require!(m_len == v_len,
1148                  "mismatched lengths: mask length `{}` != other vector length `{}`",
1149                  m_len, v_len
1150         );
1151         match m_elem_ty.sty {
1152             ty::Int(_) => {},
1153             _ => {
1154                 return_error!("mask element type is `{}`, expected `i_`", m_elem_ty);
1155             }
1156         }
1157         // truncate the mask to a vector of i1s
1158         let i1 = Type::i1(bx.cx);
1159         let i1xn = Type::vector(i1, m_len as u64);
1160         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1161         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1162     }
1163
1164     fn simd_simple_float_intrinsic(
1165         name: &str,
1166         in_elem: &::rustc::ty::TyS,
1167         in_ty: &::rustc::ty::TyS,
1168         in_len: usize,
1169         bx: &Builder<'a, 'll, 'tcx>,
1170         span: Span,
1171         args: &[OperandRef<'ll, 'tcx>],
1172     ) -> Result<&'ll Value, ()> {
1173         macro_rules! emit_error {
1174             ($msg: tt) => {
1175                 emit_error!($msg, )
1176             };
1177             ($msg: tt, $($fmt: tt)*) => {
1178                 span_invalid_monomorphization_error(
1179                     bx.sess(), span,
1180                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
1181                                      $msg),
1182                              name, $($fmt)*));
1183             }
1184         }
1185         macro_rules! return_error {
1186             ($($fmt: tt)*) => {
1187                 {
1188                     emit_error!($($fmt)*);
1189                     return Err(());
1190                 }
1191             }
1192         }
1193         let ety = match in_elem.sty {
1194             ty::Float(f) if f.bit_width() == 32 => {
1195                 if in_len < 2 || in_len > 16 {
1196                     return_error!(
1197                         "unsupported floating-point vector `{}` with length `{}` \
1198                          out-of-range [2, 16]",
1199                         in_ty, in_len);
1200                 }
1201                 "f32"
1202             },
1203             ty::Float(f) if f.bit_width() == 64 => {
1204                 if in_len < 2 || in_len > 8 {
1205                     return_error!("unsupported floating-point vector `{}` with length `{}` \
1206                                    out-of-range [2, 8]",
1207                                   in_ty, in_len);
1208                 }
1209                 "f64"
1210             },
1211             ty::Float(f) => {
1212                 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1213                               f, in_ty);
1214             },
1215             _ => {
1216                 return_error!("`{}` is not a floating-point type", in_ty);
1217             }
1218         };
1219
1220         let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1221         let intrinsic = bx.cx.get_intrinsic(&llvm_name);
1222         let c = bx.call(intrinsic,
1223                         &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1224                         None);
1225         unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1226         return Ok(c);
1227     }
1228
1229     if name == "simd_fsqrt" {
1230         return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1231     }
1232
1233     if name == "simd_fsin" {
1234         return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1235     }
1236
1237     if name == "simd_fcos" {
1238         return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1239     }
1240
1241     if name == "simd_fabs" {
1242         return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1243     }
1244
1245     if name == "simd_floor" {
1246         return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1247     }
1248
1249     if name == "simd_ceil" {
1250         return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1251     }
1252
1253     if name == "simd_fexp" {
1254         return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1255     }
1256
1257     if name == "simd_fexp2" {
1258         return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1259     }
1260
1261     if name == "simd_flog10" {
1262         return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1263     }
1264
1265     if name == "simd_flog2" {
1266         return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1267     }
1268
1269     if name == "simd_flog" {
1270         return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1271     }
1272
1273     if name == "simd_fpowi" {
1274         return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1275     }
1276
1277     if name == "simd_fpow"  {
1278         return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1279     }
1280
1281     if name == "simd_fma" {
1282         return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1283     }
1284
1285     // FIXME: use:
1286     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1287     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1288     fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1289         let p0s: String = "p0".repeat(no_pointers);
1290         match elem_ty.sty {
1291             ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1292             ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1293             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1294             _ => unreachable!(),
1295         }
1296     }
1297
1298     fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1299                       mut no_pointers: usize) -> &'ll Type {
1300         // FIXME: use cx.layout_of(ty).llvm_type() ?
1301         let mut elem_ty = match elem_ty.sty {
1302             ty::Int(v) => Type::int_from_ty(cx, v),
1303             ty::Uint(v) => Type::uint_from_ty(cx, v),
1304             ty::Float(v) => Type::float_from_ty(cx, v),
1305             _ => unreachable!(),
1306         };
1307         while no_pointers > 0 {
1308             elem_ty = elem_ty.ptr_to();
1309             no_pointers -= 1;
1310         }
1311         Type::vector(elem_ty, vec_len as u64)
1312     }
1313
1314
1315     if name == "simd_gather"  {
1316         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1317         //             mask: <N x i{M}>) -> <N x T>
1318         // * N: number of elements in the input vectors
1319         // * T: type of the element to load
1320         // * M: any integer width is supported, will be truncated to i1
1321
1322         // All types must be simd vector types
1323         require_simd!(in_ty, "first");
1324         require_simd!(arg_tys[1], "second");
1325         require_simd!(arg_tys[2], "third");
1326         require_simd!(ret_ty, "return");
1327
1328         // Of the same length:
1329         require!(in_len == arg_tys[1].simd_size(tcx),
1330                  "expected {} argument with length {} (same as input type `{}`), \
1331                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1332                  arg_tys[1].simd_size(tcx));
1333         require!(in_len == arg_tys[2].simd_size(tcx),
1334                  "expected {} argument with length {} (same as input type `{}`), \
1335                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1336                  arg_tys[2].simd_size(tcx));
1337
1338         // The return type must match the first argument type
1339         require!(ret_ty == in_ty,
1340                  "expected return type `{}`, found `{}`",
1341                  in_ty, ret_ty);
1342
1343         // This counts how many pointers
1344         fn ptr_count(t: ty::Ty) -> usize {
1345             match t.sty {
1346                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1347                 _ => 0,
1348             }
1349         }
1350
1351         // Non-ptr type
1352         fn non_ptr(t: ty::Ty) -> ty::Ty {
1353             match t.sty {
1354                 ty::RawPtr(p) => non_ptr(p.ty),
1355                 _ => t,
1356             }
1357         }
1358
1359         // The second argument must be a simd vector with an element type that's a pointer
1360         // to the element type of the first argument
1361         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1362             ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1363                                                    non_ptr(arg_tys[1].simd_type(tcx))),
1364             _ => {
1365                 require!(false, "expected element type `{}` of second argument `{}` \
1366                                  to be a pointer to the element type `{}` of the first \
1367                                  argument `{}`, found `{}` != `*_ {}`",
1368                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1369                          arg_tys[1].simd_type(tcx).sty, in_elem);
1370                 unreachable!();
1371             }
1372         };
1373         assert!(pointer_count > 0);
1374         assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx)));
1375         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1376
1377         // The element type of the third argument must be a signed integer type of any width:
1378         match arg_tys[2].simd_type(tcx).sty {
1379             ty::Int(_) => (),
1380             _ => {
1381                 require!(false, "expected element type `{}` of third argument `{}` \
1382                                  to be a signed integer type",
1383                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1384             }
1385         }
1386
1387         // Alignment of T, must be a constant integer value:
1388         let alignment_ty = Type::i32(bx.cx);
1389         let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1390
1391         // Truncate the mask vector to a vector of i1s:
1392         let (mask, mask_ty) = {
1393             let i1 = Type::i1(bx.cx);
1394             let i1xn = Type::vector(i1, in_len as u64);
1395             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1396         };
1397
1398         // Type of the vector of pointers:
1399         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1400         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1401
1402         // Type of the vector of elements:
1403         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1404         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1405
1406         let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1407                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1408         let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1409                                      Type::func(&[llvm_pointer_vec_ty, alignment_ty, mask_ty,
1410                                                   llvm_elem_vec_ty], llvm_elem_vec_ty));
1411         llvm::SetUnnamedAddr(f, false);
1412         let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1413                         None);
1414         return Ok(v);
1415     }
1416
1417     if name == "simd_scatter"  {
1418         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1419         //             mask: <N x i{M}>) -> ()
1420         // * N: number of elements in the input vectors
1421         // * T: type of the element to load
1422         // * M: any integer width is supported, will be truncated to i1
1423
1424         // All types must be simd vector types
1425         require_simd!(in_ty, "first");
1426         require_simd!(arg_tys[1], "second");
1427         require_simd!(arg_tys[2], "third");
1428
1429         // Of the same length:
1430         require!(in_len == arg_tys[1].simd_size(tcx),
1431                  "expected {} argument with length {} (same as input type `{}`), \
1432                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1433                  arg_tys[1].simd_size(tcx));
1434         require!(in_len == arg_tys[2].simd_size(tcx),
1435                  "expected {} argument with length {} (same as input type `{}`), \
1436                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1437                  arg_tys[2].simd_size(tcx));
1438
1439         // This counts how many pointers
1440         fn ptr_count(t: ty::Ty) -> usize {
1441             match t.sty {
1442                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1443                 _ => 0,
1444             }
1445         }
1446
1447         // Non-ptr type
1448         fn non_ptr(t: ty::Ty) -> ty::Ty {
1449             match t.sty {
1450                 ty::RawPtr(p) => non_ptr(p.ty),
1451                 _ => t,
1452             }
1453         }
1454
1455         // The second argument must be a simd vector with an element type that's a pointer
1456         // to the element type of the first argument
1457         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1458             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1459                 => (ptr_count(arg_tys[1].simd_type(tcx)),
1460                     non_ptr(arg_tys[1].simd_type(tcx))),
1461             _ => {
1462                 require!(false, "expected element type `{}` of second argument `{}` \
1463                                  to be a pointer to the element type `{}` of the first \
1464                                  argument `{}`, found `{}` != `*mut {}`",
1465                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1466                          arg_tys[1].simd_type(tcx).sty, in_elem);
1467                 unreachable!();
1468             }
1469         };
1470         assert!(pointer_count > 0);
1471         assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx)));
1472         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1473
1474         // The element type of the third argument must be a signed integer type of any width:
1475         match arg_tys[2].simd_type(tcx).sty {
1476             ty::Int(_) => (),
1477             _ => {
1478                 require!(false, "expected element type `{}` of third argument `{}` \
1479                                  to be a signed integer type",
1480                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1481             }
1482         }
1483
1484         // Alignment of T, must be a constant integer value:
1485         let alignment_ty = Type::i32(bx.cx);
1486         let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1487
1488         // Truncate the mask vector to a vector of i1s:
1489         let (mask, mask_ty) = {
1490             let i1 = Type::i1(bx.cx);
1491             let i1xn = Type::vector(i1, in_len as u64);
1492             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1493         };
1494
1495         let ret_t = Type::void(bx.cx);
1496
1497         // Type of the vector of pointers:
1498         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1499         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1500
1501         // Type of the vector of elements:
1502         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1503         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1504
1505         let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1506                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1507         let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1508                                      Type::func(&[llvm_elem_vec_ty,
1509                                                   llvm_pointer_vec_ty,
1510                                                   alignment_ty,
1511                                                   mask_ty], ret_t));
1512         llvm::SetUnnamedAddr(f, false);
1513         let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1514                         None);
1515         return Ok(v);
1516     }
1517
1518     macro_rules! arith_red {
1519         ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1520             if name == $name {
1521                 require!(ret_ty == in_elem,
1522                          "expected return type `{}` (element of input `{}`), found `{}`",
1523                          in_elem, in_ty, ret_ty);
1524                 return match in_elem.sty {
1525                     ty::Int(_) | ty::Uint(_) => {
1526                         let r = bx.$integer_reduce(args[0].immediate());
1527                         if $ordered {
1528                             // if overflow occurs, the result is the
1529                             // mathematical result modulo 2^n:
1530                             if name.contains("mul") {
1531                                 Ok(bx.mul(args[1].immediate(), r))
1532                             } else {
1533                                 Ok(bx.add(args[1].immediate(), r))
1534                             }
1535                         } else {
1536                             Ok(bx.$integer_reduce(args[0].immediate()))
1537                         }
1538                     },
1539                     ty::Float(f) => {
1540                         // ordered arithmetic reductions take an accumulator
1541                         let acc = if $ordered {
1542                             let acc = args[1].immediate();
1543                             // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1544                             // * if the accumulator of the fadd isn't 0, incorrect
1545                             //   code is generated
1546                             // * if the accumulator of the fmul isn't 1, incorrect
1547                             //   code is generated
1548                             match const_get_real(acc) {
1549                                 None => return_error!("accumulator of {} is not a constant", $name),
1550                                 Some((v, loses_info)) => {
1551                                     if $name.contains("mul") && v != 1.0_f64 {
1552                                         return_error!("accumulator of {} is not 1.0", $name);
1553                                     } else if $name.contains("add") && v != 0.0_f64 {
1554                                         return_error!("accumulator of {} is not 0.0", $name);
1555                                     } else if loses_info {
1556                                         return_error!("accumulator of {} loses information", $name);
1557                                     }
1558                                 }
1559                             }
1560                             acc
1561                         } else {
1562                             // unordered arithmetic reductions do not:
1563                             match f.bit_width() {
1564                                 32 => C_undef(Type::f32(bx.cx)),
1565                                 64 => C_undef(Type::f64(bx.cx)),
1566                                 v => {
1567                                     return_error!(r#"
1568 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1569                                         $name, in_ty, in_elem, v, ret_ty
1570                                     )
1571                                 }
1572                             }
1573
1574                         };
1575                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1576                     }
1577                     _ => {
1578                         return_error!(
1579                             "unsupported {} from `{}` with element `{}` to `{}`",
1580                             $name, in_ty, in_elem, ret_ty
1581                         )
1582                     },
1583                 }
1584             }
1585         }
1586     }
1587
1588     arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1589     arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1590     arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1591     arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1592
1593     macro_rules! minmax_red {
1594         ($name:tt: $int_red:ident, $float_red:ident) => {
1595             if name == $name {
1596                 require!(ret_ty == in_elem,
1597                          "expected return type `{}` (element of input `{}`), found `{}`",
1598                          in_elem, in_ty, ret_ty);
1599                 return match in_elem.sty {
1600                     ty::Int(_i) => {
1601                         Ok(bx.$int_red(args[0].immediate(), true))
1602                     },
1603                     ty::Uint(_u) => {
1604                         Ok(bx.$int_red(args[0].immediate(), false))
1605                     },
1606                     ty::Float(_f) => {
1607                         Ok(bx.$float_red(args[0].immediate()))
1608                     }
1609                     _ => {
1610                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1611                                       $name, in_ty, in_elem, ret_ty)
1612                     },
1613                 }
1614             }
1615
1616         }
1617     }
1618
1619     minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1620     minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1621
1622     minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1623     minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1624
1625     macro_rules! bitwise_red {
1626         ($name:tt : $red:ident, $boolean:expr) => {
1627             if name == $name {
1628                 let input = if !$boolean {
1629                     require!(ret_ty == in_elem,
1630                              "expected return type `{}` (element of input `{}`), found `{}`",
1631                              in_elem, in_ty, ret_ty);
1632                     args[0].immediate()
1633                 } else {
1634                     match in_elem.sty {
1635                         ty::Int(_) | ty::Uint(_) => {},
1636                         _ => {
1637                             return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1638                                           $name, in_ty, in_elem, ret_ty)
1639                         }
1640                     }
1641
1642                     // boolean reductions operate on vectors of i1s:
1643                     let i1 = Type::i1(bx.cx);
1644                     let i1xn = Type::vector(i1, in_len as u64);
1645                     bx.trunc(args[0].immediate(), i1xn)
1646                 };
1647                 return match in_elem.sty {
1648                     ty::Int(_) | ty::Uint(_) => {
1649                         let r = bx.$red(input);
1650                         Ok(
1651                             if !$boolean {
1652                                 r
1653                             } else {
1654                                 bx.zext(r, Type::bool(bx.cx))
1655                             }
1656                         )
1657                     },
1658                     _ => {
1659                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1660                                       $name, in_ty, in_elem, ret_ty)
1661                     },
1662                 }
1663             }
1664         }
1665     }
1666
1667     bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1668     bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1669     bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1670     bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1671     bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1672
1673     if name == "simd_cast" {
1674         require_simd!(ret_ty, "return");
1675         let out_len = ret_ty.simd_size(tcx);
1676         require!(in_len == out_len,
1677                  "expected return type with length {} (same as input type `{}`), \
1678                   found `{}` with length {}",
1679                  in_len, in_ty,
1680                  ret_ty, out_len);
1681         // casting cares about nominal type, not just structural type
1682         let out_elem = ret_ty.simd_type(tcx);
1683
1684         if in_elem == out_elem { return Ok(args[0].immediate()); }
1685
1686         enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1687
1688         let (in_style, in_width) = match in_elem.sty {
1689             // vectors of pointer-sized integers should've been
1690             // disallowed before here, so this unwrap is safe.
1691             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1692             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1693             ty::Float(f) => (Style::Float, f.bit_width()),
1694             _ => (Style::Unsupported, 0)
1695         };
1696         let (out_style, out_width) = match out_elem.sty {
1697             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1698             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1699             ty::Float(f) => (Style::Float, f.bit_width()),
1700             _ => (Style::Unsupported, 0)
1701         };
1702
1703         match (in_style, out_style) {
1704             (Style::Int(in_is_signed), Style::Int(_)) => {
1705                 return Ok(match in_width.cmp(&out_width) {
1706                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1707                     Ordering::Equal => args[0].immediate(),
1708                     Ordering::Less => if in_is_signed {
1709                         bx.sext(args[0].immediate(), llret_ty)
1710                     } else {
1711                         bx.zext(args[0].immediate(), llret_ty)
1712                     }
1713                 })
1714             }
1715             (Style::Int(in_is_signed), Style::Float) => {
1716                 return Ok(if in_is_signed {
1717                     bx.sitofp(args[0].immediate(), llret_ty)
1718                 } else {
1719                     bx.uitofp(args[0].immediate(), llret_ty)
1720                 })
1721             }
1722             (Style::Float, Style::Int(out_is_signed)) => {
1723                 return Ok(if out_is_signed {
1724                     bx.fptosi(args[0].immediate(), llret_ty)
1725                 } else {
1726                     bx.fptoui(args[0].immediate(), llret_ty)
1727                 })
1728             }
1729             (Style::Float, Style::Float) => {
1730                 return Ok(match in_width.cmp(&out_width) {
1731                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1732                     Ordering::Equal => args[0].immediate(),
1733                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1734                 })
1735             }
1736             _ => {/* Unsupported. Fallthrough. */}
1737         }
1738         require!(false,
1739                  "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1740                  in_ty, in_elem,
1741                  ret_ty, out_elem);
1742     }
1743     macro_rules! arith {
1744         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1745             $(if name == stringify!($name) {
1746                 match in_elem.sty {
1747                     $($(ty::$p(_))|* => {
1748                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1749                     })*
1750                     _ => {},
1751                 }
1752                 require!(false,
1753                             "unsupported operation on `{}` with element `{}`",
1754                             in_ty,
1755                             in_elem)
1756             })*
1757         }
1758     }
1759     arith! {
1760         simd_add: Uint, Int => add, Float => fadd;
1761         simd_sub: Uint, Int => sub, Float => fsub;
1762         simd_mul: Uint, Int => mul, Float => fmul;
1763         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1764         simd_rem: Uint => urem, Int => srem, Float => frem;
1765         simd_shl: Uint, Int => shl;
1766         simd_shr: Uint => lshr, Int => ashr;
1767         simd_and: Uint, Int => and;
1768         simd_or: Uint, Int => or;
1769         simd_xor: Uint, Int => xor;
1770         simd_fmax: Float => maxnum;
1771         simd_fmin: Float => minnum;
1772     }
1773     span_bug!(span, "unknown SIMD intrinsic");
1774 }
1775
1776 // Returns the width of an int Ty, and if it's signed or not
1777 // Returns None if the type is not an integer
1778 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1779 // stuffs.
1780 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1781     match ty.sty {
1782         ty::Int(t) => Some((match t {
1783             ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1784             ast::IntTy::I8 => 8,
1785             ast::IntTy::I16 => 16,
1786             ast::IntTy::I32 => 32,
1787             ast::IntTy::I64 => 64,
1788             ast::IntTy::I128 => 128,
1789         }, true)),
1790         ty::Uint(t) => Some((match t {
1791             ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1792             ast::UintTy::U8 => 8,
1793             ast::UintTy::U16 => 16,
1794             ast::UintTy::U32 => 32,
1795             ast::UintTy::U64 => 64,
1796             ast::UintTy::U128 => 128,
1797         }, false)),
1798         _ => None,
1799     }
1800 }
1801
1802 // Returns the width of a float TypeVariant
1803 // Returns None if the type is not a float
1804 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1805     match *sty {
1806         ty::Float(t) => Some(t.bit_width() as u64),
1807         _ => None,
1808     }
1809 }