]> git.lizzy.rs Git - rust.git/blob - src/intrinsics.rs
[WIP] simd_shuffle*
[rust.git] / src / intrinsics.rs
1 use crate::prelude::*;
2
3 use rustc::ty::subst::SubstsRef;
4
5 macro_rules! intrinsic_pat {
6     (_) => {
7         _
8     };
9     ($name:ident) => {
10         stringify!($name)
11     }
12 }
13
14 macro_rules! intrinsic_arg {
15     (o $fx:expr, $arg:ident) => {
16         $arg
17     };
18     (c $fx:expr, $arg:ident) => {
19         trans_operand($fx, $arg)
20     };
21     (v $fx:expr, $arg:ident) => {
22         trans_operand($fx, $arg).load_scalar($fx)
23     };
24 }
25
26 macro_rules! intrinsic_substs {
27     ($substs:expr, $index:expr,) => {};
28     ($substs:expr, $index:expr, $first:ident $(,$rest:ident)*) => {
29         let $first = $substs.type_at($index);
30         intrinsic_substs!($substs, $index+1, $($rest),*);
31     };
32 }
33
34 macro_rules! intrinsic_match {
35     ($fx:expr, $intrinsic:expr, $substs:expr, $args:expr, $(
36         $($name:tt)|+ $(if $cond:expr)?, $(<$($subst:ident),*>)? ($($a:ident $arg:ident),*) $content:block;
37     )*) => {
38         match $intrinsic {
39             $(
40                 $(intrinsic_pat!($name))|* $(if $cond)? => {
41                     #[allow(unused_parens, non_snake_case)]
42                     {
43                         $(
44                             intrinsic_substs!($substs, 0, $($subst),*);
45                         )?
46                         if let [$($arg),*] = $args {
47                             let ($($arg,)*) = (
48                                 $(intrinsic_arg!($a $fx, $arg),)*
49                             );
50                             #[warn(unused_parens, non_snake_case)]
51                             {
52                                 $content
53                             }
54                         } else {
55                             bug!("wrong number of args for intrinsic {:?}", $intrinsic);
56                         }
57                     }
58                 }
59             )*
60             _ => unimpl!("unsupported intrinsic {}", $intrinsic),
61         }
62     };
63 }
64
65 macro_rules! call_intrinsic_match {
66     ($fx:expr, $intrinsic:expr, $substs:expr, $ret:expr, $destination:expr, $args:expr, $(
67         $name:ident($($arg:ident),*) -> $ty:ident => $func:ident,
68     )*) => {
69         match $intrinsic {
70             $(
71                 stringify!($name) => {
72                     assert!($substs.is_noop());
73                     if let [$(ref $arg),*] = *$args {
74                         let ($($arg,)*) = (
75                             $(trans_operand($fx, $arg),)*
76                         );
77                         let res = $fx.easy_call(stringify!($func), &[$($arg),*], $fx.tcx.types.$ty);
78                         $ret.write_cvalue($fx, res);
79
80                         if let Some((_, dest)) = $destination {
81                             let ret_ebb = $fx.get_ebb(dest);
82                             $fx.bcx.ins().jump(ret_ebb, &[]);
83                             return;
84                         } else {
85                             unreachable!();
86                         }
87                     } else {
88                         bug!("wrong number of args for intrinsic {:?}", $intrinsic);
89                     }
90                 }
91             )*
92             _ => {}
93         }
94     }
95 }
96
97 macro_rules! atomic_binop_return_old {
98     ($fx:expr, $op:ident<$T:ident>($ptr:ident, $src:ident) -> $ret:ident) => {
99         let clif_ty = $fx.clif_type($T).unwrap();
100         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
101         let new = $fx.bcx.ins().$op(old, $src);
102         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
103         $ret.write_cvalue($fx, CValue::by_val(old, $fx.layout_of($T)));
104     };
105 }
106
107 macro_rules! atomic_minmax {
108     ($fx:expr, $cc:expr, <$T:ident> ($ptr:ident, $src:ident) -> $ret:ident) => {
109         // Read old
110         let clif_ty = $fx.clif_type($T).unwrap();
111         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
112
113         // Compare
114         let is_eq = $fx.bcx.ins().icmp(IntCC::SignedGreaterThan, old, $src);
115         let new = crate::common::codegen_select(&mut $fx.bcx, is_eq, old, $src);
116
117         // Write new
118         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
119
120         let ret_val = CValue::by_val(old, $ret.layout());
121         $ret.write_cvalue($fx, ret_val);
122     };
123 }
124
125 fn lane_type_and_count<'tcx>(
126     fx: &FunctionCx<'_, 'tcx, impl Backend>,
127     layout: TyLayout<'tcx>,
128     intrinsic: &str,
129 ) -> (TyLayout<'tcx>, u32) {
130     assert!(layout.ty.is_simd());
131     let lane_count = match layout.fields {
132         layout::FieldPlacement::Array { stride: _, count } => u32::try_from(count).unwrap(),
133         _ => panic!("Non vector type {:?} passed to or returned from simd_* intrinsic {}", layout.ty, intrinsic),
134     };
135     let lane_layout = layout.field(fx, 0);
136     (lane_layout, lane_count)
137 }
138
139 fn simd_for_each_lane<'tcx, B: Backend>(
140     fx: &mut FunctionCx<'_, 'tcx, B>,
141     intrinsic: &str,
142     x: CValue<'tcx>,
143     y: CValue<'tcx>,
144     ret: CPlace<'tcx>,
145     f: impl Fn(&mut FunctionCx<'_, 'tcx, B>, TyLayout<'tcx>, TyLayout<'tcx>, Value, Value) -> CValue<'tcx>,
146 ) {
147     assert_eq!(x.layout(), y.layout());
148     let layout = x.layout();
149
150     let (lane_layout, lane_count) = lane_type_and_count(fx, layout, intrinsic);
151     let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic);
152     assert_eq!(lane_count, ret_lane_count);
153
154     for lane in 0..lane_count {
155         let lane = mir::Field::new(lane.try_into().unwrap());
156         let x_lane = x.value_field(fx, lane).load_scalar(fx);
157         let y_lane = y.value_field(fx, lane).load_scalar(fx);
158
159         let res_lane = f(fx, lane_layout, ret_lane_layout, x_lane, y_lane);
160
161         ret.place_field(fx, lane).write_cvalue(fx, res_lane);
162     }
163 }
164
165 fn bool_to_zero_or_max_uint<'tcx>(
166     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
167     layout: TyLayout<'tcx>,
168     val: Value,
169 ) -> CValue<'tcx> {
170     let ty = fx.clif_type(layout.ty).unwrap();
171
172     let zero = fx.bcx.ins().iconst(ty, 0);
173     let max = fx.bcx.ins().iconst(ty, (u64::max_value() >> (64 - ty.bits())) as i64);
174     let res = crate::common::codegen_select(&mut fx.bcx, val, max, zero);
175     CValue::by_val(res, layout)
176 }
177
178 macro_rules! simd_cmp {
179     ($fx:expr, $intrinsic:expr, $cc:ident($x:ident, $y:ident) -> $ret:ident) => {
180         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, _lane_layout, res_lane_layout, x_lane, y_lane| {
181             let res_lane = fx.bcx.ins().icmp(IntCC::$cc, x_lane, y_lane);
182             bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
183         });
184     };
185     ($fx:expr, $intrinsic:expr, $cc_u:ident|$cc_s:ident($x:ident, $y:ident) -> $ret:ident) => {
186         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, res_lane_layout, x_lane, y_lane| {
187             let res_lane = match lane_layout.ty.sty {
188                 ty::Uint(_) => fx.bcx.ins().icmp(IntCC::$cc_u, x_lane, y_lane),
189                 ty::Int(_) => fx.bcx.ins().icmp(IntCC::$cc_s, x_lane, y_lane),
190                 _ => unreachable!("{:?}", lane_layout.ty),
191             };
192             bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
193         });
194     };
195
196 }
197
198 macro_rules! simd_binop {
199     ($fx:expr, $intrinsic:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) => {
200         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, _lane_layout, ret_lane_layout, x_lane, y_lane| {
201             let res_lane = fx.bcx.ins().$op(x_lane, y_lane);
202             CValue::by_val(res_lane, ret_lane_layout)
203         });
204     };
205     ($fx:expr, $intrinsic:expr, $op_u:ident|$op_s:ident($x:ident, $y:ident) -> $ret:ident) => {
206         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| {
207             let res_lane = match lane_layout.ty.sty {
208                 ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane),
209                 ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane),
210                 _ => unreachable!("{:?}", lane_layout.ty),
211             };
212             CValue::by_val(res_lane, ret_lane_layout)
213         });
214     };
215 }
216
217 pub fn codegen_intrinsic_call<'a, 'tcx: 'a>(
218     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
219     def_id: DefId,
220     substs: SubstsRef<'tcx>,
221     args: &[mir::Operand<'tcx>],
222     destination: Option<(CPlace<'tcx>, BasicBlock)>,
223 ) {
224     let intrinsic = fx.tcx.item_name(def_id).as_str();
225     let intrinsic = &intrinsic[..];
226
227     let ret = match destination {
228         Some((place, _)) => place,
229         None => {
230             // Insert non returning intrinsics here
231             match intrinsic {
232                 "abort" => {
233                     trap_panic(fx, "Called intrinsic::abort.");
234                 }
235                 "unreachable" => {
236                     trap_unreachable(fx, "[corruption] Called intrinsic::unreachable.");
237                 }
238                 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
239             }
240             return;
241         }
242     };
243
244     let u64_layout = fx.layout_of(fx.tcx.types.u64);
245     let usize_layout = fx.layout_of(fx.tcx.types.usize);
246
247     call_intrinsic_match! {
248         fx, intrinsic, substs, ret, destination, args,
249         expf32(flt) -> f32 => expf,
250         expf64(flt) -> f64 => exp,
251         exp2f32(flt) -> f32 => exp2f,
252         exp2f64(flt) -> f64 => exp2,
253         sqrtf32(flt) -> f32 => sqrtf,
254         sqrtf64(flt) -> f64 => sqrt,
255         powif32(a, x) -> f32 => __powisf2, // compiler-builtins
256         powif64(a, x) -> f64 => __powidf2, // compiler-builtins
257         logf32(flt) -> f32 => logf,
258         logf64(flt) -> f64 => log,
259         fabsf32(flt) -> f32 => fabsf,
260         fabsf64(flt) -> f64 => fabs,
261         fmaf32(x, y, z) -> f32 => fmaf,
262         fmaf64(x, y, z) -> f64 => fma,
263
264         // rounding variants
265         floorf32(flt) -> f32 => floorf,
266         floorf64(flt) -> f64 => floor,
267         ceilf32(flt) -> f32 => ceilf,
268         ceilf64(flt) -> f64 => ceil,
269         truncf32(flt) -> f32 => truncf,
270         truncf64(flt) -> f64 => trunc,
271         roundf32(flt) -> f32 => roundf,
272         roundf64(flt) -> f64 => round,
273
274         // trigonometry
275         sinf32(flt) -> f32 => sinf,
276         sinf64(flt) -> f64 => sin,
277         cosf32(flt) -> f32 => cosf,
278         cosf64(flt) -> f64 => cos,
279         tanf32(flt) -> f32 => tanf,
280         tanf64(flt) -> f64 => tan,
281     }
282
283     intrinsic_match! {
284         fx, intrinsic, substs, args,
285
286         assume, (c _a) {};
287         likely | unlikely, (c a) {
288             ret.write_cvalue(fx, a);
289         };
290         breakpoint, () {
291             fx.bcx.ins().debugtrap();
292         };
293         copy | copy_nonoverlapping, <elem_ty> (v src, v dst, v count) {
294             let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
295             let elem_size = fx
296                 .bcx
297                 .ins()
298                 .iconst(fx.pointer_type, elem_size as i64);
299             assert_eq!(args.len(), 3);
300             let byte_amount = fx.bcx.ins().imul(count, elem_size);
301
302             if intrinsic.ends_with("_nonoverlapping") {
303                 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
304             } else {
305                 fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
306             }
307         };
308         discriminant_value, (c val) {
309             let pointee_layout = fx.layout_of(val.layout().ty.builtin_deref(true).unwrap().ty);
310             let place = CPlace::for_addr(val.load_scalar(fx), pointee_layout);
311             let discr = crate::base::trans_get_discriminant(fx, place, ret.layout());
312             ret.write_cvalue(fx, discr);
313         };
314         size_of, <T> () {
315             let size_of = fx.layout_of(T).size.bytes();
316             let size_of = CValue::const_val(fx, usize_layout.ty, size_of.into());
317             ret.write_cvalue(fx, size_of);
318         };
319         size_of_val, <T> (c ptr) {
320             let layout = fx.layout_of(T);
321             let size = if layout.is_unsized() {
322                 let (_ptr, info) = ptr.load_scalar_pair(fx);
323                 let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
324                 size
325             } else {
326                 fx
327                     .bcx
328                     .ins()
329                     .iconst(fx.pointer_type, layout.size.bytes() as i64)
330             };
331             ret.write_cvalue(fx, CValue::by_val(size, usize_layout));
332         };
333         min_align_of, <T> () {
334             let min_align = fx.layout_of(T).align.abi.bytes();
335             let min_align = CValue::const_val(fx, usize_layout.ty, min_align.into());
336             ret.write_cvalue(fx, min_align);
337         };
338         min_align_of_val, <T> (c ptr) {
339             let layout = fx.layout_of(T);
340             let align = if layout.is_unsized() {
341                 let (_ptr, info) = ptr.load_scalar_pair(fx);
342                 let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
343                 align
344             } else {
345                 fx
346                     .bcx
347                     .ins()
348                     .iconst(fx.pointer_type, layout.align.abi.bytes() as i64)
349             };
350             ret.write_cvalue(fx, CValue::by_val(align, usize_layout));
351         };
352         pref_align_of, <T> () {
353             let pref_align = fx.layout_of(T).align.pref.bytes();
354             let pref_align = CValue::const_val(fx, usize_layout.ty, pref_align.into());
355             ret.write_cvalue(fx, pref_align);
356         };
357
358
359         type_id, <T> () {
360             let type_id = fx.tcx.type_id_hash(T);
361             let type_id = CValue::const_val(fx, u64_layout.ty, type_id.into());
362             ret.write_cvalue(fx, type_id);
363         };
364         type_name, <T> () {
365             let type_name = fx.tcx.type_name(T);
366             let type_name = crate::constant::trans_const_value(fx, type_name);
367             ret.write_cvalue(fx, type_name);
368         };
369
370         _ if intrinsic.starts_with("unchecked_") || intrinsic == "exact_div", (c x, c y) {
371             // FIXME trap on overflow
372             let bin_op = match intrinsic {
373                 "unchecked_sub" => BinOp::Sub,
374                 "unchecked_div" | "exact_div" => BinOp::Div,
375                 "unchecked_rem" => BinOp::Rem,
376                 "unchecked_shl" => BinOp::Shl,
377                 "unchecked_shr" => BinOp::Shr,
378                 _ => unimplemented!("intrinsic {}", intrinsic),
379             };
380             let res = match ret.layout().ty.sty {
381                 ty::Uint(_) => crate::base::trans_int_binop(
382                     fx,
383                     bin_op,
384                     x,
385                     y,
386                     ret.layout().ty,
387                     false,
388                 ),
389                 ty::Int(_) => crate::base::trans_int_binop(
390                     fx,
391                     bin_op,
392                     x,
393                     y,
394                     ret.layout().ty,
395                     true,
396                 ),
397                 _ => panic!(),
398             };
399             ret.write_cvalue(fx, res);
400         };
401         _ if intrinsic.ends_with("_with_overflow"), <T> (c x, c y) {
402             assert_eq!(x.layout().ty, y.layout().ty);
403             let bin_op = match intrinsic {
404                 "add_with_overflow" => BinOp::Add,
405                 "sub_with_overflow" => BinOp::Sub,
406                 "mul_with_overflow" => BinOp::Mul,
407                 _ => unimplemented!("intrinsic {}", intrinsic),
408             };
409             let res = match T.sty {
410                 ty::Uint(_) => crate::base::trans_checked_int_binop(
411                     fx,
412                     bin_op,
413                     x,
414                     y,
415                     ret.layout().ty,
416                     false,
417                 ),
418                 ty::Int(_) => crate::base::trans_checked_int_binop(
419                     fx,
420                     bin_op,
421                     x,
422                     y,
423                     ret.layout().ty,
424                     true,
425                 ),
426                 _ => panic!(),
427             };
428             ret.write_cvalue(fx, res);
429         };
430         _ if intrinsic.starts_with("overflowing_"), <T> (c x, c y) {
431             assert_eq!(x.layout().ty, y.layout().ty);
432             let bin_op = match intrinsic {
433                 "overflowing_add" => BinOp::Add,
434                 "overflowing_sub" => BinOp::Sub,
435                 "overflowing_mul" => BinOp::Mul,
436                 _ => unimplemented!("intrinsic {}", intrinsic),
437             };
438             let res = match T.sty {
439                 ty::Uint(_) => crate::base::trans_int_binop(
440                     fx,
441                     bin_op,
442                     x,
443                     y,
444                     ret.layout().ty,
445                     false,
446                 ),
447                 ty::Int(_) => crate::base::trans_int_binop(
448                     fx,
449                     bin_op,
450                     x,
451                     y,
452                     ret.layout().ty,
453                     true,
454                 ),
455                 _ => panic!(),
456             };
457             ret.write_cvalue(fx, res);
458         };
459         _ if intrinsic.starts_with("saturating_"), <T> (c x, c y) {
460             // FIXME implement saturating behavior
461             assert_eq!(x.layout().ty, y.layout().ty);
462             let bin_op = match intrinsic {
463                 "saturating_add" => BinOp::Add,
464                 "saturating_sub" => BinOp::Sub,
465                 "saturating_mul" => BinOp::Mul,
466                 _ => unimplemented!("intrinsic {}", intrinsic),
467             };
468             let res = match T.sty {
469                 ty::Uint(_) => crate::base::trans_int_binop(
470                     fx,
471                     bin_op,
472                     x,
473                     y,
474                     ret.layout().ty,
475                     false,
476                 ),
477                 ty::Int(_) => crate::base::trans_int_binop(
478                     fx,
479                     bin_op,
480                     x,
481                     y,
482                     ret.layout().ty,
483                     true,
484                 ),
485                 _ => panic!(),
486             };
487             ret.write_cvalue(fx, res);
488         };
489         rotate_left, <T>(v x, v y) {
490             let layout = fx.layout_of(T);
491             let res = fx.bcx.ins().rotl(x, y);
492             ret.write_cvalue(fx, CValue::by_val(res, layout));
493         };
494         rotate_right, <T>(v x, v y) {
495             let layout = fx.layout_of(T);
496             let res = fx.bcx.ins().rotr(x, y);
497             ret.write_cvalue(fx, CValue::by_val(res, layout));
498         };
499
500         // The only difference between offset and arith_offset is regarding UB. Because Cranelift
501         // doesn't have UB both are codegen'ed the same way
502         offset | arith_offset, (c base, v offset) {
503             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
504             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
505             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
506             let base_val = base.load_scalar(fx);
507             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
508             ret.write_cvalue(fx, CValue::by_val(res, base.layout()));
509         };
510
511         transmute, <src_ty, dst_ty> (c from) {
512             assert_eq!(from.layout().ty, src_ty);
513             let addr = from.force_stack(fx);
514             let dst_layout = fx.layout_of(dst_ty);
515             ret.write_cvalue(fx, CValue::by_ref(addr, dst_layout))
516         };
517         init, () {
518             if ret.layout().abi == Abi::Uninhabited {
519                 crate::trap::trap_panic(fx, "[panic] Called intrinsic::init for uninhabited type.");
520                 return;
521             }
522
523             match ret {
524                 CPlace::NoPlace(_layout) => {}
525                 CPlace::Var(var, layout) => {
526                     let clif_ty = fx.clif_type(layout.ty).unwrap();
527                     let val = match clif_ty {
528                         types::I8 | types::I16 | types::I32 | types::I64 => fx.bcx.ins().iconst(clif_ty, 0),
529                         types::F32 => {
530                             let zero = fx.bcx.ins().iconst(types::I32, 0);
531                             fx.bcx.ins().bitcast(types::F32, zero)
532                         }
533                         types::F64 => {
534                             let zero = fx.bcx.ins().iconst(types::I64, 0);
535                             fx.bcx.ins().bitcast(types::F64, zero)
536                         }
537                         _ => panic!("clif_type returned {}", clif_ty),
538                     };
539                     fx.bcx.def_var(mir_var(var), val);
540                 }
541                 _ => {
542                     let addr = ret.to_addr(fx);
543                     let layout = ret.layout();
544                     fx.bcx.emit_small_memset(fx.module.target_config(), addr, 0, layout.size.bytes(), 1);
545                 }
546             }
547         };
548         write_bytes, (c dst, v val, v count) {
549             let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty;
550             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
551             let count = fx.bcx.ins().imul_imm(count, pointee_size as i64);
552             let dst_ptr = dst.load_scalar(fx);
553             fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count);
554         };
555         ctlz | ctlz_nonzero, <T> (v arg) {
556             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
557                 // FIXME verify this algorithm is correct
558                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
559                 let lsb_lz = fx.bcx.ins().clz(lsb);
560                 let msb_lz = fx.bcx.ins().clz(msb);
561                 let msb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, msb, 0);
562                 let lsb_lz_plus_64 = fx.bcx.ins().iadd_imm(lsb_lz, 64);
563                 fx.bcx.ins().select(msb_is_zero, lsb_lz_plus_64, msb_lz)
564             } else {
565                 fx.bcx.ins().clz(arg)
566             };
567             let res = CValue::by_val(res, fx.layout_of(T));
568             ret.write_cvalue(fx, res);
569         };
570         cttz | cttz_nonzero, <T> (v arg) {
571             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
572                 // FIXME verify this algorithm is correct
573                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
574                 let lsb_tz = fx.bcx.ins().ctz(lsb);
575                 let msb_tz = fx.bcx.ins().ctz(msb);
576                 let lsb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, lsb, 0);
577                 let msb_tz_plus_64 = fx.bcx.ins().iadd_imm(msb_tz, 64);
578                 fx.bcx.ins().select(lsb_is_zero, msb_tz_plus_64, lsb_tz)
579             } else {
580                 fx.bcx.ins().ctz(arg)
581             };
582             let res = CValue::by_val(res, fx.layout_of(T));
583             ret.write_cvalue(fx, res);
584         };
585         ctpop, <T> (v arg) {
586             let res = CValue::by_val(fx.bcx.ins().popcnt(arg), fx.layout_of(T));
587             ret.write_cvalue(fx, res);
588         };
589         bitreverse, <T> (v arg) {
590             let res = CValue::by_val(fx.bcx.ins().bitrev(arg), fx.layout_of(T));
591             ret.write_cvalue(fx, res);
592         };
593         bswap, <T> (v arg) {
594             // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift
595             fn swap(bcx: &mut FunctionBuilder, v: Value) -> Value {
596                 match bcx.func.dfg.value_type(v) {
597                     types::I8 => v,
598
599                     // https://code.woboq.org/gcc/include/bits/byteswap.h.html
600                     types::I16 => {
601                         let tmp1 = bcx.ins().ishl_imm(v, 8);
602                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00);
603
604                         let tmp2 = bcx.ins().ushr_imm(v, 8);
605                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF);
606
607                         bcx.ins().bor(n1, n2)
608                     }
609                     types::I32 => {
610                         let tmp1 = bcx.ins().ishl_imm(v, 24);
611                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000);
612
613                         let tmp2 = bcx.ins().ishl_imm(v, 8);
614                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000);
615
616                         let tmp3 = bcx.ins().ushr_imm(v, 8);
617                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00);
618
619                         let tmp4 = bcx.ins().ushr_imm(v, 24);
620                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF);
621
622                         let or_tmp1 = bcx.ins().bor(n1, n2);
623                         let or_tmp2 = bcx.ins().bor(n3, n4);
624                         bcx.ins().bor(or_tmp1, or_tmp2)
625                     }
626                     types::I64 => {
627                         let tmp1 = bcx.ins().ishl_imm(v, 56);
628                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64);
629
630                         let tmp2 = bcx.ins().ishl_imm(v, 40);
631                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64);
632
633                         let tmp3 = bcx.ins().ishl_imm(v, 24);
634                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64);
635
636                         let tmp4 = bcx.ins().ishl_imm(v, 8);
637                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64);
638
639                         let tmp5 = bcx.ins().ushr_imm(v, 8);
640                         let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64);
641
642                         let tmp6 = bcx.ins().ushr_imm(v, 24);
643                         let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64);
644
645                         let tmp7 = bcx.ins().ushr_imm(v, 40);
646                         let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64);
647
648                         let tmp8 = bcx.ins().ushr_imm(v, 56);
649                         let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64);
650
651                         let or_tmp1 = bcx.ins().bor(n1, n2);
652                         let or_tmp2 = bcx.ins().bor(n3, n4);
653                         let or_tmp3 = bcx.ins().bor(n5, n6);
654                         let or_tmp4 = bcx.ins().bor(n7, n8);
655
656                         let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2);
657                         let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4);
658                         bcx.ins().bor(or_tmp5, or_tmp6)
659                     }
660                     types::I128 => {
661                         let (lo, hi) = bcx.ins().isplit(v);
662                         let lo = swap(bcx, lo);
663                         let hi = swap(bcx, hi);
664                         bcx.ins().iconcat(hi, lo)
665                     }
666                     ty => unimplemented!("bswap {}", ty),
667                 }
668             };
669             let res = CValue::by_val(swap(&mut fx.bcx, arg), fx.layout_of(T));
670             ret.write_cvalue(fx, res);
671         };
672         needs_drop, <T> () {
673             let needs_drop = if T.needs_drop(fx.tcx, ParamEnv::reveal_all()) {
674                 1
675             } else {
676                 0
677             };
678             let needs_drop = CValue::const_val(fx, fx.tcx.types.bool, needs_drop);
679             ret.write_cvalue(fx, needs_drop);
680         };
681         panic_if_uninhabited, <T> () {
682             if fx.layout_of(T).abi.is_uninhabited() {
683                 crate::trap::trap_panic(fx, "[panic] Called intrinsic::panic_if_uninhabited for uninhabited type.");
684                 return;
685             }
686         };
687
688         volatile_load, (c ptr) {
689             // Cranelift treats loads as volatile by default
690             let inner_layout =
691                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
692             let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout);
693             ret.write_cvalue(fx, val);
694         };
695         volatile_store, (v ptr, c val) {
696             // Cranelift treats stores as volatile by default
697             let dest = CPlace::for_addr(ptr, val.layout());
698             dest.write_cvalue(fx, val);
699         };
700
701         _ if intrinsic.starts_with("atomic_fence"), () {};
702         _ if intrinsic.starts_with("atomic_singlethreadfence"), () {};
703         _ if intrinsic.starts_with("atomic_load"), (c ptr) {
704             let inner_layout =
705                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
706             let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout);
707             ret.write_cvalue(fx, val);
708         };
709         _ if intrinsic.starts_with("atomic_store"), (v ptr, c val) {
710             let dest = CPlace::for_addr(ptr, val.layout());
711             dest.write_cvalue(fx, val);
712         };
713         _ if intrinsic.starts_with("atomic_xchg"), <T> (v ptr, c src) {
714             // Read old
715             let clif_ty = fx.clif_type(T).unwrap();
716             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
717             ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T)));
718
719             // Write new
720             let dest = CPlace::for_addr(ptr, src.layout());
721             dest.write_cvalue(fx, src);
722         };
723         _ if intrinsic.starts_with("atomic_cxchg"), <T> (v ptr, v test_old, v new) { // both atomic_cxchg_* and atomic_cxchgweak_*
724             // Read old
725             let clif_ty = fx.clif_type(T).unwrap();
726             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
727
728             // Compare
729             let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old);
730             let new = crate::common::codegen_select(&mut fx.bcx, is_eq, new, old); // Keep old if not equal to test_old
731
732             // Write new
733             fx.bcx.ins().store(MemFlags::new(), new, ptr, 0);
734
735             let ret_val = CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout());
736             ret.write_cvalue(fx, ret_val);
737         };
738
739         _ if intrinsic.starts_with("atomic_xadd"), <T> (v ptr, v amount) {
740             atomic_binop_return_old! (fx, iadd<T>(ptr, amount) -> ret);
741         };
742         _ if intrinsic.starts_with("atomic_xsub"), <T> (v ptr, v amount) {
743             atomic_binop_return_old! (fx, isub<T>(ptr, amount) -> ret);
744         };
745         _ if intrinsic.starts_with("atomic_and"), <T> (v ptr, v src) {
746             atomic_binop_return_old! (fx, band<T>(ptr, src) -> ret);
747         };
748         _ if intrinsic.starts_with("atomic_nand"), <T> (v ptr, v src) {
749             atomic_binop_return_old! (fx, band_not<T>(ptr, src) -> ret);
750         };
751         _ if intrinsic.starts_with("atomic_or"), <T> (v ptr, v src) {
752             atomic_binop_return_old! (fx, bor<T>(ptr, src) -> ret);
753         };
754         _ if intrinsic.starts_with("atomic_xor"), <T> (v ptr, v src) {
755             atomic_binop_return_old! (fx, bxor<T>(ptr, src) -> ret);
756         };
757
758         _ if intrinsic.starts_with("atomic_max"), <T> (v ptr, v src) {
759             atomic_minmax!(fx, IntCC::SignedGreaterThan, <T> (ptr, src) -> ret);
760         };
761         _ if intrinsic.starts_with("atomic_umax"), <T> (v ptr, v src) {
762             atomic_minmax!(fx, IntCC::UnsignedGreaterThan, <T> (ptr, src) -> ret);
763         };
764         _ if intrinsic.starts_with("atomic_min"), <T> (v ptr, v src) {
765             atomic_minmax!(fx, IntCC::SignedLessThan, <T> (ptr, src) -> ret);
766         };
767         _ if intrinsic.starts_with("atomic_umin"), <T> (v ptr, v src) {
768             atomic_minmax!(fx, IntCC::UnsignedLessThan, <T> (ptr, src) -> ret);
769         };
770
771         minnumf32, (v a, v b) {
772             let val = fx.bcx.ins().fmin(a, b);
773             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
774             ret.write_cvalue(fx, val);
775         };
776         minnumf64, (v a, v b) {
777             let val = fx.bcx.ins().fmin(a, b);
778             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
779             ret.write_cvalue(fx, val);
780         };
781         maxnumf32, (v a, v b) {
782             let val = fx.bcx.ins().fmax(a, b);
783             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
784             ret.write_cvalue(fx, val);
785         };
786         maxnumf64, (v a, v b) {
787             let val = fx.bcx.ins().fmax(a, b);
788             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
789             ret.write_cvalue(fx, val);
790         };
791
792         simd_cast, (c x) {
793             ret.write_cvalue(fx, x.unchecked_cast_to(ret.layout()));
794         };
795
796         simd_eq, (c x, c y) {
797             simd_cmp!(fx, intrinsic, Equal(x, y) -> ret);
798         };
799         simd_ne, (c x, c y) {
800             simd_cmp!(fx, intrinsic, NotEqual(x, y) -> ret);
801         };
802         simd_lt, (c x, c y) {
803             simd_cmp!(fx, intrinsic, UnsignedLessThan|SignedLessThan(x, y) -> ret);
804         };
805         simd_le, (c x, c y) {
806             simd_cmp!(fx, intrinsic, UnsignedLessThanOrEqual|SignedLessThanOrEqual(x, y) -> ret);
807         };
808         simd_gt, (c x, c y) {
809             simd_cmp!(fx, intrinsic, UnsignedGreaterThan|SignedGreaterThan(x, y) -> ret);
810         };
811         simd_ge, (c x, c y) {
812             simd_cmp!(fx, intrinsic, UnsignedGreaterThanOrEqual|SignedGreaterThanOrEqual(x, y) -> ret);
813         };
814
815         // simd_shuffle32<T, U>(x: T, y: T, idx: [u32; 32]) -> U
816         _ if intrinsic.starts_with("simd_shuffle"), (c x, c y, o idx) {
817             let n: u32 = intrinsic["simd_shuffle".len()..].parse().unwrap();
818
819             assert_eq!(x.layout(), y.layout());
820             let layout = x.layout();
821
822             let (lane_type, lane_count) = lane_type_and_count(fx, layout, intrinsic);
823             let (ret_lane_type, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic);
824
825             assert_eq!(lane_type, ret_lane_type);
826             assert_eq!(n, ret_lane_count);
827
828             let total_len = lane_count * 2;
829
830             let indexes = {
831                 use rustc::mir::interpret::*;
832                 let idx_place = match idx {
833                     Operand::Copy(idx_place) => {
834                         idx_place
835                     }
836                     _ => panic!("simd_shuffle* idx is not Operand::Copy, but {:?}", idx),
837                 };
838
839                 assert!(idx_place.projection.is_none());
840                 let static_ = match &idx_place.base {
841                     PlaceBase::Static(static_) => {
842                         static_
843                     }
844                     PlaceBase::Local(_) => panic!("simd_shuffle* idx is not constant, but a local"),
845                 };
846
847                 let idx_const = match &static_.kind {
848                     StaticKind::Static(_) => unimplemented!(),
849                     StaticKind::Promoted(promoted) => {
850                         fx.tcx.const_eval(ParamEnv::reveal_all().and(GlobalId {
851                             instance: fx.instance,
852                             promoted: Some(*promoted),
853                         })).unwrap()
854                     }
855                 };
856
857                 let idx_bytes = match idx_const.val {
858                     ConstValue::ByRef { align: _, offset, alloc } => {
859                         let ptr = Pointer::new(AllocId(0 /* dummy */), offset);
860                         let size = Size::from_bytes(4 * u64::from(ret_lane_count) /* size_of([u32; ret_lane_count]) */);
861                         alloc.get_bytes(fx, ptr, size).unwrap()
862                     }
863                     _ => unreachable!("{:?}", idx_const),
864                 };
865
866                 (0..ret_lane_count).map(|i| {
867                     let i = usize::try_from(i).unwrap();
868                     let idx = rustc::mir::interpret::read_target_uint(
869                         fx.tcx.data_layout.endian,
870                         &idx_bytes[4*i.. 4*i + 4],
871                     ).expect("read_target_uint");
872                     u32::try_from(idx).expect("try_from u32")
873                 }).collect::<Vec<u32>>()
874             };
875
876             for &idx in &indexes {
877                 assert!(idx < total_len, "idx {} out of range 0..{}", idx, total_len);
878             }
879
880
881
882             println!("{:?}", indexes);
883             unimplemented!();
884         };
885
886         simd_add, (c x, c y) {
887             simd_binop!(fx, intrinsic, iadd(x, y) -> ret);
888         };
889         simd_sub, (c x, c y) {
890             simd_binop!(fx, intrinsic, isub(x, y) -> ret);
891         };
892         simd_mul, (c x, c y) {
893             simd_binop!(fx, intrinsic, imul(x, y) -> ret);
894         };
895         simd_div, (c x, c y) {
896             simd_binop!(fx, intrinsic, udiv|sdiv(x, y) -> ret);
897         };
898         simd_rem, (c x, c y) {
899             simd_binop!(fx, intrinsic, urem|srem(x, y) -> ret);
900         };
901         simd_shl, (c x, c y) {
902             simd_binop!(fx, intrinsic, ishl(x, y) -> ret);
903         };
904         simd_shr, (c x, c y) {
905             simd_binop!(fx, intrinsic, ushr|sshr(x, y) -> ret);
906         };
907         simd_and, (c x, c y) {
908             simd_binop!(fx, intrinsic, band(x, y) -> ret);
909         };
910         simd_or, (c x, c y) {
911             simd_binop!(fx, intrinsic, bor(x, y) -> ret);
912         };
913         simd_xor, (c x, c y) {
914             simd_binop!(fx, intrinsic, bxor(x, y) -> ret);
915         };
916
917         simd_fmin, (c x, c y) {
918             simd_binop!(fx, intrinsic, fmin(x, y) -> ret);
919         };
920         simd_fmax, (c x, c y) {
921             simd_binop!(fx, intrinsic, fmax(x, y) -> ret);
922         };
923     }
924
925     if let Some((_, dest)) = destination {
926         let ret_ebb = fx.get_ebb(dest);
927         fx.bcx.ins().jump(ret_ebb, &[]);
928     } else {
929         trap_unreachable(fx, "[corruption] Diverging intrinsic returned.");
930     }
931 }