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