]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/intrinsic.rs
Rollup merge of #75140 - GuillaumeGomez:cleanup-e0745, r=pickfire
[rust.git] / src / librustc_codegen_llvm / 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 log::debug;
11
12 use rustc_ast::ast;
13 use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
14 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
15 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
16 use rustc_codegen_ssa::coverageinfo::ExprKind;
17 use rustc_codegen_ssa::glue;
18 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
19 use rustc_codegen_ssa::mir::place::PlaceRef;
20 use rustc_codegen_ssa::traits::*;
21 use rustc_codegen_ssa::MemFlags;
22 use rustc_hir as hir;
23 use rustc_middle::mir::coverage;
24 use rustc_middle::mir::Operand;
25 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
26 use rustc_middle::ty::{self, Ty};
27 use rustc_middle::{bug, span_bug};
28 use rustc_span::{sym, symbol::kw, Span, Symbol};
29 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
30 use rustc_target::spec::PanicStrategy;
31
32 use std::cmp::Ordering;
33 use std::iter;
34
35 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<&'ll Value> {
36     let llvm_name = match name {
37         sym::sqrtf32 => "llvm.sqrt.f32",
38         sym::sqrtf64 => "llvm.sqrt.f64",
39         sym::powif32 => "llvm.powi.f32",
40         sym::powif64 => "llvm.powi.f64",
41         sym::sinf32 => "llvm.sin.f32",
42         sym::sinf64 => "llvm.sin.f64",
43         sym::cosf32 => "llvm.cos.f32",
44         sym::cosf64 => "llvm.cos.f64",
45         sym::powf32 => "llvm.pow.f32",
46         sym::powf64 => "llvm.pow.f64",
47         sym::expf32 => "llvm.exp.f32",
48         sym::expf64 => "llvm.exp.f64",
49         sym::exp2f32 => "llvm.exp2.f32",
50         sym::exp2f64 => "llvm.exp2.f64",
51         sym::logf32 => "llvm.log.f32",
52         sym::logf64 => "llvm.log.f64",
53         sym::log10f32 => "llvm.log10.f32",
54         sym::log10f64 => "llvm.log10.f64",
55         sym::log2f32 => "llvm.log2.f32",
56         sym::log2f64 => "llvm.log2.f64",
57         sym::fmaf32 => "llvm.fma.f32",
58         sym::fmaf64 => "llvm.fma.f64",
59         sym::fabsf32 => "llvm.fabs.f32",
60         sym::fabsf64 => "llvm.fabs.f64",
61         sym::minnumf32 => "llvm.minnum.f32",
62         sym::minnumf64 => "llvm.minnum.f64",
63         sym::maxnumf32 => "llvm.maxnum.f32",
64         sym::maxnumf64 => "llvm.maxnum.f64",
65         sym::copysignf32 => "llvm.copysign.f32",
66         sym::copysignf64 => "llvm.copysign.f64",
67         sym::floorf32 => "llvm.floor.f32",
68         sym::floorf64 => "llvm.floor.f64",
69         sym::ceilf32 => "llvm.ceil.f32",
70         sym::ceilf64 => "llvm.ceil.f64",
71         sym::truncf32 => "llvm.trunc.f32",
72         sym::truncf64 => "llvm.trunc.f64",
73         sym::rintf32 => "llvm.rint.f32",
74         sym::rintf64 => "llvm.rint.f64",
75         sym::nearbyintf32 => "llvm.nearbyint.f32",
76         sym::nearbyintf64 => "llvm.nearbyint.f64",
77         sym::roundf32 => "llvm.round.f32",
78         sym::roundf64 => "llvm.round.f64",
79         sym::assume => "llvm.assume",
80         sym::abort => "llvm.trap",
81         _ => return None,
82     };
83     Some(cx.get_intrinsic(&llvm_name))
84 }
85
86 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
87     fn is_codegen_intrinsic(
88         &mut self,
89         intrinsic: Symbol,
90         args: &Vec<Operand<'tcx>>,
91         caller_instance: ty::Instance<'tcx>,
92     ) -> bool {
93         let mut is_codegen_intrinsic = true;
94         // Set `is_codegen_intrinsic` to `false` to bypass `codegen_intrinsic_call()`.
95
96         if self.tcx.sess.opts.debugging_opts.instrument_coverage {
97             // If the intrinsic is from the local MIR, add the coverage information to the Codegen
98             // context, to be encoded into the local crate's coverage map.
99             if caller_instance.def_id().is_local() {
100                 // FIXME(richkadel): Make sure to add coverage analysis tests on a crate with
101                 // external crate dependencies, where:
102                 //   1. Both binary and dependent crates are compiled with `-Zinstrument-coverage`
103                 //   2. Only binary is compiled with `-Zinstrument-coverage`
104                 //   3. Only dependent crates are compiled with `-Zinstrument-coverage`
105                 match intrinsic {
106                     sym::count_code_region => {
107                         use coverage::count_code_region_args::*;
108                         self.add_counter_region(
109                             caller_instance,
110                             op_to_u64(&args[FUNCTION_SOURCE_HASH]),
111                             op_to_u32(&args[COUNTER_ID]),
112                             op_to_u32(&args[START_BYTE_POS]),
113                             op_to_u32(&args[END_BYTE_POS]),
114                         );
115                     }
116                     sym::coverage_counter_add | sym::coverage_counter_subtract => {
117                         use coverage::coverage_counter_expression_args::*;
118                         self.add_counter_expression_region(
119                             caller_instance,
120                             op_to_u32(&args[EXPRESSION_ID]),
121                             op_to_u32(&args[LEFT_ID]),
122                             if intrinsic == sym::coverage_counter_add {
123                                 ExprKind::Add
124                             } else {
125                                 ExprKind::Subtract
126                             },
127                             op_to_u32(&args[RIGHT_ID]),
128                             op_to_u32(&args[START_BYTE_POS]),
129                             op_to_u32(&args[END_BYTE_POS]),
130                         );
131                     }
132                     sym::coverage_unreachable => {
133                         use coverage::coverage_unreachable_args::*;
134                         self.add_unreachable_region(
135                             caller_instance,
136                             op_to_u32(&args[START_BYTE_POS]),
137                             op_to_u32(&args[END_BYTE_POS]),
138                         );
139                     }
140                     _ => {}
141                 }
142             }
143
144             // Only the `count_code_region` coverage intrinsic is translated into an actual LLVM
145             // intrinsic call (local or not); otherwise, set `is_codegen_intrinsic` to `false`.
146             match intrinsic {
147                 sym::coverage_counter_add
148                 | sym::coverage_counter_subtract
149                 | sym::coverage_unreachable => {
150                     is_codegen_intrinsic = false;
151                 }
152                 _ => {}
153             }
154         }
155         is_codegen_intrinsic
156     }
157
158     fn codegen_intrinsic_call(
159         &mut self,
160         instance: ty::Instance<'tcx>,
161         fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
162         args: &[OperandRef<'tcx, &'ll Value>],
163         llresult: &'ll Value,
164         span: Span,
165         caller_instance: ty::Instance<'tcx>,
166     ) {
167         let tcx = self.tcx;
168         let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
169
170         let (def_id, substs) = match callee_ty.kind {
171             ty::FnDef(def_id, substs) => (def_id, substs),
172             _ => bug!("expected fn item type, found {}", callee_ty),
173         };
174
175         let sig = callee_ty.fn_sig(tcx);
176         let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
177         let arg_tys = sig.inputs();
178         let ret_ty = sig.output();
179         let name = tcx.item_name(def_id);
180         let name_str = &*name.as_str();
181
182         let llret_ty = self.layout_of(ret_ty).llvm_type(self);
183         let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
184
185         let simple = get_simple_intrinsic(self, name);
186         let llval = match name {
187             _ if simple.is_some() => self.call(
188                 simple.unwrap(),
189                 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
190                 None,
191             ),
192             sym::unreachable => {
193                 return;
194             }
195             sym::likely => {
196                 let expect = self.get_intrinsic(&("llvm.expect.i1"));
197                 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
198             }
199             sym::unlikely => {
200                 let expect = self.get_intrinsic(&("llvm.expect.i1"));
201                 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
202             }
203             kw::Try => {
204                 try_intrinsic(
205                     self,
206                     args[0].immediate(),
207                     args[1].immediate(),
208                     args[2].immediate(),
209                     llresult,
210                 );
211                 return;
212             }
213             sym::breakpoint => {
214                 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
215                 self.call(llfn, &[], None)
216             }
217             sym::count_code_region => {
218                 // FIXME(richkadel): The current implementation assumes the MIR for the given
219                 // caller_instance represents a single function. Validate and/or correct if inlining
220                 // and/or monomorphization invalidates these assumptions.
221                 let coverageinfo = tcx.coverageinfo(caller_instance.def_id());
222                 let mangled_fn = tcx.symbol_name(caller_instance);
223                 let (mangled_fn_name, _len_val) = self.const_str(Symbol::intern(mangled_fn.name));
224                 let num_counters = self.const_u32(coverageinfo.num_counters);
225                 use coverage::count_code_region_args::*;
226                 let hash = args[FUNCTION_SOURCE_HASH].immediate();
227                 let index = args[COUNTER_ID].immediate();
228                 debug!(
229                     "translating Rust intrinsic `count_code_region()` to LLVM intrinsic: \
230                     instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
231                     mangled_fn.name, hash, num_counters, index,
232                 );
233                 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
234             }
235             sym::va_start => self.va_start(args[0].immediate()),
236             sym::va_end => self.va_end(args[0].immediate()),
237             sym::va_copy => {
238                 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
239                 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
240             }
241             sym::va_arg => {
242                 match fn_abi.ret.layout.abi {
243                     abi::Abi::Scalar(ref scalar) => {
244                         match scalar.value {
245                             Primitive::Int(..) => {
246                                 if self.cx().size_of(ret_ty).bytes() < 4 {
247                                     // `va_arg` should not be called on a integer type
248                                     // less than 4 bytes in length. If it is, promote
249                                     // the integer to a `i32` and truncate the result
250                                     // back to the smaller type.
251                                     let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
252                                     self.trunc(promoted_result, llret_ty)
253                                 } else {
254                                     emit_va_arg(self, args[0], ret_ty)
255                                 }
256                             }
257                             Primitive::F64 | Primitive::Pointer => {
258                                 emit_va_arg(self, args[0], ret_ty)
259                             }
260                             // `va_arg` should never be used with the return type f32.
261                             Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
262                         }
263                     }
264                     _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
265                 }
266             }
267             sym::size_of_val => {
268                 let tp_ty = substs.type_at(0);
269                 if let OperandValue::Pair(_, meta) = args[0].val {
270                     let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
271                     llsize
272                 } else {
273                     self.const_usize(self.size_of(tp_ty).bytes())
274                 }
275             }
276             sym::min_align_of_val => {
277                 let tp_ty = substs.type_at(0);
278                 if let OperandValue::Pair(_, meta) = args[0].val {
279                     let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
280                     llalign
281                 } else {
282                     self.const_usize(self.align_of(tp_ty).bytes())
283                 }
284             }
285             sym::size_of
286             | sym::pref_align_of
287             | sym::min_align_of
288             | sym::needs_drop
289             | sym::type_id
290             | sym::type_name
291             | sym::variant_count => {
292                 let value = self
293                     .tcx
294                     .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
295                     .unwrap();
296                 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
297             }
298             // Effectively no-op
299             sym::forget => {
300                 return;
301             }
302             sym::offset => {
303                 let ptr = args[0].immediate();
304                 let offset = args[1].immediate();
305                 self.inbounds_gep(ptr, &[offset])
306             }
307             sym::arith_offset => {
308                 let ptr = args[0].immediate();
309                 let offset = args[1].immediate();
310                 self.gep(ptr, &[offset])
311             }
312
313             sym::copy_nonoverlapping => {
314                 copy_intrinsic(
315                     self,
316                     false,
317                     false,
318                     substs.type_at(0),
319                     args[1].immediate(),
320                     args[0].immediate(),
321                     args[2].immediate(),
322                 );
323                 return;
324             }
325             sym::copy => {
326                 copy_intrinsic(
327                     self,
328                     true,
329                     false,
330                     substs.type_at(0),
331                     args[1].immediate(),
332                     args[0].immediate(),
333                     args[2].immediate(),
334                 );
335                 return;
336             }
337             sym::write_bytes => {
338                 memset_intrinsic(
339                     self,
340                     false,
341                     substs.type_at(0),
342                     args[0].immediate(),
343                     args[1].immediate(),
344                     args[2].immediate(),
345                 );
346                 return;
347             }
348
349             sym::volatile_copy_nonoverlapping_memory => {
350                 copy_intrinsic(
351                     self,
352                     false,
353                     true,
354                     substs.type_at(0),
355                     args[0].immediate(),
356                     args[1].immediate(),
357                     args[2].immediate(),
358                 );
359                 return;
360             }
361             sym::volatile_copy_memory => {
362                 copy_intrinsic(
363                     self,
364                     true,
365                     true,
366                     substs.type_at(0),
367                     args[0].immediate(),
368                     args[1].immediate(),
369                     args[2].immediate(),
370                 );
371                 return;
372             }
373             sym::volatile_set_memory => {
374                 memset_intrinsic(
375                     self,
376                     true,
377                     substs.type_at(0),
378                     args[0].immediate(),
379                     args[1].immediate(),
380                     args[2].immediate(),
381                 );
382                 return;
383             }
384             sym::volatile_load | sym::unaligned_volatile_load => {
385                 let tp_ty = substs.type_at(0);
386                 let mut ptr = args[0].immediate();
387                 if let PassMode::Cast(ty) = fn_abi.ret.mode {
388                     ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
389                 }
390                 let load = self.volatile_load(ptr);
391                 let align = if name == sym::unaligned_volatile_load {
392                     1
393                 } else {
394                     self.align_of(tp_ty).bytes() as u32
395                 };
396                 unsafe {
397                     llvm::LLVMSetAlignment(load, align);
398                 }
399                 to_immediate(self, load, self.layout_of(tp_ty))
400             }
401             sym::volatile_store => {
402                 let dst = args[0].deref(self.cx());
403                 args[1].val.volatile_store(self, dst);
404                 return;
405             }
406             sym::unaligned_volatile_store => {
407                 let dst = args[0].deref(self.cx());
408                 args[1].val.unaligned_volatile_store(self, dst);
409                 return;
410             }
411             sym::prefetch_read_data
412             | sym::prefetch_write_data
413             | sym::prefetch_read_instruction
414             | sym::prefetch_write_instruction => {
415                 let expect = self.get_intrinsic(&("llvm.prefetch"));
416                 let (rw, cache_type) = match name {
417                     sym::prefetch_read_data => (0, 1),
418                     sym::prefetch_write_data => (1, 1),
419                     sym::prefetch_read_instruction => (0, 0),
420                     sym::prefetch_write_instruction => (1, 0),
421                     _ => bug!(),
422                 };
423                 self.call(
424                     expect,
425                     &[
426                         args[0].immediate(),
427                         self.const_i32(rw),
428                         args[1].immediate(),
429                         self.const_i32(cache_type),
430                     ],
431                     None,
432                 )
433             }
434             sym::ctlz
435             | sym::ctlz_nonzero
436             | sym::cttz
437             | sym::cttz_nonzero
438             | sym::ctpop
439             | sym::bswap
440             | sym::bitreverse
441             | sym::add_with_overflow
442             | sym::sub_with_overflow
443             | sym::mul_with_overflow
444             | sym::wrapping_add
445             | sym::wrapping_sub
446             | sym::wrapping_mul
447             | sym::unchecked_div
448             | sym::unchecked_rem
449             | sym::unchecked_shl
450             | sym::unchecked_shr
451             | sym::unchecked_add
452             | sym::unchecked_sub
453             | sym::unchecked_mul
454             | sym::exact_div
455             | sym::rotate_left
456             | sym::rotate_right
457             | sym::saturating_add
458             | sym::saturating_sub => {
459                 let ty = arg_tys[0];
460                 match int_type_width_signed(ty, self) {
461                     Some((width, signed)) => match name {
462                         sym::ctlz | sym::cttz => {
463                             let y = self.const_bool(false);
464                             let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
465                             self.call(llfn, &[args[0].immediate(), y], None)
466                         }
467                         sym::ctlz_nonzero | sym::cttz_nonzero => {
468                             let y = self.const_bool(true);
469                             let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
470                             let llfn = self.get_intrinsic(llvm_name);
471                             self.call(llfn, &[args[0].immediate(), y], None)
472                         }
473                         sym::ctpop => self.call(
474                             self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
475                             &[args[0].immediate()],
476                             None,
477                         ),
478                         sym::bswap => {
479                             if width == 8 {
480                                 args[0].immediate() // byte swap a u8/i8 is just a no-op
481                             } else {
482                                 self.call(
483                                     self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
484                                     &[args[0].immediate()],
485                                     None,
486                                 )
487                             }
488                         }
489                         sym::bitreverse => self.call(
490                             self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
491                             &[args[0].immediate()],
492                             None,
493                         ),
494                         sym::add_with_overflow
495                         | sym::sub_with_overflow
496                         | sym::mul_with_overflow => {
497                             let intrinsic = format!(
498                                 "llvm.{}{}.with.overflow.i{}",
499                                 if signed { 's' } else { 'u' },
500                                 &name_str[..3],
501                                 width
502                             );
503                             let llfn = self.get_intrinsic(&intrinsic);
504
505                             // Convert `i1` to a `bool`, and write it to the out parameter
506                             let pair =
507                                 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
508                             let val = self.extract_value(pair, 0);
509                             let overflow = self.extract_value(pair, 1);
510                             let overflow = self.zext(overflow, self.type_bool());
511
512                             let dest = result.project_field(self, 0);
513                             self.store(val, dest.llval, dest.align);
514                             let dest = result.project_field(self, 1);
515                             self.store(overflow, dest.llval, dest.align);
516
517                             return;
518                         }
519                         sym::wrapping_add => self.add(args[0].immediate(), args[1].immediate()),
520                         sym::wrapping_sub => self.sub(args[0].immediate(), args[1].immediate()),
521                         sym::wrapping_mul => self.mul(args[0].immediate(), args[1].immediate()),
522                         sym::exact_div => {
523                             if signed {
524                                 self.exactsdiv(args[0].immediate(), args[1].immediate())
525                             } else {
526                                 self.exactudiv(args[0].immediate(), args[1].immediate())
527                             }
528                         }
529                         sym::unchecked_div => {
530                             if signed {
531                                 self.sdiv(args[0].immediate(), args[1].immediate())
532                             } else {
533                                 self.udiv(args[0].immediate(), args[1].immediate())
534                             }
535                         }
536                         sym::unchecked_rem => {
537                             if signed {
538                                 self.srem(args[0].immediate(), args[1].immediate())
539                             } else {
540                                 self.urem(args[0].immediate(), args[1].immediate())
541                             }
542                         }
543                         sym::unchecked_shl => self.shl(args[0].immediate(), args[1].immediate()),
544                         sym::unchecked_shr => {
545                             if signed {
546                                 self.ashr(args[0].immediate(), args[1].immediate())
547                             } else {
548                                 self.lshr(args[0].immediate(), args[1].immediate())
549                             }
550                         }
551                         sym::unchecked_add => {
552                             if signed {
553                                 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
554                             } else {
555                                 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
556                             }
557                         }
558                         sym::unchecked_sub => {
559                             if signed {
560                                 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
561                             } else {
562                                 self.unchecked_usub(args[0].immediate(), args[1].immediate())
563                             }
564                         }
565                         sym::unchecked_mul => {
566                             if signed {
567                                 self.unchecked_smul(args[0].immediate(), args[1].immediate())
568                             } else {
569                                 self.unchecked_umul(args[0].immediate(), args[1].immediate())
570                             }
571                         }
572                         sym::rotate_left | sym::rotate_right => {
573                             let is_left = name == sym::rotate_left;
574                             let val = args[0].immediate();
575                             let raw_shift = args[1].immediate();
576                             // rotate = funnel shift with first two args the same
577                             let llvm_name =
578                                 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
579                             let llfn = self.get_intrinsic(llvm_name);
580                             self.call(llfn, &[val, val, raw_shift], None)
581                         }
582                         sym::saturating_add | sym::saturating_sub => {
583                             let is_add = name == sym::saturating_add;
584                             let lhs = args[0].immediate();
585                             let rhs = args[1].immediate();
586                             let llvm_name = &format!(
587                                 "llvm.{}{}.sat.i{}",
588                                 if signed { 's' } else { 'u' },
589                                 if is_add { "add" } else { "sub" },
590                                 width
591                             );
592                             let llfn = self.get_intrinsic(llvm_name);
593                             self.call(llfn, &[lhs, rhs], None)
594                         }
595                         _ => bug!(),
596                     },
597                     None => {
598                         span_invalid_monomorphization_error(
599                             tcx.sess,
600                             span,
601                             &format!(
602                                 "invalid monomorphization of `{}` intrinsic: \
603                                       expected basic integer type, found `{}`",
604                                 name, ty
605                             ),
606                         );
607                         return;
608                     }
609                 }
610             }
611             sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
612                 match float_type_width(arg_tys[0]) {
613                     Some(_width) => match name {
614                         sym::fadd_fast => self.fadd_fast(args[0].immediate(), args[1].immediate()),
615                         sym::fsub_fast => self.fsub_fast(args[0].immediate(), args[1].immediate()),
616                         sym::fmul_fast => self.fmul_fast(args[0].immediate(), args[1].immediate()),
617                         sym::fdiv_fast => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
618                         sym::frem_fast => self.frem_fast(args[0].immediate(), args[1].immediate()),
619                         _ => bug!(),
620                     },
621                     None => {
622                         span_invalid_monomorphization_error(
623                             tcx.sess,
624                             span,
625                             &format!(
626                                 "invalid monomorphization of `{}` intrinsic: \
627                                       expected basic float type, found `{}`",
628                                 name, arg_tys[0]
629                             ),
630                         );
631                         return;
632                     }
633                 }
634             }
635
636             sym::float_to_int_unchecked => {
637                 if float_type_width(arg_tys[0]).is_none() {
638                     span_invalid_monomorphization_error(
639                         tcx.sess,
640                         span,
641                         &format!(
642                             "invalid monomorphization of `float_to_int_unchecked` \
643                                   intrinsic: expected basic float type, \
644                                   found `{}`",
645                             arg_tys[0]
646                         ),
647                     );
648                     return;
649                 }
650                 let (width, signed) = match int_type_width_signed(ret_ty, self.cx) {
651                     Some(pair) => pair,
652                     None => {
653                         span_invalid_monomorphization_error(
654                             tcx.sess,
655                             span,
656                             &format!(
657                                 "invalid monomorphization of `float_to_int_unchecked` \
658                                       intrinsic:  expected basic integer type, \
659                                       found `{}`",
660                                 ret_ty
661                             ),
662                         );
663                         return;
664                     }
665                 };
666                 if signed {
667                     self.fptosi(args[0].immediate(), self.cx.type_ix(width))
668                 } else {
669                     self.fptoui(args[0].immediate(), self.cx.type_ix(width))
670                 }
671             }
672
673             sym::discriminant_value => {
674                 if ret_ty.is_integral() {
675                     args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
676                 } else {
677                     span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
678                 }
679             }
680
681             _ if name_str.starts_with("simd_") => {
682                 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
683                     Ok(llval) => llval,
684                     Err(()) => return,
685                 }
686             }
687             // This requires that atomic intrinsics follow a specific naming pattern:
688             // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
689             name if name_str.starts_with("atomic_") => {
690                 use rustc_codegen_ssa::common::AtomicOrdering::*;
691                 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
692
693                 let split: Vec<&str> = name_str.split('_').collect();
694
695                 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
696                 let (order, failorder) = match split.len() {
697                     2 => (SequentiallyConsistent, SequentiallyConsistent),
698                     3 => match split[2] {
699                         "unordered" => (Unordered, Unordered),
700                         "relaxed" => (Monotonic, Monotonic),
701                         "acq" => (Acquire, Acquire),
702                         "rel" => (Release, Monotonic),
703                         "acqrel" => (AcquireRelease, Acquire),
704                         "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
705                         "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
706                         _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
707                     },
708                     4 => match (split[2], split[3]) {
709                         ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
710                         ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
711                         _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
712                     },
713                     _ => self.sess().fatal("Atomic intrinsic not in correct format"),
714                 };
715
716                 let invalid_monomorphization = |ty| {
717                     span_invalid_monomorphization_error(
718                         tcx.sess,
719                         span,
720                         &format!(
721                             "invalid monomorphization of `{}` intrinsic: \
722                                   expected basic integer type, found `{}`",
723                             name, ty
724                         ),
725                     );
726                 };
727
728                 match split[1] {
729                     "cxchg" | "cxchgweak" => {
730                         let ty = substs.type_at(0);
731                         if int_type_width_signed(ty, self).is_some() {
732                             let weak = split[1] == "cxchgweak";
733                             let pair = self.atomic_cmpxchg(
734                                 args[0].immediate(),
735                                 args[1].immediate(),
736                                 args[2].immediate(),
737                                 order,
738                                 failorder,
739                                 weak,
740                             );
741                             let val = self.extract_value(pair, 0);
742                             let success = self.extract_value(pair, 1);
743                             let success = self.zext(success, self.type_bool());
744
745                             let dest = result.project_field(self, 0);
746                             self.store(val, dest.llval, dest.align);
747                             let dest = result.project_field(self, 1);
748                             self.store(success, dest.llval, dest.align);
749                             return;
750                         } else {
751                             return invalid_monomorphization(ty);
752                         }
753                     }
754
755                     "load" => {
756                         let ty = substs.type_at(0);
757                         if int_type_width_signed(ty, self).is_some() {
758                             let size = self.size_of(ty);
759                             self.atomic_load(args[0].immediate(), order, size)
760                         } else {
761                             return invalid_monomorphization(ty);
762                         }
763                     }
764
765                     "store" => {
766                         let ty = substs.type_at(0);
767                         if int_type_width_signed(ty, self).is_some() {
768                             let size = self.size_of(ty);
769                             self.atomic_store(
770                                 args[1].immediate(),
771                                 args[0].immediate(),
772                                 order,
773                                 size,
774                             );
775                             return;
776                         } else {
777                             return invalid_monomorphization(ty);
778                         }
779                     }
780
781                     "fence" => {
782                         self.atomic_fence(order, SynchronizationScope::CrossThread);
783                         return;
784                     }
785
786                     "singlethreadfence" => {
787                         self.atomic_fence(order, SynchronizationScope::SingleThread);
788                         return;
789                     }
790
791                     // These are all AtomicRMW ops
792                     op => {
793                         let atom_op = match op {
794                             "xchg" => AtomicRmwBinOp::AtomicXchg,
795                             "xadd" => AtomicRmwBinOp::AtomicAdd,
796                             "xsub" => AtomicRmwBinOp::AtomicSub,
797                             "and" => AtomicRmwBinOp::AtomicAnd,
798                             "nand" => AtomicRmwBinOp::AtomicNand,
799                             "or" => AtomicRmwBinOp::AtomicOr,
800                             "xor" => AtomicRmwBinOp::AtomicXor,
801                             "max" => AtomicRmwBinOp::AtomicMax,
802                             "min" => AtomicRmwBinOp::AtomicMin,
803                             "umax" => AtomicRmwBinOp::AtomicUMax,
804                             "umin" => AtomicRmwBinOp::AtomicUMin,
805                             _ => self.sess().fatal("unknown atomic operation"),
806                         };
807
808                         let ty = substs.type_at(0);
809                         if int_type_width_signed(ty, self).is_some() {
810                             self.atomic_rmw(
811                                 atom_op,
812                                 args[0].immediate(),
813                                 args[1].immediate(),
814                                 order,
815                             )
816                         } else {
817                             return invalid_monomorphization(ty);
818                         }
819                     }
820                 }
821             }
822
823             sym::nontemporal_store => {
824                 let dst = args[0].deref(self.cx());
825                 args[1].val.nontemporal_store(self, dst);
826                 return;
827             }
828
829             sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
830                 let a = args[0].immediate();
831                 let b = args[1].immediate();
832                 if name == sym::ptr_guaranteed_eq {
833                     self.icmp(IntPredicate::IntEQ, a, b)
834                 } else {
835                     self.icmp(IntPredicate::IntNE, a, b)
836                 }
837             }
838
839             sym::ptr_offset_from => {
840                 let ty = substs.type_at(0);
841                 let pointee_size = self.size_of(ty);
842
843                 // This is the same sequence that Clang emits for pointer subtraction.
844                 // It can be neither `nsw` nor `nuw` because the input is treated as
845                 // unsigned but then the output is treated as signed, so neither works.
846                 let a = args[0].immediate();
847                 let b = args[1].immediate();
848                 let a = self.ptrtoint(a, self.type_isize());
849                 let b = self.ptrtoint(b, self.type_isize());
850                 let d = self.sub(a, b);
851                 let pointee_size = self.const_usize(pointee_size.bytes());
852                 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
853                 self.exactsdiv(d, pointee_size)
854             }
855
856             _ => bug!("unknown intrinsic '{}'", name),
857         };
858
859         if !fn_abi.ret.is_ignore() {
860             if let PassMode::Cast(ty) = fn_abi.ret.mode {
861                 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
862                 let ptr = self.pointercast(result.llval, ptr_llty);
863                 self.store(llval, ptr, result.align);
864             } else {
865                 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
866                     .val
867                     .store(self, result);
868             }
869         }
870     }
871
872     fn abort(&mut self) {
873         let fnname = self.get_intrinsic(&("llvm.trap"));
874         self.call(fnname, &[], None);
875     }
876
877     fn assume(&mut self, val: Self::Value) {
878         let assume_intrinsic = self.get_intrinsic("llvm.assume");
879         self.call(assume_intrinsic, &[val], None);
880     }
881
882     fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
883         let expect = self.get_intrinsic(&"llvm.expect.i1");
884         self.call(expect, &[cond, self.const_bool(expected)], None)
885     }
886
887     fn sideeffect(&mut self) {
888         if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
889             let fnname = self.get_intrinsic(&("llvm.sideeffect"));
890             self.call(fnname, &[], None);
891         }
892     }
893
894     fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
895         let intrinsic = self.cx().get_intrinsic("llvm.va_start");
896         self.call(intrinsic, &[va_list], None)
897     }
898
899     fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
900         let intrinsic = self.cx().get_intrinsic("llvm.va_end");
901         self.call(intrinsic, &[va_list], None)
902     }
903 }
904
905 fn copy_intrinsic(
906     bx: &mut Builder<'a, 'll, 'tcx>,
907     allow_overlap: bool,
908     volatile: bool,
909     ty: Ty<'tcx>,
910     dst: &'ll Value,
911     src: &'ll Value,
912     count: &'ll Value,
913 ) {
914     let (size, align) = bx.size_and_align_of(ty);
915     let size = bx.mul(bx.const_usize(size.bytes()), count);
916     let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
917     if allow_overlap {
918         bx.memmove(dst, align, src, align, size, flags);
919     } else {
920         bx.memcpy(dst, align, src, align, size, flags);
921     }
922 }
923
924 fn memset_intrinsic(
925     bx: &mut Builder<'a, 'll, 'tcx>,
926     volatile: bool,
927     ty: Ty<'tcx>,
928     dst: &'ll Value,
929     val: &'ll Value,
930     count: &'ll Value,
931 ) {
932     let (size, align) = bx.size_and_align_of(ty);
933     let size = bx.mul(bx.const_usize(size.bytes()), count);
934     let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
935     bx.memset(dst, val, size, align, flags);
936 }
937
938 fn try_intrinsic(
939     bx: &mut Builder<'a, 'll, 'tcx>,
940     try_func: &'ll Value,
941     data: &'ll Value,
942     catch_func: &'ll Value,
943     dest: &'ll Value,
944 ) {
945     if bx.sess().panic_strategy() == PanicStrategy::Abort {
946         bx.call(try_func, &[data], None);
947         // Return 0 unconditionally from the intrinsic call;
948         // we can never unwind.
949         let ret_align = bx.tcx().data_layout.i32_align.abi;
950         bx.store(bx.const_i32(0), dest, ret_align);
951     } else if wants_msvc_seh(bx.sess()) {
952         codegen_msvc_try(bx, try_func, data, catch_func, dest);
953     } else {
954         codegen_gnu_try(bx, try_func, data, catch_func, dest);
955     }
956 }
957
958 // MSVC's definition of the `rust_try` function.
959 //
960 // This implementation uses the new exception handling instructions in LLVM
961 // which have support in LLVM for SEH on MSVC targets. Although these
962 // instructions are meant to work for all targets, as of the time of this
963 // writing, however, LLVM does not recommend the usage of these new instructions
964 // as the old ones are still more optimized.
965 fn codegen_msvc_try(
966     bx: &mut Builder<'a, 'll, 'tcx>,
967     try_func: &'ll Value,
968     data: &'ll Value,
969     catch_func: &'ll Value,
970     dest: &'ll Value,
971 ) {
972     let llfn = get_rust_try_fn(bx, &mut |mut bx| {
973         bx.set_personality_fn(bx.eh_personality());
974         bx.sideeffect();
975
976         let mut normal = bx.build_sibling_block("normal");
977         let mut catchswitch = bx.build_sibling_block("catchswitch");
978         let mut catchpad = bx.build_sibling_block("catchpad");
979         let mut caught = bx.build_sibling_block("caught");
980
981         let try_func = llvm::get_param(bx.llfn(), 0);
982         let data = llvm::get_param(bx.llfn(), 1);
983         let catch_func = llvm::get_param(bx.llfn(), 2);
984
985         // We're generating an IR snippet that looks like:
986         //
987         //   declare i32 @rust_try(%try_func, %data, %catch_func) {
988         //      %slot = alloca u8*
989         //      invoke %try_func(%data) to label %normal unwind label %catchswitch
990         //
991         //   normal:
992         //      ret i32 0
993         //
994         //   catchswitch:
995         //      %cs = catchswitch within none [%catchpad] unwind to caller
996         //
997         //   catchpad:
998         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
999         //      %ptr = load %slot
1000         //      call %catch_func(%data, %ptr)
1001         //      catchret from %tok to label %caught
1002         //
1003         //   caught:
1004         //      ret i32 1
1005         //   }
1006         //
1007         // This structure follows the basic usage of throw/try/catch in LLVM.
1008         // For example, compile this C++ snippet to see what LLVM generates:
1009         //
1010         //      #include <stdint.h>
1011         //
1012         //      struct rust_panic {
1013         //          rust_panic(const rust_panic&);
1014         //          ~rust_panic();
1015         //
1016         //          uint64_t x[2];
1017         //      };
1018         //
1019         //      int __rust_try(
1020         //          void (*try_func)(void*),
1021         //          void *data,
1022         //          void (*catch_func)(void*, void*) noexcept
1023         //      ) {
1024         //          try {
1025         //              try_func(data);
1026         //              return 0;
1027         //          } catch(rust_panic& a) {
1028         //              catch_func(data, &a);
1029         //              return 1;
1030         //          }
1031         //      }
1032         //
1033         // More information can be found in libstd's seh.rs implementation.
1034         let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1035         let slot = bx.alloca(bx.type_i8p(), ptr_align);
1036         bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
1037
1038         normal.ret(bx.const_i32(0));
1039
1040         let cs = catchswitch.catch_switch(None, None, 1);
1041         catchswitch.add_handler(cs, catchpad.llbb());
1042
1043         // We can't use the TypeDescriptor defined in libpanic_unwind because it
1044         // might be in another DLL and the SEH encoding only supports specifying
1045         // a TypeDescriptor from the current module.
1046         //
1047         // However this isn't an issue since the MSVC runtime uses string
1048         // comparison on the type name to match TypeDescriptors rather than
1049         // pointer equality.
1050         //
1051         // So instead we generate a new TypeDescriptor in each module that uses
1052         // `try` and let the linker merge duplicate definitions in the same
1053         // module.
1054         //
1055         // When modifying, make sure that the type_name string exactly matches
1056         // the one used in src/libpanic_unwind/seh.rs.
1057         let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1058         let type_name = bx.const_bytes(b"rust_panic\0");
1059         let type_info =
1060             bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1061         let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1062         unsafe {
1063             llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1064             llvm::SetUniqueComdat(bx.llmod, tydesc);
1065             llvm::LLVMSetInitializer(tydesc, type_info);
1066         }
1067
1068         // The flag value of 8 indicates that we are catching the exception by
1069         // reference instead of by value. We can't use catch by value because
1070         // that requires copying the exception object, which we don't support
1071         // since our exception object effectively contains a Box.
1072         //
1073         // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1074         let flags = bx.const_i32(8);
1075         let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1076         let ptr = catchpad.load(slot, ptr_align);
1077         catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1078
1079         catchpad.catch_ret(&funclet, caught.llbb());
1080
1081         caught.ret(bx.const_i32(1));
1082     });
1083
1084     // Note that no invoke is used here because by definition this function
1085     // can't panic (that's what it's catching).
1086     let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1087     let i32_align = bx.tcx().data_layout.i32_align.abi;
1088     bx.store(ret, dest, i32_align);
1089 }
1090
1091 // Definition of the standard `try` function for Rust using the GNU-like model
1092 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1093 // instructions).
1094 //
1095 // This codegen is a little surprising because we always call a shim
1096 // function instead of inlining the call to `invoke` manually here. This is done
1097 // because in LLVM we're only allowed to have one personality per function
1098 // definition. The call to the `try` intrinsic is being inlined into the
1099 // function calling it, and that function may already have other personality
1100 // functions in play. By calling a shim we're guaranteed that our shim will have
1101 // the right personality function.
1102 fn codegen_gnu_try(
1103     bx: &mut Builder<'a, 'll, 'tcx>,
1104     try_func: &'ll Value,
1105     data: &'ll Value,
1106     catch_func: &'ll Value,
1107     dest: &'ll Value,
1108 ) {
1109     let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1110         // Codegens the shims described above:
1111         //
1112         //   bx:
1113         //      invoke %try_func(%data) normal %normal unwind %catch
1114         //
1115         //   normal:
1116         //      ret 0
1117         //
1118         //   catch:
1119         //      (%ptr, _) = landingpad
1120         //      call %catch_func(%data, %ptr)
1121         //      ret 1
1122
1123         bx.sideeffect();
1124
1125         let mut then = bx.build_sibling_block("then");
1126         let mut catch = bx.build_sibling_block("catch");
1127
1128         let try_func = llvm::get_param(bx.llfn(), 0);
1129         let data = llvm::get_param(bx.llfn(), 1);
1130         let catch_func = llvm::get_param(bx.llfn(), 2);
1131         bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1132         then.ret(bx.const_i32(0));
1133
1134         // Type indicator for the exception being thrown.
1135         //
1136         // The first value in this tuple is a pointer to the exception object
1137         // being thrown.  The second value is a "selector" indicating which of
1138         // the landing pad clauses the exception's type had been matched to.
1139         // rust_try ignores the selector.
1140         let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1141         let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1142         let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1143             Some(tydesc) => {
1144                 let tydesc = bx.get_static(tydesc);
1145                 bx.bitcast(tydesc, bx.type_i8p())
1146             }
1147             None => bx.const_null(bx.type_i8p()),
1148         };
1149         catch.add_clause(vals, tydesc);
1150         let ptr = catch.extract_value(vals, 0);
1151         catch.call(catch_func, &[data, ptr], None);
1152         catch.ret(bx.const_i32(1));
1153     });
1154
1155     // Note that no invoke is used here because by definition this function
1156     // can't panic (that's what it's catching).
1157     let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1158     let i32_align = bx.tcx().data_layout.i32_align.abi;
1159     bx.store(ret, dest, i32_align);
1160 }
1161
1162 // Helper function to give a Block to a closure to codegen a shim function.
1163 // This is currently primarily used for the `try` intrinsic functions above.
1164 fn gen_fn<'ll, 'tcx>(
1165     cx: &CodegenCx<'ll, 'tcx>,
1166     name: &str,
1167     inputs: Vec<Ty<'tcx>>,
1168     output: Ty<'tcx>,
1169     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1170 ) -> &'ll Value {
1171     let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1172         inputs.into_iter(),
1173         output,
1174         false,
1175         hir::Unsafety::Unsafe,
1176         Abi::Rust,
1177     ));
1178     let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1179     let llfn = cx.declare_fn(name, &fn_abi);
1180     cx.set_frame_pointer_elimination(llfn);
1181     cx.apply_target_cpu_attr(llfn);
1182     // FIXME(eddyb) find a nicer way to do this.
1183     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1184     let bx = Builder::new_block(cx, llfn, "entry-block");
1185     codegen(bx);
1186     llfn
1187 }
1188
1189 // Helper function used to get a handle to the `__rust_try` function used to
1190 // catch exceptions.
1191 //
1192 // This function is only generated once and is then cached.
1193 fn get_rust_try_fn<'ll, 'tcx>(
1194     cx: &CodegenCx<'ll, 'tcx>,
1195     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1196 ) -> &'ll Value {
1197     if let Some(llfn) = cx.rust_try_fn.get() {
1198         return llfn;
1199     }
1200
1201     // Define the type up front for the signature of the rust_try function.
1202     let tcx = cx.tcx;
1203     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1204     let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1205         iter::once(i8p),
1206         tcx.mk_unit(),
1207         false,
1208         hir::Unsafety::Unsafe,
1209         Abi::Rust,
1210     )));
1211     let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1212         [i8p, i8p].iter().cloned(),
1213         tcx.mk_unit(),
1214         false,
1215         hir::Unsafety::Unsafe,
1216         Abi::Rust,
1217     )));
1218     let output = tcx.types.i32;
1219     let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1220     cx.rust_try_fn.set(Some(rust_try));
1221     rust_try
1222 }
1223
1224 fn generic_simd_intrinsic(
1225     bx: &mut Builder<'a, 'll, 'tcx>,
1226     name: Symbol,
1227     callee_ty: Ty<'tcx>,
1228     args: &[OperandRef<'tcx, &'ll Value>],
1229     ret_ty: Ty<'tcx>,
1230     llret_ty: &'ll Type,
1231     span: Span,
1232 ) -> Result<&'ll Value, ()> {
1233     // macros for error handling:
1234     macro_rules! emit_error {
1235         ($msg: tt) => {
1236             emit_error!($msg, )
1237         };
1238         ($msg: tt, $($fmt: tt)*) => {
1239             span_invalid_monomorphization_error(
1240                 bx.sess(), span,
1241                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1242                          name, $($fmt)*));
1243         }
1244     }
1245
1246     macro_rules! return_error {
1247         ($($fmt: tt)*) => {
1248             {
1249                 emit_error!($($fmt)*);
1250                 return Err(());
1251             }
1252         }
1253     }
1254
1255     macro_rules! require {
1256         ($cond: expr, $($fmt: tt)*) => {
1257             if !$cond {
1258                 return_error!($($fmt)*);
1259             }
1260         };
1261     }
1262
1263     macro_rules! require_simd {
1264         ($ty: expr, $position: expr) => {
1265             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1266         };
1267     }
1268
1269     let tcx = bx.tcx();
1270     let sig = tcx
1271         .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1272     let arg_tys = sig.inputs();
1273     let name_str = &*name.as_str();
1274
1275     if name == sym::simd_select_bitmask {
1276         let in_ty = arg_tys[0];
1277         let m_len = match in_ty.kind {
1278             // Note that this `.unwrap()` crashes for isize/usize, that's sort
1279             // of intentional as there's not currently a use case for that.
1280             ty::Int(i) => i.bit_width().unwrap(),
1281             ty::Uint(i) => i.bit_width().unwrap(),
1282             _ => return_error!("`{}` is not an integral type", in_ty),
1283         };
1284         require_simd!(arg_tys[1], "argument");
1285         let v_len = arg_tys[1].simd_size(tcx);
1286         require!(
1287             m_len == v_len,
1288             "mismatched lengths: mask length `{}` != other vector length `{}`",
1289             m_len,
1290             v_len
1291         );
1292         let i1 = bx.type_i1();
1293         let i1xn = bx.type_vector(i1, m_len);
1294         let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1295         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1296     }
1297
1298     // every intrinsic below takes a SIMD vector as its first argument
1299     require_simd!(arg_tys[0], "input");
1300     let in_ty = arg_tys[0];
1301     let in_elem = arg_tys[0].simd_type(tcx);
1302     let in_len = arg_tys[0].simd_size(tcx);
1303
1304     let comparison = match name {
1305         sym::simd_eq => Some(hir::BinOpKind::Eq),
1306         sym::simd_ne => Some(hir::BinOpKind::Ne),
1307         sym::simd_lt => Some(hir::BinOpKind::Lt),
1308         sym::simd_le => Some(hir::BinOpKind::Le),
1309         sym::simd_gt => Some(hir::BinOpKind::Gt),
1310         sym::simd_ge => Some(hir::BinOpKind::Ge),
1311         _ => None,
1312     };
1313
1314     if let Some(cmp_op) = comparison {
1315         require_simd!(ret_ty, "return");
1316
1317         let out_len = ret_ty.simd_size(tcx);
1318         require!(
1319             in_len == out_len,
1320             "expected return type with length {} (same as input type `{}`), \
1321                   found `{}` with length {}",
1322             in_len,
1323             in_ty,
1324             ret_ty,
1325             out_len
1326         );
1327         require!(
1328             bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1329             "expected return type with integer elements, found `{}` with non-integer `{}`",
1330             ret_ty,
1331             ret_ty.simd_type(tcx)
1332         );
1333
1334         return Ok(compare_simd_types(
1335             bx,
1336             args[0].immediate(),
1337             args[1].immediate(),
1338             in_elem,
1339             llret_ty,
1340             cmp_op,
1341         ));
1342     }
1343
1344     if name_str.starts_with("simd_shuffle") {
1345         let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1346             span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1347         });
1348
1349         require_simd!(ret_ty, "return");
1350
1351         let out_len = ret_ty.simd_size(tcx);
1352         require!(
1353             out_len == n,
1354             "expected return type of length {}, found `{}` with length {}",
1355             n,
1356             ret_ty,
1357             out_len
1358         );
1359         require!(
1360             in_elem == ret_ty.simd_type(tcx),
1361             "expected return element type `{}` (element of input `{}`), \
1362                   found `{}` with element type `{}`",
1363             in_elem,
1364             in_ty,
1365             ret_ty,
1366             ret_ty.simd_type(tcx)
1367         );
1368
1369         let total_len = u128::from(in_len) * 2;
1370
1371         let vector = args[2].immediate();
1372
1373         let indices: Option<Vec<_>> = (0..n)
1374             .map(|i| {
1375                 let arg_idx = i;
1376                 let val = bx.const_get_elt(vector, i as u64);
1377                 match bx.const_to_opt_u128(val, true) {
1378                     None => {
1379                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1380                         None
1381                     }
1382                     Some(idx) if idx >= total_len => {
1383                         emit_error!(
1384                             "shuffle index #{} is out of bounds (limit {})",
1385                             arg_idx,
1386                             total_len
1387                         );
1388                         None
1389                     }
1390                     Some(idx) => Some(bx.const_i32(idx as i32)),
1391                 }
1392             })
1393             .collect();
1394         let indices = match indices {
1395             Some(i) => i,
1396             None => return Ok(bx.const_null(llret_ty)),
1397         };
1398
1399         return Ok(bx.shuffle_vector(
1400             args[0].immediate(),
1401             args[1].immediate(),
1402             bx.const_vector(&indices),
1403         ));
1404     }
1405
1406     if name == sym::simd_insert {
1407         require!(
1408             in_elem == arg_tys[2],
1409             "expected inserted type `{}` (element of input `{}`), found `{}`",
1410             in_elem,
1411             in_ty,
1412             arg_tys[2]
1413         );
1414         return Ok(bx.insert_element(
1415             args[0].immediate(),
1416             args[2].immediate(),
1417             args[1].immediate(),
1418         ));
1419     }
1420     if name == sym::simd_extract {
1421         require!(
1422             ret_ty == in_elem,
1423             "expected return type `{}` (element of input `{}`), found `{}`",
1424             in_elem,
1425             in_ty,
1426             ret_ty
1427         );
1428         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1429     }
1430
1431     if name == sym::simd_select {
1432         let m_elem_ty = in_elem;
1433         let m_len = in_len;
1434         require_simd!(arg_tys[1], "argument");
1435         let v_len = arg_tys[1].simd_size(tcx);
1436         require!(
1437             m_len == v_len,
1438             "mismatched lengths: mask length `{}` != other vector length `{}`",
1439             m_len,
1440             v_len
1441         );
1442         match m_elem_ty.kind {
1443             ty::Int(_) => {}
1444             _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1445         }
1446         // truncate the mask to a vector of i1s
1447         let i1 = bx.type_i1();
1448         let i1xn = bx.type_vector(i1, m_len as u64);
1449         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1450         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1451     }
1452
1453     if name == sym::simd_bitmask {
1454         // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1455         // vector mask and returns an unsigned integer containing the most
1456         // significant bit (MSB) of each lane.
1457
1458         // If the vector has less than 8 lanes, an u8 is returned with zeroed
1459         // trailing bits.
1460         let expected_int_bits = in_len.max(8);
1461         match ret_ty.kind {
1462             ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1463             _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1464         }
1465
1466         // Integer vector <i{in_bitwidth} x in_len>:
1467         let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1468             ty::Int(i) => {
1469                 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1470             }
1471             ty::Uint(i) => {
1472                 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1473             }
1474             _ => return_error!(
1475                 "vector argument `{}`'s element type `{}`, expected integer element type",
1476                 in_ty,
1477                 in_elem
1478             ),
1479         };
1480
1481         // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1482         let shift_indices =
1483             vec![
1484                 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1485                 in_len as _
1486             ];
1487         let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1488         // Truncate vector to an <i1 x N>
1489         let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1490         // Bitcast <i1 x N> to iN:
1491         let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1492         // Zero-extend iN to the bitmask type:
1493         return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1494     }
1495
1496     fn simd_simple_float_intrinsic(
1497         name: &str,
1498         in_elem: &::rustc_middle::ty::TyS<'_>,
1499         in_ty: &::rustc_middle::ty::TyS<'_>,
1500         in_len: u64,
1501         bx: &mut Builder<'a, 'll, 'tcx>,
1502         span: Span,
1503         args: &[OperandRef<'tcx, &'ll Value>],
1504     ) -> Result<&'ll Value, ()> {
1505         macro_rules! emit_error {
1506             ($msg: tt) => {
1507                 emit_error!($msg, )
1508             };
1509             ($msg: tt, $($fmt: tt)*) => {
1510                 span_invalid_monomorphization_error(
1511                     bx.sess(), span,
1512                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1513                              name, $($fmt)*));
1514             }
1515         }
1516         macro_rules! return_error {
1517             ($($fmt: tt)*) => {
1518                 {
1519                     emit_error!($($fmt)*);
1520                     return Err(());
1521                 }
1522             }
1523         }
1524         let ety = match in_elem.kind {
1525             ty::Float(f) if f.bit_width() == 32 => {
1526                 if in_len < 2 || in_len > 16 {
1527                     return_error!(
1528                         "unsupported floating-point vector `{}` with length `{}` \
1529                          out-of-range [2, 16]",
1530                         in_ty,
1531                         in_len
1532                     );
1533                 }
1534                 "f32"
1535             }
1536             ty::Float(f) if f.bit_width() == 64 => {
1537                 if in_len < 2 || in_len > 8 {
1538                     return_error!(
1539                         "unsupported floating-point vector `{}` with length `{}` \
1540                                    out-of-range [2, 8]",
1541                         in_ty,
1542                         in_len
1543                     );
1544                 }
1545                 "f64"
1546             }
1547             ty::Float(f) => {
1548                 return_error!(
1549                     "unsupported element type `{}` of floating-point vector `{}`",
1550                     f.name_str(),
1551                     in_ty
1552                 );
1553             }
1554             _ => {
1555                 return_error!("`{}` is not a floating-point type", in_ty);
1556             }
1557         };
1558
1559         let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1560         let intrinsic = bx.get_intrinsic(&llvm_name);
1561         let c =
1562             bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1563         unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1564         Ok(c)
1565     }
1566
1567     match name {
1568         sym::simd_fsqrt => {
1569             return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1570         }
1571         sym::simd_fsin => {
1572             return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1573         }
1574         sym::simd_fcos => {
1575             return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1576         }
1577         sym::simd_fabs => {
1578             return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1579         }
1580         sym::simd_floor => {
1581             return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1582         }
1583         sym::simd_ceil => {
1584             return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1585         }
1586         sym::simd_fexp => {
1587             return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1588         }
1589         sym::simd_fexp2 => {
1590             return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1591         }
1592         sym::simd_flog10 => {
1593             return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1594         }
1595         sym::simd_flog2 => {
1596             return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1597         }
1598         sym::simd_flog => {
1599             return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1600         }
1601         sym::simd_fpowi => {
1602             return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1603         }
1604         sym::simd_fpow => {
1605             return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1606         }
1607         sym::simd_fma => {
1608             return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1609         }
1610         _ => { /* fallthrough */ }
1611     }
1612
1613     // FIXME: use:
1614     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1615     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1616     fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1617         let p0s: String = "p0".repeat(no_pointers);
1618         match elem_ty.kind {
1619             ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1620             ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1621             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1622             _ => unreachable!(),
1623         }
1624     }
1625
1626     fn llvm_vector_ty(
1627         cx: &CodegenCx<'ll, '_>,
1628         elem_ty: Ty<'_>,
1629         vec_len: u64,
1630         mut no_pointers: usize,
1631     ) -> &'ll Type {
1632         // FIXME: use cx.layout_of(ty).llvm_type() ?
1633         let mut elem_ty = match elem_ty.kind {
1634             ty::Int(v) => cx.type_int_from_ty(v),
1635             ty::Uint(v) => cx.type_uint_from_ty(v),
1636             ty::Float(v) => cx.type_float_from_ty(v),
1637             _ => unreachable!(),
1638         };
1639         while no_pointers > 0 {
1640             elem_ty = cx.type_ptr_to(elem_ty);
1641             no_pointers -= 1;
1642         }
1643         cx.type_vector(elem_ty, vec_len)
1644     }
1645
1646     if name == sym::simd_gather {
1647         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1648         //             mask: <N x i{M}>) -> <N x T>
1649         // * N: number of elements in the input vectors
1650         // * T: type of the element to load
1651         // * M: any integer width is supported, will be truncated to i1
1652
1653         // All types must be simd vector types
1654         require_simd!(in_ty, "first");
1655         require_simd!(arg_tys[1], "second");
1656         require_simd!(arg_tys[2], "third");
1657         require_simd!(ret_ty, "return");
1658
1659         // Of the same length:
1660         require!(
1661             in_len == arg_tys[1].simd_size(tcx),
1662             "expected {} argument with length {} (same as input type `{}`), \
1663                   found `{}` with length {}",
1664             "second",
1665             in_len,
1666             in_ty,
1667             arg_tys[1],
1668             arg_tys[1].simd_size(tcx)
1669         );
1670         require!(
1671             in_len == arg_tys[2].simd_size(tcx),
1672             "expected {} argument with length {} (same as input type `{}`), \
1673                   found `{}` with length {}",
1674             "third",
1675             in_len,
1676             in_ty,
1677             arg_tys[2],
1678             arg_tys[2].simd_size(tcx)
1679         );
1680
1681         // The return type must match the first argument type
1682         require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1683
1684         // This counts how many pointers
1685         fn ptr_count(t: Ty<'_>) -> usize {
1686             match t.kind {
1687                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1688                 _ => 0,
1689             }
1690         }
1691
1692         // Non-ptr type
1693         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1694             match t.kind {
1695                 ty::RawPtr(p) => non_ptr(p.ty),
1696                 _ => t,
1697             }
1698         }
1699
1700         // The second argument must be a simd vector with an element type that's a pointer
1701         // to the element type of the first argument
1702         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1703             ty::RawPtr(p) if p.ty == in_elem => {
1704                 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1705             }
1706             _ => {
1707                 require!(
1708                     false,
1709                     "expected element type `{}` of second argument `{}` \
1710                                  to be a pointer to the element type `{}` of the first \
1711                                  argument `{}`, found `{}` != `*_ {}`",
1712                     arg_tys[1].simd_type(tcx),
1713                     arg_tys[1],
1714                     in_elem,
1715                     in_ty,
1716                     arg_tys[1].simd_type(tcx),
1717                     in_elem
1718                 );
1719                 unreachable!();
1720             }
1721         };
1722         assert!(pointer_count > 0);
1723         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1724         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1725
1726         // The element type of the third argument must be a signed integer type of any width:
1727         match arg_tys[2].simd_type(tcx).kind {
1728             ty::Int(_) => (),
1729             _ => {
1730                 require!(
1731                     false,
1732                     "expected element type `{}` of third argument `{}` \
1733                                  to be a signed integer type",
1734                     arg_tys[2].simd_type(tcx),
1735                     arg_tys[2]
1736                 );
1737             }
1738         }
1739
1740         // Alignment of T, must be a constant integer value:
1741         let alignment_ty = bx.type_i32();
1742         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1743
1744         // Truncate the mask vector to a vector of i1s:
1745         let (mask, mask_ty) = {
1746             let i1 = bx.type_i1();
1747             let i1xn = bx.type_vector(i1, in_len);
1748             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1749         };
1750
1751         // Type of the vector of pointers:
1752         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1753         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1754
1755         // Type of the vector of elements:
1756         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1757         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1758
1759         let llvm_intrinsic =
1760             format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1761         let f = bx.declare_cfn(
1762             &llvm_intrinsic,
1763             bx.type_func(
1764                 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1765                 llvm_elem_vec_ty,
1766             ),
1767         );
1768         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1769         let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1770         return Ok(v);
1771     }
1772
1773     if name == sym::simd_scatter {
1774         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1775         //             mask: <N x i{M}>) -> ()
1776         // * N: number of elements in the input vectors
1777         // * T: type of the element to load
1778         // * M: any integer width is supported, will be truncated to i1
1779
1780         // All types must be simd vector types
1781         require_simd!(in_ty, "first");
1782         require_simd!(arg_tys[1], "second");
1783         require_simd!(arg_tys[2], "third");
1784
1785         // Of the same length:
1786         require!(
1787             in_len == arg_tys[1].simd_size(tcx),
1788             "expected {} argument with length {} (same as input type `{}`), \
1789                   found `{}` with length {}",
1790             "second",
1791             in_len,
1792             in_ty,
1793             arg_tys[1],
1794             arg_tys[1].simd_size(tcx)
1795         );
1796         require!(
1797             in_len == arg_tys[2].simd_size(tcx),
1798             "expected {} argument with length {} (same as input type `{}`), \
1799                   found `{}` with length {}",
1800             "third",
1801             in_len,
1802             in_ty,
1803             arg_tys[2],
1804             arg_tys[2].simd_size(tcx)
1805         );
1806
1807         // This counts how many pointers
1808         fn ptr_count(t: Ty<'_>) -> usize {
1809             match t.kind {
1810                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1811                 _ => 0,
1812             }
1813         }
1814
1815         // Non-ptr type
1816         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1817             match t.kind {
1818                 ty::RawPtr(p) => non_ptr(p.ty),
1819                 _ => t,
1820             }
1821         }
1822
1823         // The second argument must be a simd vector with an element type that's a pointer
1824         // to the element type of the first argument
1825         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1826             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1827                 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1828             }
1829             _ => {
1830                 require!(
1831                     false,
1832                     "expected element type `{}` of second argument `{}` \
1833                                  to be a pointer to the element type `{}` of the first \
1834                                  argument `{}`, found `{}` != `*mut {}`",
1835                     arg_tys[1].simd_type(tcx),
1836                     arg_tys[1],
1837                     in_elem,
1838                     in_ty,
1839                     arg_tys[1].simd_type(tcx),
1840                     in_elem
1841                 );
1842                 unreachable!();
1843             }
1844         };
1845         assert!(pointer_count > 0);
1846         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1847         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1848
1849         // The element type of the third argument must be a signed integer type of any width:
1850         match arg_tys[2].simd_type(tcx).kind {
1851             ty::Int(_) => (),
1852             _ => {
1853                 require!(
1854                     false,
1855                     "expected element type `{}` of third argument `{}` \
1856                                  to be a signed integer type",
1857                     arg_tys[2].simd_type(tcx),
1858                     arg_tys[2]
1859                 );
1860             }
1861         }
1862
1863         // Alignment of T, must be a constant integer value:
1864         let alignment_ty = bx.type_i32();
1865         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1866
1867         // Truncate the mask vector to a vector of i1s:
1868         let (mask, mask_ty) = {
1869             let i1 = bx.type_i1();
1870             let i1xn = bx.type_vector(i1, in_len);
1871             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1872         };
1873
1874         let ret_t = bx.type_void();
1875
1876         // Type of the vector of pointers:
1877         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1878         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1879
1880         // Type of the vector of elements:
1881         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1882         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1883
1884         let llvm_intrinsic =
1885             format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1886         let f = bx.declare_cfn(
1887             &llvm_intrinsic,
1888             bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1889         );
1890         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1891         let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1892         return Ok(v);
1893     }
1894
1895     macro_rules! arith_red {
1896         ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1897          $identity:expr) => {
1898             if name == sym::$name {
1899                 require!(
1900                     ret_ty == in_elem,
1901                     "expected return type `{}` (element of input `{}`), found `{}`",
1902                     in_elem,
1903                     in_ty,
1904                     ret_ty
1905                 );
1906                 return match in_elem.kind {
1907                     ty::Int(_) | ty::Uint(_) => {
1908                         let r = bx.$integer_reduce(args[0].immediate());
1909                         if $ordered {
1910                             // if overflow occurs, the result is the
1911                             // mathematical result modulo 2^n:
1912                             Ok(bx.$op(args[1].immediate(), r))
1913                         } else {
1914                             Ok(bx.$integer_reduce(args[0].immediate()))
1915                         }
1916                     }
1917                     ty::Float(f) => {
1918                         let acc = if $ordered {
1919                             // ordered arithmetic reductions take an accumulator
1920                             args[1].immediate()
1921                         } else {
1922                             // unordered arithmetic reductions use the identity accumulator
1923                             match f.bit_width() {
1924                                 32 => bx.const_real(bx.type_f32(), $identity),
1925                                 64 => bx.const_real(bx.type_f64(), $identity),
1926                                 v => return_error!(
1927                                     r#"
1928 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1929                                     sym::$name,
1930                                     in_ty,
1931                                     in_elem,
1932                                     v,
1933                                     ret_ty
1934                                 ),
1935                             }
1936                         };
1937                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1938                     }
1939                     _ => return_error!(
1940                         "unsupported {} from `{}` with element `{}` to `{}`",
1941                         sym::$name,
1942                         in_ty,
1943                         in_elem,
1944                         ret_ty
1945                     ),
1946                 };
1947             }
1948         };
1949     }
1950
1951     arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1952     arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1953     arith_red!(
1954         simd_reduce_add_unordered: vector_reduce_add,
1955         vector_reduce_fadd_fast,
1956         false,
1957         add,
1958         0.0
1959     );
1960     arith_red!(
1961         simd_reduce_mul_unordered: vector_reduce_mul,
1962         vector_reduce_fmul_fast,
1963         false,
1964         mul,
1965         1.0
1966     );
1967
1968     macro_rules! minmax_red {
1969         ($name:ident: $int_red:ident, $float_red:ident) => {
1970             if name == sym::$name {
1971                 require!(
1972                     ret_ty == in_elem,
1973                     "expected return type `{}` (element of input `{}`), found `{}`",
1974                     in_elem,
1975                     in_ty,
1976                     ret_ty
1977                 );
1978                 return match in_elem.kind {
1979                     ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1980                     ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1981                     ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1982                     _ => return_error!(
1983                         "unsupported {} from `{}` with element `{}` to `{}`",
1984                         sym::$name,
1985                         in_ty,
1986                         in_elem,
1987                         ret_ty
1988                     ),
1989                 };
1990             }
1991         };
1992     }
1993
1994     minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1995     minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1996
1997     minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1998     minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1999
2000     macro_rules! bitwise_red {
2001         ($name:ident : $red:ident, $boolean:expr) => {
2002             if name == sym::$name {
2003                 let input = if !$boolean {
2004                     require!(
2005                         ret_ty == in_elem,
2006                         "expected return type `{}` (element of input `{}`), found `{}`",
2007                         in_elem,
2008                         in_ty,
2009                         ret_ty
2010                     );
2011                     args[0].immediate()
2012                 } else {
2013                     match in_elem.kind {
2014                         ty::Int(_) | ty::Uint(_) => {}
2015                         _ => return_error!(
2016                             "unsupported {} from `{}` with element `{}` to `{}`",
2017                             sym::$name,
2018                             in_ty,
2019                             in_elem,
2020                             ret_ty
2021                         ),
2022                     }
2023
2024                     // boolean reductions operate on vectors of i1s:
2025                     let i1 = bx.type_i1();
2026                     let i1xn = bx.type_vector(i1, in_len as u64);
2027                     bx.trunc(args[0].immediate(), i1xn)
2028                 };
2029                 return match in_elem.kind {
2030                     ty::Int(_) | ty::Uint(_) => {
2031                         let r = bx.$red(input);
2032                         Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2033                     }
2034                     _ => return_error!(
2035                         "unsupported {} from `{}` with element `{}` to `{}`",
2036                         sym::$name,
2037                         in_ty,
2038                         in_elem,
2039                         ret_ty
2040                     ),
2041                 };
2042             }
2043         };
2044     }
2045
2046     bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2047     bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2048     bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2049     bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2050     bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2051
2052     if name == sym::simd_cast {
2053         require_simd!(ret_ty, "return");
2054         let out_len = ret_ty.simd_size(tcx);
2055         require!(
2056             in_len == out_len,
2057             "expected return type with length {} (same as input type `{}`), \
2058                   found `{}` with length {}",
2059             in_len,
2060             in_ty,
2061             ret_ty,
2062             out_len
2063         );
2064         // casting cares about nominal type, not just structural type
2065         let out_elem = ret_ty.simd_type(tcx);
2066
2067         if in_elem == out_elem {
2068             return Ok(args[0].immediate());
2069         }
2070
2071         enum Style {
2072             Float,
2073             Int(/* is signed? */ bool),
2074             Unsupported,
2075         }
2076
2077         let (in_style, in_width) = match in_elem.kind {
2078             // vectors of pointer-sized integers should've been
2079             // disallowed before here, so this unwrap is safe.
2080             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2081             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2082             ty::Float(f) => (Style::Float, f.bit_width()),
2083             _ => (Style::Unsupported, 0),
2084         };
2085         let (out_style, out_width) = match out_elem.kind {
2086             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2087             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2088             ty::Float(f) => (Style::Float, f.bit_width()),
2089             _ => (Style::Unsupported, 0),
2090         };
2091
2092         match (in_style, out_style) {
2093             (Style::Int(in_is_signed), Style::Int(_)) => {
2094                 return Ok(match in_width.cmp(&out_width) {
2095                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2096                     Ordering::Equal => args[0].immediate(),
2097                     Ordering::Less => {
2098                         if in_is_signed {
2099                             bx.sext(args[0].immediate(), llret_ty)
2100                         } else {
2101                             bx.zext(args[0].immediate(), llret_ty)
2102                         }
2103                     }
2104                 });
2105             }
2106             (Style::Int(in_is_signed), Style::Float) => {
2107                 return Ok(if in_is_signed {
2108                     bx.sitofp(args[0].immediate(), llret_ty)
2109                 } else {
2110                     bx.uitofp(args[0].immediate(), llret_ty)
2111                 });
2112             }
2113             (Style::Float, Style::Int(out_is_signed)) => {
2114                 return Ok(if out_is_signed {
2115                     bx.fptosi(args[0].immediate(), llret_ty)
2116                 } else {
2117                     bx.fptoui(args[0].immediate(), llret_ty)
2118                 });
2119             }
2120             (Style::Float, Style::Float) => {
2121                 return Ok(match in_width.cmp(&out_width) {
2122                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2123                     Ordering::Equal => args[0].immediate(),
2124                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2125                 });
2126             }
2127             _ => { /* Unsupported. Fallthrough. */ }
2128         }
2129         require!(
2130             false,
2131             "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2132             in_ty,
2133             in_elem,
2134             ret_ty,
2135             out_elem
2136         );
2137     }
2138     macro_rules! arith {
2139         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2140             $(if name == sym::$name {
2141                 match in_elem.kind {
2142                     $($(ty::$p(_))|* => {
2143                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2144                     })*
2145                     _ => {},
2146                 }
2147                 require!(false,
2148                          "unsupported operation on `{}` with element `{}`",
2149                          in_ty,
2150                          in_elem)
2151             })*
2152         }
2153     }
2154     arith! {
2155         simd_add: Uint, Int => add, Float => fadd;
2156         simd_sub: Uint, Int => sub, Float => fsub;
2157         simd_mul: Uint, Int => mul, Float => fmul;
2158         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2159         simd_rem: Uint => urem, Int => srem, Float => frem;
2160         simd_shl: Uint, Int => shl;
2161         simd_shr: Uint => lshr, Int => ashr;
2162         simd_and: Uint, Int => and;
2163         simd_or: Uint, Int => or;
2164         simd_xor: Uint, Int => xor;
2165         simd_fmax: Float => maxnum;
2166         simd_fmin: Float => minnum;
2167
2168     }
2169
2170     if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2171         let lhs = args[0].immediate();
2172         let rhs = args[1].immediate();
2173         let is_add = name == sym::simd_saturating_add;
2174         let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2175         let (signed, elem_width, elem_ty) = match in_elem.kind {
2176             ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2177             ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2178             _ => {
2179                 return_error!(
2180                     "expected element type `{}` of vector type `{}` \
2181                      to be a signed or unsigned integer type",
2182                     arg_tys[0].simd_type(tcx),
2183                     arg_tys[0]
2184                 );
2185             }
2186         };
2187         let llvm_intrinsic = &format!(
2188             "llvm.{}{}.sat.v{}i{}",
2189             if signed { 's' } else { 'u' },
2190             if is_add { "add" } else { "sub" },
2191             in_len,
2192             elem_width
2193         );
2194         let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2195
2196         let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2197         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2198         let v = bx.call(f, &[lhs, rhs], None);
2199         return Ok(v);
2200     }
2201
2202     span_bug!(span, "unknown SIMD intrinsic");
2203 }
2204
2205 // Returns the width of an int Ty, and if it's signed or not
2206 // Returns None if the type is not an integer
2207 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2208 // stuffs.
2209 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2210     match ty.kind {
2211         ty::Int(t) => Some((
2212             match t {
2213                 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2214                 ast::IntTy::I8 => 8,
2215                 ast::IntTy::I16 => 16,
2216                 ast::IntTy::I32 => 32,
2217                 ast::IntTy::I64 => 64,
2218                 ast::IntTy::I128 => 128,
2219             },
2220             true,
2221         )),
2222         ty::Uint(t) => Some((
2223             match t {
2224                 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2225                 ast::UintTy::U8 => 8,
2226                 ast::UintTy::U16 => 16,
2227                 ast::UintTy::U32 => 32,
2228                 ast::UintTy::U64 => 64,
2229                 ast::UintTy::U128 => 128,
2230             },
2231             false,
2232         )),
2233         _ => None,
2234     }
2235 }
2236
2237 // Returns the width of a float Ty
2238 // Returns None if the type is not a float
2239 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2240     match ty.kind {
2241         ty::Float(t) => Some(t.bit_width()),
2242         _ => None,
2243     }
2244 }
2245
2246 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2247     Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")
2248 }
2249
2250 fn op_to_u64<'tcx>(op: &Operand<'tcx>) -> u64 {
2251     Operand::scalar_from_const(op).to_u64().expect("Scalar is u64")
2252 }