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