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