]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/intrinsic.rs
Tweak move error
[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 normal = bx.append_sibling_block("normal");
456         let catchswitch = bx.append_sibling_block("catchswitch");
457         let catchpad_rust = bx.append_sibling_block("catchpad_rust");
458         let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
459         let caught = bx.append_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, catchswitch, None);
524
525         bx.switch_to_block(normal);
526         bx.ret(bx.const_i32(0));
527
528         bx.switch_to_block(catchswitch);
529         let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
530
531         // We can't use the TypeDescriptor defined in libpanic_unwind because it
532         // might be in another DLL and the SEH encoding only supports specifying
533         // a TypeDescriptor from the current module.
534         //
535         // However this isn't an issue since the MSVC runtime uses string
536         // comparison on the type name to match TypeDescriptors rather than
537         // pointer equality.
538         //
539         // So instead we generate a new TypeDescriptor in each module that uses
540         // `try` and let the linker merge duplicate definitions in the same
541         // module.
542         //
543         // When modifying, make sure that the type_name string exactly matches
544         // the one used in src/libpanic_unwind/seh.rs.
545         let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
546         let type_name = bx.const_bytes(b"rust_panic\0");
547         let type_info =
548             bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
549         let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
550         unsafe {
551             llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
552             llvm::SetUniqueComdat(bx.llmod, tydesc);
553             llvm::LLVMSetInitializer(tydesc, type_info);
554         }
555
556         // The flag value of 8 indicates that we are catching the exception by
557         // reference instead of by value. We can't use catch by value because
558         // that requires copying the exception object, which we don't support
559         // since our exception object effectively contains a Box.
560         //
561         // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
562         bx.switch_to_block(catchpad_rust);
563         let flags = bx.const_i32(8);
564         let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
565         let ptr = bx.load(bx.type_i8p(), slot, ptr_align);
566         let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
567         bx.call(catch_ty, catch_func, &[data, ptr], Some(&funclet));
568         bx.catch_ret(&funclet, caught);
569
570         // The flag value of 64 indicates a "catch-all".
571         bx.switch_to_block(catchpad_foreign);
572         let flags = bx.const_i32(64);
573         let null = bx.const_null(bx.type_i8p());
574         let funclet = bx.catch_pad(cs, &[null, flags, null]);
575         bx.call(catch_ty, catch_func, &[data, null], Some(&funclet));
576         bx.catch_ret(&funclet, caught);
577
578         bx.switch_to_block(caught);
579         bx.ret(bx.const_i32(1));
580     });
581
582     // Note that no invoke is used here because by definition this function
583     // can't panic (that's what it's catching).
584     let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
585     let i32_align = bx.tcx().data_layout.i32_align.abi;
586     bx.store(ret, dest, i32_align);
587 }
588
589 // Definition of the standard `try` function for Rust using the GNU-like model
590 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
591 // instructions).
592 //
593 // This codegen is a little surprising because we always call a shim
594 // function instead of inlining the call to `invoke` manually here. This is done
595 // because in LLVM we're only allowed to have one personality per function
596 // definition. The call to the `try` intrinsic is being inlined into the
597 // function calling it, and that function may already have other personality
598 // functions in play. By calling a shim we're guaranteed that our shim will have
599 // the right personality function.
600 fn codegen_gnu_try<'ll>(
601     bx: &mut Builder<'_, 'll, '_>,
602     try_func: &'ll Value,
603     data: &'ll Value,
604     catch_func: &'ll Value,
605     dest: &'ll Value,
606 ) {
607     let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
608         // Codegens the shims described above:
609         //
610         //   bx:
611         //      invoke %try_func(%data) normal %normal unwind %catch
612         //
613         //   normal:
614         //      ret 0
615         //
616         //   catch:
617         //      (%ptr, _) = landingpad
618         //      call %catch_func(%data, %ptr)
619         //      ret 1
620         let then = bx.append_sibling_block("then");
621         let catch = bx.append_sibling_block("catch");
622
623         let try_func = llvm::get_param(bx.llfn(), 0);
624         let data = llvm::get_param(bx.llfn(), 1);
625         let catch_func = llvm::get_param(bx.llfn(), 2);
626         let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
627         bx.invoke(try_func_ty, try_func, &[data], then, catch, None);
628
629         bx.switch_to_block(then);
630         bx.ret(bx.const_i32(0));
631
632         // Type indicator for the exception being thrown.
633         //
634         // The first value in this tuple is a pointer to the exception object
635         // being thrown.  The second value is a "selector" indicating which of
636         // the landing pad clauses the exception's type had been matched to.
637         // rust_try ignores the selector.
638         bx.switch_to_block(catch);
639         let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
640         let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
641         let tydesc = bx.const_null(bx.type_i8p());
642         bx.add_clause(vals, tydesc);
643         let ptr = bx.extract_value(vals, 0);
644         let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
645         bx.call(catch_ty, catch_func, &[data, ptr], None);
646         bx.ret(bx.const_i32(1));
647     });
648
649     // Note that no invoke is used here because by definition this function
650     // can't panic (that's what it's catching).
651     let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
652     let i32_align = bx.tcx().data_layout.i32_align.abi;
653     bx.store(ret, dest, i32_align);
654 }
655
656 // Variant of codegen_gnu_try used for emscripten where Rust panics are
657 // implemented using C++ exceptions. Here we use exceptions of a specific type
658 // (`struct rust_panic`) to represent Rust panics.
659 fn codegen_emcc_try<'ll>(
660     bx: &mut Builder<'_, 'll, '_>,
661     try_func: &'ll Value,
662     data: &'ll Value,
663     catch_func: &'ll Value,
664     dest: &'ll Value,
665 ) {
666     let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
667         // Codegens the shims described above:
668         //
669         //   bx:
670         //      invoke %try_func(%data) normal %normal unwind %catch
671         //
672         //   normal:
673         //      ret 0
674         //
675         //   catch:
676         //      (%ptr, %selector) = landingpad
677         //      %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
678         //      %is_rust_panic = %selector == %rust_typeid
679         //      %catch_data = alloca { i8*, i8 }
680         //      %catch_data[0] = %ptr
681         //      %catch_data[1] = %is_rust_panic
682         //      call %catch_func(%data, %catch_data)
683         //      ret 1
684         let then = bx.append_sibling_block("then");
685         let catch = bx.append_sibling_block("catch");
686
687         let try_func = llvm::get_param(bx.llfn(), 0);
688         let data = llvm::get_param(bx.llfn(), 1);
689         let catch_func = llvm::get_param(bx.llfn(), 2);
690         let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
691         bx.invoke(try_func_ty, try_func, &[data], then, catch, None);
692
693         bx.switch_to_block(then);
694         bx.ret(bx.const_i32(0));
695
696         // Type indicator for the exception being thrown.
697         //
698         // The first value in this tuple is a pointer to the exception object
699         // being thrown.  The second value is a "selector" indicating which of
700         // the landing pad clauses the exception's type had been matched to.
701         bx.switch_to_block(catch);
702         let tydesc = bx.eh_catch_typeinfo();
703         let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
704         let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
705         bx.add_clause(vals, tydesc);
706         bx.add_clause(vals, bx.const_null(bx.type_i8p()));
707         let ptr = bx.extract_value(vals, 0);
708         let selector = bx.extract_value(vals, 1);
709
710         // Check if the typeid we got is the one for a Rust panic.
711         let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[tydesc]);
712         let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
713         let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
714
715         // We need to pass two values to catch_func (ptr and is_rust_panic), so
716         // create an alloca and pass a pointer to that.
717         let ptr_align = bx.tcx().data_layout.pointer_align.abi;
718         let i8_align = bx.tcx().data_layout.i8_align.abi;
719         let catch_data_type = bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false);
720         let catch_data = bx.alloca(catch_data_type, ptr_align);
721         let catch_data_0 =
722             bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(0)]);
723         bx.store(ptr, catch_data_0, ptr_align);
724         let catch_data_1 =
725             bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(1)]);
726         bx.store(is_rust_panic, catch_data_1, i8_align);
727         let catch_data = bx.bitcast(catch_data, bx.type_i8p());
728
729         let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
730         bx.call(catch_ty, catch_func, &[data, catch_data], None);
731         bx.ret(bx.const_i32(1));
732     });
733
734     // Note that no invoke is used here because by definition this function
735     // can't panic (that's what it's catching).
736     let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
737     let i32_align = bx.tcx().data_layout.i32_align.abi;
738     bx.store(ret, dest, i32_align);
739 }
740
741 // Helper function to give a Block to a closure to codegen a shim function.
742 // This is currently primarily used for the `try` intrinsic functions above.
743 fn gen_fn<'ll, 'tcx>(
744     cx: &CodegenCx<'ll, 'tcx>,
745     name: &str,
746     rust_fn_sig: ty::PolyFnSig<'tcx>,
747     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
748 ) -> (&'ll Type, &'ll Value) {
749     let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
750     let llty = fn_abi.llvm_type(cx);
751     let llfn = cx.declare_fn(name, fn_abi);
752     cx.set_frame_pointer_type(llfn);
753     cx.apply_target_cpu_attr(llfn);
754     // FIXME(eddyb) find a nicer way to do this.
755     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
756     let llbb = Builder::append_block(cx, llfn, "entry-block");
757     let bx = Builder::build(cx, llbb);
758     codegen(bx);
759     (llty, llfn)
760 }
761
762 // Helper function used to get a handle to the `__rust_try` function used to
763 // catch exceptions.
764 //
765 // This function is only generated once and is then cached.
766 fn get_rust_try_fn<'ll, 'tcx>(
767     cx: &CodegenCx<'ll, 'tcx>,
768     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
769 ) -> (&'ll Type, &'ll Value) {
770     if let Some(llfn) = cx.rust_try_fn.get() {
771         return llfn;
772     }
773
774     // Define the type up front for the signature of the rust_try function.
775     let tcx = cx.tcx;
776     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
777     // `unsafe fn(*mut i8) -> ()`
778     let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
779         iter::once(i8p),
780         tcx.mk_unit(),
781         false,
782         hir::Unsafety::Unsafe,
783         Abi::Rust,
784     )));
785     // `unsafe fn(*mut i8, *mut i8) -> ()`
786     let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
787         [i8p, i8p].iter().cloned(),
788         tcx.mk_unit(),
789         false,
790         hir::Unsafety::Unsafe,
791         Abi::Rust,
792     )));
793     // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
794     let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
795         [try_fn_ty, i8p, catch_fn_ty].into_iter(),
796         tcx.types.i32,
797         false,
798         hir::Unsafety::Unsafe,
799         Abi::Rust,
800     ));
801     let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
802     cx.rust_try_fn.set(Some(rust_try));
803     rust_try
804 }
805
806 fn generic_simd_intrinsic<'ll, 'tcx>(
807     bx: &mut Builder<'_, 'll, 'tcx>,
808     name: Symbol,
809     callee_ty: Ty<'tcx>,
810     args: &[OperandRef<'tcx, &'ll Value>],
811     ret_ty: Ty<'tcx>,
812     llret_ty: &'ll Type,
813     span: Span,
814 ) -> Result<&'ll Value, ()> {
815     // macros for error handling:
816     macro_rules! emit_error {
817         ($msg: tt) => {
818             emit_error!($msg, )
819         };
820         ($msg: tt, $($fmt: tt)*) => {
821             span_invalid_monomorphization_error(
822                 bx.sess(), span,
823                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
824                          name, $($fmt)*));
825         }
826     }
827
828     macro_rules! return_error {
829         ($($fmt: tt)*) => {
830             {
831                 emit_error!($($fmt)*);
832                 return Err(());
833             }
834         }
835     }
836
837     macro_rules! require {
838         ($cond: expr, $($fmt: tt)*) => {
839             if !$cond {
840                 return_error!($($fmt)*);
841             }
842         };
843     }
844
845     macro_rules! require_simd {
846         ($ty: expr, $position: expr) => {
847             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
848         };
849     }
850
851     let tcx = bx.tcx();
852     let sig =
853         tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
854     let arg_tys = sig.inputs();
855
856     if name == sym::simd_select_bitmask {
857         require_simd!(arg_tys[1], "argument");
858         let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
859
860         let expected_int_bits = (len.max(8) - 1).next_power_of_two();
861         let expected_bytes = len / 8 + ((len % 8 > 0) as u64);
862
863         let mask_ty = arg_tys[0];
864         let mask = match mask_ty.kind() {
865             ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
866             ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
867             ty::Array(elem, len)
868                 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
869                     && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
870                         == Some(expected_bytes) =>
871             {
872                 let place = PlaceRef::alloca(bx, args[0].layout);
873                 args[0].val.store(bx, place);
874                 let int_ty = bx.type_ix(expected_bytes * 8);
875                 let ptr = bx.pointercast(place.llval, bx.cx.type_ptr_to(int_ty));
876                 bx.load(int_ty, ptr, Align::ONE)
877             }
878             _ => return_error!(
879                 "invalid bitmask `{}`, expected `u{}` or `[u8; {}]`",
880                 mask_ty,
881                 expected_int_bits,
882                 expected_bytes
883             ),
884         };
885
886         let i1 = bx.type_i1();
887         let im = bx.type_ix(len);
888         let i1xn = bx.type_vector(i1, len);
889         let m_im = bx.trunc(mask, im);
890         let m_i1s = bx.bitcast(m_im, i1xn);
891         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
892     }
893
894     // every intrinsic below takes a SIMD vector as its first argument
895     require_simd!(arg_tys[0], "input");
896     let in_ty = arg_tys[0];
897
898     let comparison = match name {
899         sym::simd_eq => Some(hir::BinOpKind::Eq),
900         sym::simd_ne => Some(hir::BinOpKind::Ne),
901         sym::simd_lt => Some(hir::BinOpKind::Lt),
902         sym::simd_le => Some(hir::BinOpKind::Le),
903         sym::simd_gt => Some(hir::BinOpKind::Gt),
904         sym::simd_ge => Some(hir::BinOpKind::Ge),
905         _ => None,
906     };
907
908     let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
909     if let Some(cmp_op) = comparison {
910         require_simd!(ret_ty, "return");
911
912         let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
913         require!(
914             in_len == out_len,
915             "expected return type with length {} (same as input type `{}`), \
916              found `{}` with length {}",
917             in_len,
918             in_ty,
919             ret_ty,
920             out_len
921         );
922         require!(
923             bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
924             "expected return type with integer elements, found `{}` with non-integer `{}`",
925             ret_ty,
926             out_ty
927         );
928
929         return Ok(compare_simd_types(
930             bx,
931             args[0].immediate(),
932             args[1].immediate(),
933             in_elem,
934             llret_ty,
935             cmp_op,
936         ));
937     }
938
939     if let Some(stripped) = name.as_str().strip_prefix("simd_shuffle") {
940         // If this intrinsic is the older "simd_shuffleN" form, simply parse the integer.
941         // If there is no suffix, use the index array length.
942         let n: u64 = if stripped.is_empty() {
943             // Make sure this is actually an array, since typeck only checks the length-suffixed
944             // version of this intrinsic.
945             match args[2].layout.ty.kind() {
946                 ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => {
947                     len.try_eval_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(|| {
948                         span_bug!(span, "could not evaluate shuffle index array length")
949                     })
950                 }
951                 _ => return_error!(
952                     "simd_shuffle index must be an array of `u32`, got `{}`",
953                     args[2].layout.ty
954                 ),
955             }
956         } else {
957             stripped.parse().unwrap_or_else(|_| {
958                 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
959             })
960         };
961
962         require_simd!(ret_ty, "return");
963         let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
964         require!(
965             out_len == n,
966             "expected return type of length {}, found `{}` with length {}",
967             n,
968             ret_ty,
969             out_len
970         );
971         require!(
972             in_elem == out_ty,
973             "expected return element type `{}` (element of input `{}`), \
974              found `{}` with element type `{}`",
975             in_elem,
976             in_ty,
977             ret_ty,
978             out_ty
979         );
980
981         let total_len = u128::from(in_len) * 2;
982
983         let vector = args[2].immediate();
984
985         let indices: Option<Vec<_>> = (0..n)
986             .map(|i| {
987                 let arg_idx = i;
988                 let val = bx.const_get_elt(vector, i as u64);
989                 match bx.const_to_opt_u128(val, true) {
990                     None => {
991                         emit_error!("shuffle index #{} is not a constant", arg_idx);
992                         None
993                     }
994                     Some(idx) if idx >= total_len => {
995                         emit_error!(
996                             "shuffle index #{} is out of bounds (limit {})",
997                             arg_idx,
998                             total_len
999                         );
1000                         None
1001                     }
1002                     Some(idx) => Some(bx.const_i32(idx as i32)),
1003                 }
1004             })
1005             .collect();
1006         let Some(indices) = indices else {
1007             return Ok(bx.const_null(llret_ty));
1008         };
1009
1010         return Ok(bx.shuffle_vector(
1011             args[0].immediate(),
1012             args[1].immediate(),
1013             bx.const_vector(&indices),
1014         ));
1015     }
1016
1017     if name == sym::simd_insert {
1018         require!(
1019             in_elem == arg_tys[2],
1020             "expected inserted type `{}` (element of input `{}`), found `{}`",
1021             in_elem,
1022             in_ty,
1023             arg_tys[2]
1024         );
1025         return Ok(bx.insert_element(
1026             args[0].immediate(),
1027             args[2].immediate(),
1028             args[1].immediate(),
1029         ));
1030     }
1031     if name == sym::simd_extract {
1032         require!(
1033             ret_ty == in_elem,
1034             "expected return type `{}` (element of input `{}`), found `{}`",
1035             in_elem,
1036             in_ty,
1037             ret_ty
1038         );
1039         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1040     }
1041
1042     if name == sym::simd_select {
1043         let m_elem_ty = in_elem;
1044         let m_len = in_len;
1045         require_simd!(arg_tys[1], "argument");
1046         let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1047         require!(
1048             m_len == v_len,
1049             "mismatched lengths: mask length `{}` != other vector length `{}`",
1050             m_len,
1051             v_len
1052         );
1053         match m_elem_ty.kind() {
1054             ty::Int(_) => {}
1055             _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1056         }
1057         // truncate the mask to a vector of i1s
1058         let i1 = bx.type_i1();
1059         let i1xn = bx.type_vector(i1, m_len as u64);
1060         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1061         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1062     }
1063
1064     if name == sym::simd_bitmask {
1065         // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1066         // vector mask and returns the most significant bit (MSB) of each lane in the form
1067         // of either:
1068         // * an unsigned integer
1069         // * an array of `u8`
1070         // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
1071         //
1072         // The bit order of the result depends on the byte endianness, LSB-first for little
1073         // endian and MSB-first for big endian.
1074         let expected_int_bits = in_len.max(8);
1075         let expected_bytes = expected_int_bits / 8 + ((expected_int_bits % 8 > 0) as u64);
1076
1077         // Integer vector <i{in_bitwidth} x in_len>:
1078         let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1079             ty::Int(i) => (
1080                 args[0].immediate(),
1081                 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1082             ),
1083             ty::Uint(i) => (
1084                 args[0].immediate(),
1085                 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1086             ),
1087             _ => return_error!(
1088                 "vector argument `{}`'s element type `{}`, expected integer element type",
1089                 in_ty,
1090                 in_elem
1091             ),
1092         };
1093
1094         // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1095         let shift_indices =
1096             vec![
1097                 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1098                 in_len as _
1099             ];
1100         let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1101         // Truncate vector to an <i1 x N>
1102         let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1103         // Bitcast <i1 x N> to iN:
1104         let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1105
1106         match ret_ty.kind() {
1107             ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
1108                 // Zero-extend iN to the bitmask type:
1109                 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1110             }
1111             ty::Array(elem, len)
1112                 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1113                     && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
1114                         == Some(expected_bytes) =>
1115             {
1116                 // Zero-extend iN to the array lengh:
1117                 let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
1118
1119                 // Convert the integer to a byte array
1120                 let ptr = bx.alloca(bx.type_ix(expected_bytes * 8), Align::ONE);
1121                 bx.store(ze, ptr, Align::ONE);
1122                 let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
1123                 let ptr = bx.pointercast(ptr, bx.cx.type_ptr_to(array_ty));
1124                 return Ok(bx.load(array_ty, ptr, Align::ONE));
1125             }
1126             _ => return_error!(
1127                 "cannot return `{}`, expected `u{}` or `[u8; {}]`",
1128                 ret_ty,
1129                 expected_int_bits,
1130                 expected_bytes
1131             ),
1132         }
1133     }
1134
1135     fn simd_simple_float_intrinsic<'ll, 'tcx>(
1136         name: Symbol,
1137         in_elem: Ty<'_>,
1138         in_ty: Ty<'_>,
1139         in_len: u64,
1140         bx: &mut Builder<'_, 'll, 'tcx>,
1141         span: Span,
1142         args: &[OperandRef<'tcx, &'ll Value>],
1143     ) -> Result<&'ll Value, ()> {
1144         macro_rules! emit_error {
1145             ($msg: tt) => {
1146                 emit_error!($msg, )
1147             };
1148             ($msg: tt, $($fmt: tt)*) => {
1149                 span_invalid_monomorphization_error(
1150                     bx.sess(), span,
1151                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1152                              name, $($fmt)*));
1153             }
1154         }
1155         macro_rules! return_error {
1156             ($($fmt: tt)*) => {
1157                 {
1158                     emit_error!($($fmt)*);
1159                     return Err(());
1160                 }
1161             }
1162         }
1163
1164         let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1165             let elem_ty = bx.cx.type_float_from_ty(*f);
1166             match f.bit_width() {
1167                 32 => ("f32", elem_ty),
1168                 64 => ("f64", elem_ty),
1169                 _ => {
1170                     return_error!(
1171                         "unsupported element type `{}` of floating-point vector `{}`",
1172                         f.name_str(),
1173                         in_ty
1174                     );
1175                 }
1176             }
1177         } else {
1178             return_error!("`{}` is not a floating-point type", in_ty);
1179         };
1180
1181         let vec_ty = bx.type_vector(elem_ty, in_len);
1182
1183         let (intr_name, fn_ty) = match name {
1184             sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1185             sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1186             sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1187             sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1188             sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1189             sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1190             sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1191             sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1192             sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1193             sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1194             sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1195             sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1196             sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1197             sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1198             sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1199             sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1200             _ => return_error!("unrecognized intrinsic `{}`", name),
1201         };
1202         let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1203         let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty);
1204         let c =
1205             bx.call(fn_ty, f, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1206         Ok(c)
1207     }
1208
1209     if std::matches!(
1210         name,
1211         sym::simd_ceil
1212             | sym::simd_fabs
1213             | sym::simd_fcos
1214             | sym::simd_fexp2
1215             | sym::simd_fexp
1216             | sym::simd_flog10
1217             | sym::simd_flog2
1218             | sym::simd_flog
1219             | sym::simd_floor
1220             | sym::simd_fma
1221             | sym::simd_fpow
1222             | sym::simd_fpowi
1223             | sym::simd_fsin
1224             | sym::simd_fsqrt
1225             | sym::simd_round
1226             | sym::simd_trunc
1227     ) {
1228         return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1229     }
1230
1231     // FIXME: use:
1232     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1233     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1234     fn llvm_vector_str(
1235         elem_ty: Ty<'_>,
1236         vec_len: u64,
1237         no_pointers: usize,
1238         bx: &Builder<'_, '_, '_>,
1239     ) -> String {
1240         let p0s: String = "p0".repeat(no_pointers);
1241         match *elem_ty.kind() {
1242             ty::Int(v) => format!(
1243                 "v{}{}i{}",
1244                 vec_len,
1245                 p0s,
1246                 // Normalize to prevent crash if v: IntTy::Isize
1247                 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1248             ),
1249             ty::Uint(v) => format!(
1250                 "v{}{}i{}",
1251                 vec_len,
1252                 p0s,
1253                 // Normalize to prevent crash if v: UIntTy::Usize
1254                 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1255             ),
1256             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1257             _ => unreachable!(),
1258         }
1259     }
1260
1261     fn llvm_vector_ty<'ll>(
1262         cx: &CodegenCx<'ll, '_>,
1263         elem_ty: Ty<'_>,
1264         vec_len: u64,
1265         mut no_pointers: usize,
1266     ) -> &'ll Type {
1267         // FIXME: use cx.layout_of(ty).llvm_type() ?
1268         let mut elem_ty = match *elem_ty.kind() {
1269             ty::Int(v) => cx.type_int_from_ty(v),
1270             ty::Uint(v) => cx.type_uint_from_ty(v),
1271             ty::Float(v) => cx.type_float_from_ty(v),
1272             _ => unreachable!(),
1273         };
1274         while no_pointers > 0 {
1275             elem_ty = cx.type_ptr_to(elem_ty);
1276             no_pointers -= 1;
1277         }
1278         cx.type_vector(elem_ty, vec_len)
1279     }
1280
1281     if name == sym::simd_gather {
1282         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1283         //             mask: <N x i{M}>) -> <N x T>
1284         // * N: number of elements in the input vectors
1285         // * T: type of the element to load
1286         // * M: any integer width is supported, will be truncated to i1
1287
1288         // All types must be simd vector types
1289         require_simd!(in_ty, "first");
1290         require_simd!(arg_tys[1], "second");
1291         require_simd!(arg_tys[2], "third");
1292         require_simd!(ret_ty, "return");
1293
1294         // Of the same length:
1295         let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1296         let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1297         require!(
1298             in_len == out_len,
1299             "expected {} argument with length {} (same as input type `{}`), \
1300              found `{}` with length {}",
1301             "second",
1302             in_len,
1303             in_ty,
1304             arg_tys[1],
1305             out_len
1306         );
1307         require!(
1308             in_len == out_len2,
1309             "expected {} argument with length {} (same as input type `{}`), \
1310              found `{}` with length {}",
1311             "third",
1312             in_len,
1313             in_ty,
1314             arg_tys[2],
1315             out_len2
1316         );
1317
1318         // The return type must match the first argument type
1319         require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1320
1321         // This counts how many pointers
1322         fn ptr_count(t: Ty<'_>) -> usize {
1323             match t.kind() {
1324                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1325                 _ => 0,
1326             }
1327         }
1328
1329         // Non-ptr type
1330         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1331             match t.kind() {
1332                 ty::RawPtr(p) => non_ptr(p.ty),
1333                 _ => t,
1334             }
1335         }
1336
1337         // The second argument must be a simd vector with an element type that's a pointer
1338         // to the element type of the first argument
1339         let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1340         let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1341         let (pointer_count, underlying_ty) = match element_ty1.kind() {
1342             ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1343             _ => {
1344                 require!(
1345                     false,
1346                     "expected element type `{}` of second argument `{}` \
1347                         to be a pointer to the element type `{}` of the first \
1348                         argument `{}`, found `{}` != `*_ {}`",
1349                     element_ty1,
1350                     arg_tys[1],
1351                     in_elem,
1352                     in_ty,
1353                     element_ty1,
1354                     in_elem
1355                 );
1356                 unreachable!();
1357             }
1358         };
1359         assert!(pointer_count > 0);
1360         assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1361         assert_eq!(underlying_ty, non_ptr(element_ty0));
1362
1363         // The element type of the third argument must be a signed integer type of any width:
1364         let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1365         match element_ty2.kind() {
1366             ty::Int(_) => (),
1367             _ => {
1368                 require!(
1369                     false,
1370                     "expected element type `{}` of third argument `{}` \
1371                                  to be a signed integer type",
1372                     element_ty2,
1373                     arg_tys[2]
1374                 );
1375             }
1376         }
1377
1378         // Alignment of T, must be a constant integer value:
1379         let alignment_ty = bx.type_i32();
1380         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1381
1382         // Truncate the mask vector to a vector of i1s:
1383         let (mask, mask_ty) = {
1384             let i1 = bx.type_i1();
1385             let i1xn = bx.type_vector(i1, in_len);
1386             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1387         };
1388
1389         // Type of the vector of pointers:
1390         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1391         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1392
1393         // Type of the vector of elements:
1394         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1395         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1396
1397         let llvm_intrinsic =
1398             format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1399         let fn_ty = bx.type_func(
1400             &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1401             llvm_elem_vec_ty,
1402         );
1403         let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1404         let v =
1405             bx.call(fn_ty, f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1406         return Ok(v);
1407     }
1408
1409     if name == sym::simd_scatter {
1410         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1411         //             mask: <N x i{M}>) -> ()
1412         // * N: number of elements in the input vectors
1413         // * T: type of the element to load
1414         // * M: any integer width is supported, will be truncated to i1
1415
1416         // All types must be simd vector types
1417         require_simd!(in_ty, "first");
1418         require_simd!(arg_tys[1], "second");
1419         require_simd!(arg_tys[2], "third");
1420
1421         // Of the same length:
1422         let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1423         let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1424         require!(
1425             in_len == element_len1,
1426             "expected {} argument with length {} (same as input type `{}`), \
1427             found `{}` with length {}",
1428             "second",
1429             in_len,
1430             in_ty,
1431             arg_tys[1],
1432             element_len1
1433         );
1434         require!(
1435             in_len == element_len2,
1436             "expected {} argument with length {} (same as input type `{}`), \
1437             found `{}` with length {}",
1438             "third",
1439             in_len,
1440             in_ty,
1441             arg_tys[2],
1442             element_len2
1443         );
1444
1445         // This counts how many pointers
1446         fn ptr_count(t: Ty<'_>) -> usize {
1447             match t.kind() {
1448                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1449                 _ => 0,
1450             }
1451         }
1452
1453         // Non-ptr type
1454         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1455             match t.kind() {
1456                 ty::RawPtr(p) => non_ptr(p.ty),
1457                 _ => t,
1458             }
1459         }
1460
1461         // The second argument must be a simd vector with an element type that's a pointer
1462         // to the element type of the first argument
1463         let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1464         let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1465         let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1466         let (pointer_count, underlying_ty) = match element_ty1.kind() {
1467             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1468                 (ptr_count(element_ty1), non_ptr(element_ty1))
1469             }
1470             _ => {
1471                 require!(
1472                     false,
1473                     "expected element type `{}` of second argument `{}` \
1474                         to be a pointer to the element type `{}` of the first \
1475                         argument `{}`, found `{}` != `*mut {}`",
1476                     element_ty1,
1477                     arg_tys[1],
1478                     in_elem,
1479                     in_ty,
1480                     element_ty1,
1481                     in_elem
1482                 );
1483                 unreachable!();
1484             }
1485         };
1486         assert!(pointer_count > 0);
1487         assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1488         assert_eq!(underlying_ty, non_ptr(element_ty0));
1489
1490         // The element type of the third argument must be a signed integer type of any width:
1491         match element_ty2.kind() {
1492             ty::Int(_) => (),
1493             _ => {
1494                 require!(
1495                     false,
1496                     "expected element type `{}` of third argument `{}` \
1497                          be a signed integer type",
1498                     element_ty2,
1499                     arg_tys[2]
1500                 );
1501             }
1502         }
1503
1504         // Alignment of T, must be a constant integer value:
1505         let alignment_ty = bx.type_i32();
1506         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1507
1508         // Truncate the mask vector to a vector of i1s:
1509         let (mask, mask_ty) = {
1510             let i1 = bx.type_i1();
1511             let i1xn = bx.type_vector(i1, in_len);
1512             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1513         };
1514
1515         let ret_t = bx.type_void();
1516
1517         // Type of the vector of pointers:
1518         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1519         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1520
1521         // Type of the vector of elements:
1522         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1523         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1524
1525         let llvm_intrinsic =
1526             format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1527         let fn_ty =
1528             bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
1529         let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1530         let v =
1531             bx.call(fn_ty, f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1532         return Ok(v);
1533     }
1534
1535     macro_rules! arith_red {
1536         ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1537          $identity:expr) => {
1538             if name == sym::$name {
1539                 require!(
1540                     ret_ty == in_elem,
1541                     "expected return type `{}` (element of input `{}`), found `{}`",
1542                     in_elem,
1543                     in_ty,
1544                     ret_ty
1545                 );
1546                 return match in_elem.kind() {
1547                     ty::Int(_) | ty::Uint(_) => {
1548                         let r = bx.$integer_reduce(args[0].immediate());
1549                         if $ordered {
1550                             // if overflow occurs, the result is the
1551                             // mathematical result modulo 2^n:
1552                             Ok(bx.$op(args[1].immediate(), r))
1553                         } else {
1554                             Ok(bx.$integer_reduce(args[0].immediate()))
1555                         }
1556                     }
1557                     ty::Float(f) => {
1558                         let acc = if $ordered {
1559                             // ordered arithmetic reductions take an accumulator
1560                             args[1].immediate()
1561                         } else {
1562                             // unordered arithmetic reductions use the identity accumulator
1563                             match f.bit_width() {
1564                                 32 => bx.const_real(bx.type_f32(), $identity),
1565                                 64 => bx.const_real(bx.type_f64(), $identity),
1566                                 v => return_error!(
1567                                     r#"
1568 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1569                                     sym::$name,
1570                                     in_ty,
1571                                     in_elem,
1572                                     v,
1573                                     ret_ty
1574                                 ),
1575                             }
1576                         };
1577                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1578                     }
1579                     _ => return_error!(
1580                         "unsupported {} from `{}` with element `{}` to `{}`",
1581                         sym::$name,
1582                         in_ty,
1583                         in_elem,
1584                         ret_ty
1585                     ),
1586                 };
1587             }
1588         };
1589     }
1590
1591     arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1592     arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1593     arith_red!(
1594         simd_reduce_add_unordered: vector_reduce_add,
1595         vector_reduce_fadd_fast,
1596         false,
1597         add,
1598         0.0
1599     );
1600     arith_red!(
1601         simd_reduce_mul_unordered: vector_reduce_mul,
1602         vector_reduce_fmul_fast,
1603         false,
1604         mul,
1605         1.0
1606     );
1607
1608     macro_rules! minmax_red {
1609         ($name:ident: $int_red:ident, $float_red:ident) => {
1610             if name == sym::$name {
1611                 require!(
1612                     ret_ty == in_elem,
1613                     "expected return type `{}` (element of input `{}`), found `{}`",
1614                     in_elem,
1615                     in_ty,
1616                     ret_ty
1617                 );
1618                 return match in_elem.kind() {
1619                     ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1620                     ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1621                     ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1622                     _ => return_error!(
1623                         "unsupported {} from `{}` with element `{}` to `{}`",
1624                         sym::$name,
1625                         in_ty,
1626                         in_elem,
1627                         ret_ty
1628                     ),
1629                 };
1630             }
1631         };
1632     }
1633
1634     minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1635     minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1636
1637     minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1638     minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1639
1640     macro_rules! bitwise_red {
1641         ($name:ident : $red:ident, $boolean:expr) => {
1642             if name == sym::$name {
1643                 let input = if !$boolean {
1644                     require!(
1645                         ret_ty == in_elem,
1646                         "expected return type `{}` (element of input `{}`), found `{}`",
1647                         in_elem,
1648                         in_ty,
1649                         ret_ty
1650                     );
1651                     args[0].immediate()
1652                 } else {
1653                     match in_elem.kind() {
1654                         ty::Int(_) | ty::Uint(_) => {}
1655                         _ => return_error!(
1656                             "unsupported {} from `{}` with element `{}` to `{}`",
1657                             sym::$name,
1658                             in_ty,
1659                             in_elem,
1660                             ret_ty
1661                         ),
1662                     }
1663
1664                     // boolean reductions operate on vectors of i1s:
1665                     let i1 = bx.type_i1();
1666                     let i1xn = bx.type_vector(i1, in_len as u64);
1667                     bx.trunc(args[0].immediate(), i1xn)
1668                 };
1669                 return match in_elem.kind() {
1670                     ty::Int(_) | ty::Uint(_) => {
1671                         let r = bx.$red(input);
1672                         Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1673                     }
1674                     _ => return_error!(
1675                         "unsupported {} from `{}` with element `{}` to `{}`",
1676                         sym::$name,
1677                         in_ty,
1678                         in_elem,
1679                         ret_ty
1680                     ),
1681                 };
1682             }
1683         };
1684     }
1685
1686     bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1687     bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1688     bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1689     bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1690     bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1691
1692     if name == sym::simd_cast || name == sym::simd_as {
1693         require_simd!(ret_ty, "return");
1694         let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1695         require!(
1696             in_len == out_len,
1697             "expected return type with length {} (same as input type `{}`), \
1698                   found `{}` with length {}",
1699             in_len,
1700             in_ty,
1701             ret_ty,
1702             out_len
1703         );
1704         // casting cares about nominal type, not just structural type
1705         if in_elem == out_elem {
1706             return Ok(args[0].immediate());
1707         }
1708
1709         enum Style {
1710             Float,
1711             Int(/* is signed? */ bool),
1712             Unsupported,
1713         }
1714
1715         let (in_style, in_width) = match in_elem.kind() {
1716             // vectors of pointer-sized integers should've been
1717             // disallowed before here, so this unwrap is safe.
1718             ty::Int(i) => (
1719                 Style::Int(true),
1720                 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1721             ),
1722             ty::Uint(u) => (
1723                 Style::Int(false),
1724                 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1725             ),
1726             ty::Float(f) => (Style::Float, f.bit_width()),
1727             _ => (Style::Unsupported, 0),
1728         };
1729         let (out_style, out_width) = match out_elem.kind() {
1730             ty::Int(i) => (
1731                 Style::Int(true),
1732                 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1733             ),
1734             ty::Uint(u) => (
1735                 Style::Int(false),
1736                 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1737             ),
1738             ty::Float(f) => (Style::Float, f.bit_width()),
1739             _ => (Style::Unsupported, 0),
1740         };
1741
1742         match (in_style, out_style) {
1743             (Style::Int(in_is_signed), Style::Int(_)) => {
1744                 return Ok(match in_width.cmp(&out_width) {
1745                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1746                     Ordering::Equal => args[0].immediate(),
1747                     Ordering::Less => {
1748                         if in_is_signed {
1749                             bx.sext(args[0].immediate(), llret_ty)
1750                         } else {
1751                             bx.zext(args[0].immediate(), llret_ty)
1752                         }
1753                     }
1754                 });
1755             }
1756             (Style::Int(in_is_signed), Style::Float) => {
1757                 return Ok(if in_is_signed {
1758                     bx.sitofp(args[0].immediate(), llret_ty)
1759                 } else {
1760                     bx.uitofp(args[0].immediate(), llret_ty)
1761                 });
1762             }
1763             (Style::Float, Style::Int(out_is_signed)) => {
1764                 return Ok(match (out_is_signed, name == sym::simd_as) {
1765                     (false, false) => bx.fptoui(args[0].immediate(), llret_ty),
1766                     (true, false) => bx.fptosi(args[0].immediate(), llret_ty),
1767                     (_, true) => bx.cast_float_to_int(out_is_signed, args[0].immediate(), llret_ty),
1768                 });
1769             }
1770             (Style::Float, Style::Float) => {
1771                 return Ok(match in_width.cmp(&out_width) {
1772                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1773                     Ordering::Equal => args[0].immediate(),
1774                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1775                 });
1776             }
1777             _ => { /* Unsupported. Fallthrough. */ }
1778         }
1779         require!(
1780             false,
1781             "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1782             in_ty,
1783             in_elem,
1784             ret_ty,
1785             out_elem
1786         );
1787     }
1788     macro_rules! arith_binary {
1789         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1790             $(if name == sym::$name {
1791                 match in_elem.kind() {
1792                     $($(ty::$p(_))|* => {
1793                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1794                     })*
1795                     _ => {},
1796                 }
1797                 require!(false,
1798                          "unsupported operation on `{}` with element `{}`",
1799                          in_ty,
1800                          in_elem)
1801             })*
1802         }
1803     }
1804     arith_binary! {
1805         simd_add: Uint, Int => add, Float => fadd;
1806         simd_sub: Uint, Int => sub, Float => fsub;
1807         simd_mul: Uint, Int => mul, Float => fmul;
1808         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1809         simd_rem: Uint => urem, Int => srem, Float => frem;
1810         simd_shl: Uint, Int => shl;
1811         simd_shr: Uint => lshr, Int => ashr;
1812         simd_and: Uint, Int => and;
1813         simd_or: Uint, Int => or;
1814         simd_xor: Uint, Int => xor;
1815         simd_fmax: Float => maxnum;
1816         simd_fmin: Float => minnum;
1817
1818     }
1819     macro_rules! arith_unary {
1820         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1821             $(if name == sym::$name {
1822                 match in_elem.kind() {
1823                     $($(ty::$p(_))|* => {
1824                         return Ok(bx.$call(args[0].immediate()))
1825                     })*
1826                     _ => {},
1827                 }
1828                 require!(false,
1829                          "unsupported operation on `{}` with element `{}`",
1830                          in_ty,
1831                          in_elem)
1832             })*
1833         }
1834     }
1835     arith_unary! {
1836         simd_neg: Int => neg, Float => fneg;
1837     }
1838
1839     if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1840         let lhs = args[0].immediate();
1841         let rhs = args[1].immediate();
1842         let is_add = name == sym::simd_saturating_add;
1843         let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1844         let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1845             ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1846             ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1847             _ => {
1848                 return_error!(
1849                     "expected element type `{}` of vector type `{}` \
1850                      to be a signed or unsigned integer type",
1851                     arg_tys[0].simd_size_and_type(bx.tcx()).1,
1852                     arg_tys[0]
1853                 );
1854             }
1855         };
1856         let llvm_intrinsic = &format!(
1857             "llvm.{}{}.sat.v{}i{}",
1858             if signed { 's' } else { 'u' },
1859             if is_add { "add" } else { "sub" },
1860             in_len,
1861             elem_width
1862         );
1863         let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1864
1865         let fn_ty = bx.type_func(&[vec_ty, vec_ty], vec_ty);
1866         let f = bx.declare_cfn(llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1867         let v = bx.call(fn_ty, f, &[lhs, rhs], None);
1868         return Ok(v);
1869     }
1870
1871     span_bug!(span, "unknown SIMD intrinsic");
1872 }
1873
1874 // Returns the width of an int Ty, and if it's signed or not
1875 // Returns None if the type is not an integer
1876 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1877 // stuffs.
1878 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1879     match ty.kind() {
1880         ty::Int(t) => {
1881             Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
1882         }
1883         ty::Uint(t) => {
1884             Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))
1885         }
1886         _ => None,
1887     }
1888 }