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