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