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