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