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