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