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