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