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