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