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