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