4 use gccjit::{ComparisonOp, Function, RValue, ToRValue, Type, UnaryOp, FunctionType};
5 use rustc_codegen_ssa::MemFlags;
6 use rustc_codegen_ssa::base::wants_msvc_seh;
7 use rustc_codegen_ssa::common::{IntPredicate, span_invalid_monomorphization_error};
8 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
9 use rustc_codegen_ssa::mir::place::PlaceRef;
10 use rustc_codegen_ssa::traits::{ArgAbiMethods, BaseTypeMethods, BuilderMethods, ConstMethods, IntrinsicCallMethods};
11 use rustc_middle::bug;
12 use rustc_middle::ty::{self, Instance, Ty};
13 use rustc_middle::ty::layout::LayoutOf;
14 use rustc_span::{Span, Symbol, symbol::kw, sym};
15 use rustc_target::abi::HasDataLayout;
16 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
17 use rustc_target::spec::PanicStrategy;
19 use crate::abi::GccType;
20 use crate::builder::Builder;
21 use crate::common::{SignType, TypeReflection};
22 use crate::context::CodegenCx;
23 use crate::type_of::LayoutGccExt;
24 use crate::intrinsic::simd::generic_simd_intrinsic;
26 fn get_simple_intrinsic<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, name: Symbol) -> Option<Function<'gcc>> {
27 let gcc_name = match name {
28 sym::sqrtf32 => "sqrtf",
29 sym::sqrtf64 => "sqrt",
30 sym::powif32 => "__builtin_powif",
31 sym::powif64 => "__builtin_powi",
32 sym::sinf32 => "sinf",
34 sym::cosf32 => "cosf",
36 sym::powf32 => "powf",
38 sym::expf32 => "expf",
40 sym::exp2f32 => "exp2f",
41 sym::exp2f64 => "exp2",
42 sym::logf32 => "logf",
44 sym::log10f32 => "log10f",
45 sym::log10f64 => "log10",
46 sym::log2f32 => "log2f",
47 sym::log2f64 => "log2",
48 sym::fmaf32 => "fmaf",
50 sym::fabsf32 => "fabsf",
51 sym::fabsf64 => "fabs",
52 sym::minnumf32 => "fminf",
53 sym::minnumf64 => "fmin",
54 sym::maxnumf32 => "fmaxf",
55 sym::maxnumf64 => "fmax",
56 sym::copysignf32 => "copysignf",
57 sym::copysignf64 => "copysign",
58 sym::floorf32 => "floorf",
59 sym::floorf64 => "floor",
60 sym::ceilf32 => "ceilf",
61 sym::ceilf64 => "ceil",
62 sym::truncf32 => "truncf",
63 sym::truncf64 => "trunc",
64 sym::rintf32 => "rintf",
65 sym::rintf64 => "rint",
66 sym::nearbyintf32 => "nearbyintf",
67 sym::nearbyintf64 => "nearbyint",
68 sym::roundf32 => "roundf",
69 sym::roundf64 => "round",
70 sym::abort => "abort",
73 Some(cx.context.get_builtin_function(&gcc_name))
76 impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
77 fn codegen_intrinsic_call(&mut self, instance: Instance<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, args: &[OperandRef<'tcx, RValue<'gcc>>], llresult: RValue<'gcc>, span: Span) {
79 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
81 let (def_id, substs) = match *callee_ty.kind() {
82 ty::FnDef(def_id, substs) => (def_id, substs),
83 _ => bug!("expected fn item type, found {}", callee_ty),
86 let sig = callee_ty.fn_sig(tcx);
87 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
88 let arg_tys = sig.inputs();
89 let ret_ty = sig.output();
90 let name = tcx.item_name(def_id);
91 let name_str = name.as_str();
93 let llret_ty = self.layout_of(ret_ty).gcc_type(self, true);
94 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
96 let simple = get_simple_intrinsic(self, name);
99 _ if simple.is_some() => {
100 // FIXME(antoyo): remove this cast when the API supports function.
101 let func = unsafe { std::mem::transmute(simple.expect("simple")) };
102 self.call(self.type_void(), func, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None)
105 self.expect(args[0].immediate(), true)
108 self.expect(args[0].immediate(), false)
130 sym::volatile_load | sym::unaligned_volatile_load => {
131 let tp_ty = substs.type_at(0);
132 let mut ptr = args[0].immediate();
133 if let PassMode::Cast(ty) = fn_abi.ret.mode {
134 ptr = self.pointercast(ptr, self.type_ptr_to(ty.gcc_type(self)));
136 let load = self.volatile_load(ptr.get_type(), ptr);
137 // TODO(antoyo): set alignment.
138 self.to_immediate(load, self.layout_of(tp_ty))
140 sym::volatile_store => {
141 let dst = args[0].deref(self.cx());
142 args[1].val.volatile_store(self, dst);
145 sym::unaligned_volatile_store => {
146 let dst = args[0].deref(self.cx());
147 args[1].val.unaligned_volatile_store(self, dst);
150 sym::prefetch_read_data
151 | sym::prefetch_write_data
152 | sym::prefetch_read_instruction
153 | sym::prefetch_write_instruction => {
165 | sym::saturating_add
166 | sym::saturating_sub => {
168 match int_type_width_signed(ty, self) {
169 Some((width, signed)) => match name {
170 sym::ctlz | sym::cttz => {
171 let func = self.current_func.borrow().expect("func");
172 let then_block = func.new_block("then");
173 let else_block = func.new_block("else");
174 let after_block = func.new_block("after");
176 let arg = args[0].immediate();
177 let result = func.new_local(None, arg.get_type(), "zeros");
178 let zero = self.cx.gcc_zero(arg.get_type());
179 let cond = self.gcc_icmp(IntPredicate::IntEQ, arg, zero);
180 self.llbb().end_with_conditional(None, cond, then_block, else_block);
182 let zero_result = self.cx.gcc_uint(arg.get_type(), width);
183 then_block.add_assignment(None, result, zero_result);
184 then_block.end_with_jump(None, after_block);
186 // NOTE: since jumps were added in a place
187 // count_leading_zeroes() does not expect, the current block
188 // in the state need to be updated.
189 self.switch_to_block(else_block);
193 sym::ctlz => self.count_leading_zeroes(width, arg),
194 sym::cttz => self.count_trailing_zeroes(width, arg),
197 self.llbb().add_assignment(None, result, zeros);
198 self.llbb().end_with_jump(None, after_block);
200 // NOTE: since jumps were added in a place rustc does not
201 // expect, the current block in the state need to be updated.
202 self.switch_to_block(after_block);
206 sym::ctlz_nonzero => {
207 self.count_leading_zeroes(width, args[0].immediate())
209 sym::cttz_nonzero => {
210 self.count_trailing_zeroes(width, args[0].immediate())
212 sym::ctpop => self.pop_count(args[0].immediate()),
215 args[0].immediate() // byte swap a u8/i8 is just a no-op
218 self.gcc_bswap(args[0].immediate(), width)
221 sym::bitreverse => self.bit_reverse(width, args[0].immediate()),
222 sym::rotate_left | sym::rotate_right => {
223 // TODO(antoyo): implement using algorithm from:
224 // https://blog.regehr.org/archives/1063
225 // for other platforms.
226 let is_left = name == sym::rotate_left;
227 let val = args[0].immediate();
228 let raw_shift = args[1].immediate();
230 self.rotate_left(val, raw_shift, width)
233 self.rotate_right(val, raw_shift, width)
236 sym::saturating_add => {
237 self.saturating_add(args[0].immediate(), args[1].immediate(), signed, width)
239 sym::saturating_sub => {
240 self.saturating_sub(args[0].immediate(), args[1].immediate(), signed, width)
245 span_invalid_monomorphization_error(
249 "invalid monomorphization of `{}` intrinsic: \
250 expected basic integer type, found `{}`",
260 use rustc_target::abi::Abi::*;
261 let tp_ty = substs.type_at(0);
262 let layout = self.layout_of(tp_ty).layout;
263 let _use_integer_compare = match layout.abi() {
264 Scalar(_) | ScalarPair(_, _) => true,
265 Uninhabited | Vector { .. } => false,
266 Aggregate { .. } => {
267 // For rusty ABIs, small aggregates are actually passed
268 // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
269 // so we re-use that same threshold here.
270 layout.size() <= self.data_layout().pointer_size * 2
274 let a = args[0].immediate();
275 let b = args[1].immediate();
276 if layout.size().bytes() == 0 {
277 self.const_bool(true)
279 /*else if use_integer_compare {
280 let integer_ty = self.type_ix(layout.size.bits()); // FIXME(antoyo): LLVM creates an integer of 96 bits for [i32; 3], but gcc doesn't support this, so it creates an integer of 128 bits.
281 let ptr_ty = self.type_ptr_to(integer_ty);
282 let a_ptr = self.bitcast(a, ptr_ty);
283 let a_val = self.load(integer_ty, a_ptr, layout.align.abi);
284 let b_ptr = self.bitcast(b, ptr_ty);
285 let b_val = self.load(integer_ty, b_ptr, layout.align.abi);
286 self.icmp(IntPredicate::IntEQ, a_val, b_val)
289 let void_ptr_type = self.context.new_type::<*const ()>();
290 let a_ptr = self.bitcast(a, void_ptr_type);
291 let b_ptr = self.bitcast(b, void_ptr_type);
292 let n = self.context.new_cast(None, self.const_usize(layout.size().bytes()), self.sizet_type);
293 let builtin = self.context.get_builtin_function("memcmp");
294 let cmp = self.context.new_call(None, builtin, &[a_ptr, b_ptr, n]);
295 self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0))
300 args[0].val.store(self, result);
302 let block = self.llbb();
303 let extended_asm = block.add_extended_asm(None, "");
304 extended_asm.add_input_operand(None, "r", result.llval);
305 extended_asm.add_clobber("memory");
306 extended_asm.set_volatile_flag(true);
308 // We have copied the value to `result` already.
312 _ if name_str.starts_with("simd_") => {
313 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
319 _ => bug!("unknown intrinsic '{}'", name),
322 if !fn_abi.ret.is_ignore() {
323 if let PassMode::Cast(ty) = fn_abi.ret.mode {
324 let ptr_llty = self.type_ptr_to(ty.gcc_type(self));
325 let ptr = self.pointercast(result.llval, ptr_llty);
326 self.store(llval, ptr, result.align);
329 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
331 .store(self, result);
336 fn abort(&mut self) {
337 let func = self.context.get_builtin_function("abort");
338 let func: RValue<'gcc> = unsafe { std::mem::transmute(func) };
339 self.call(self.type_void(), func, &[], None);
342 fn assume(&mut self, value: Self::Value) {
343 // TODO(antoyo): switch to assume when it exists.
344 // Or use something like this:
345 // #define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)
346 self.expect(value, true);
349 fn expect(&mut self, cond: Self::Value, _expected: bool) -> Self::Value {
354 fn type_test(&mut self, _pointer: Self::Value, _typeid: Self::Value) -> Self::Value {
356 self.context.new_rvalue_from_int(self.int_type, 0)
359 fn va_start(&mut self, _va_list: RValue<'gcc>) -> RValue<'gcc> {
363 fn va_end(&mut self, _va_list: RValue<'gcc>) -> RValue<'gcc> {
368 impl<'a, 'gcc, 'tcx> ArgAbiMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
369 fn store_fn_arg(&mut self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>, idx: &mut usize, dst: PlaceRef<'tcx, Self::Value>) {
370 arg_abi.store_fn_arg(self, idx, dst)
373 fn store_arg(&mut self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>, val: RValue<'gcc>, dst: PlaceRef<'tcx, RValue<'gcc>>) {
374 arg_abi.store(self, val, dst)
377 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> Type<'gcc> {
378 arg_abi.memory_ty(self)
382 pub trait ArgAbiExt<'gcc, 'tcx> {
383 fn memory_ty(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>;
384 fn store(&self, bx: &mut Builder<'_, 'gcc, 'tcx>, val: RValue<'gcc>, dst: PlaceRef<'tcx, RValue<'gcc>>);
385 fn store_fn_arg(&self, bx: &mut Builder<'_, 'gcc, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx, RValue<'gcc>>);
388 impl<'gcc, 'tcx> ArgAbiExt<'gcc, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
389 /// Gets the LLVM type for a place of the original Rust type of
390 /// this argument/return, i.e., the result of `type_of::type_of`.
391 fn memory_ty(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> {
392 self.layout.gcc_type(cx, true)
395 /// Stores a direct/indirect value described by this ArgAbi into a
396 /// place for the original Rust type of this argument/return.
397 /// Can be used for both storing formal arguments into Rust variables
398 /// or results of call/invoke instructions into their destinations.
399 fn store(&self, bx: &mut Builder<'_, 'gcc, 'tcx>, val: RValue<'gcc>, dst: PlaceRef<'tcx, RValue<'gcc>>) {
400 if self.is_ignore() {
403 if self.is_sized_indirect() {
404 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
406 else if self.is_unsized_indirect() {
407 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
409 else if let PassMode::Cast(cast) = self.mode {
410 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
411 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
412 let can_store_through_cast_ptr = false;
413 if can_store_through_cast_ptr {
414 let cast_ptr_llty = bx.type_ptr_to(cast.gcc_type(bx));
415 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
416 bx.store(val, cast_dst, self.layout.align.abi);
419 // The actual return type is a struct, but the ABI
420 // adaptation code has cast it into some scalar type. The
421 // code that follows is the only reliable way I have
422 // found to do a transform like i64 -> {i32,i32}.
423 // Basically we dump the data onto the stack then memcpy it.
425 // Other approaches I tried:
426 // - Casting rust ret pointer to the foreign type and using Store
427 // is (a) unsafe if size of foreign type > size of rust type and
428 // (b) runs afoul of strict aliasing rules, yielding invalid
429 // assembly under -O (specifically, the store gets removed).
430 // - Truncating foreign type to correct integral type and then
431 // bitcasting to the struct type yields invalid cast errors.
433 // We instead thus allocate some scratch space...
434 let scratch_size = cast.size(bx);
435 let scratch_align = cast.align(bx);
436 let llscratch = bx.alloca(cast.gcc_type(bx), scratch_align);
437 bx.lifetime_start(llscratch, scratch_size);
439 // ... where we first store the value...
440 bx.store(val, llscratch, scratch_align);
442 // ... and then memcpy it to the intended destination.
445 self.layout.align.abi,
448 bx.const_usize(self.layout.size.bytes()),
452 bx.lifetime_end(llscratch, scratch_size);
456 OperandValue::Immediate(val).store(bx, dst);
460 fn store_fn_arg<'a>(&self, bx: &mut Builder<'a, 'gcc, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx, RValue<'gcc>>) {
462 let val = bx.current_func().get_param(*idx as i32);
467 PassMode::Ignore => {},
468 PassMode::Pair(..) => {
469 OperandValue::Pair(next(), next()).store(bx, dst);
471 PassMode::Indirect { extra_attrs: Some(_), .. } => {
472 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
474 PassMode::Direct(_) | PassMode::Indirect { extra_attrs: None, .. } | PassMode::Cast(_) => {
475 let next_arg = next();
476 self.store(bx, next_arg, dst);
482 fn int_type_width_signed<'gcc, 'tcx>(ty: Ty<'tcx>, cx: &CodegenCx<'gcc, 'tcx>) -> Option<(u64, bool)> {
486 rustc_middle::ty::IntTy::Isize => u64::from(cx.tcx.sess.target.pointer_width),
487 rustc_middle::ty::IntTy::I8 => 8,
488 rustc_middle::ty::IntTy::I16 => 16,
489 rustc_middle::ty::IntTy::I32 => 32,
490 rustc_middle::ty::IntTy::I64 => 64,
491 rustc_middle::ty::IntTy::I128 => 128,
495 ty::Uint(t) => Some((
497 rustc_middle::ty::UintTy::Usize => u64::from(cx.tcx.sess.target.pointer_width),
498 rustc_middle::ty::UintTy::U8 => 8,
499 rustc_middle::ty::UintTy::U16 => 16,
500 rustc_middle::ty::UintTy::U32 => 32,
501 rustc_middle::ty::UintTy::U64 => 64,
502 rustc_middle::ty::UintTy::U128 => 128,
510 impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
511 fn bit_reverse(&mut self, width: u64, value: RValue<'gcc>) -> RValue<'gcc> {
512 let result_type = value.get_type();
513 let typ = result_type.to_unsigned(self.cx);
516 if result_type.is_signed(self.cx) {
517 self.gcc_int_cast(value, typ)
523 let context = &self.cx.context;
528 let left = self.and(value, context.new_rvalue_from_int(typ, 0xF0));
529 let left = self.lshr(left, context.new_rvalue_from_int(typ, 4));
530 let right = self.and(value, context.new_rvalue_from_int(typ, 0x0F));
531 let right = self.shl(right, context.new_rvalue_from_int(typ, 4));
532 let step1 = self.or(left, right);
535 let left = self.and(step1, context.new_rvalue_from_int(typ, 0xCC));
536 let left = self.lshr(left, context.new_rvalue_from_int(typ, 2));
537 let right = self.and(step1, context.new_rvalue_from_int(typ, 0x33));
538 let right = self.shl(right, context.new_rvalue_from_int(typ, 2));
539 let step2 = self.or(left, right);
542 let left = self.and(step2, context.new_rvalue_from_int(typ, 0xAA));
543 let left = self.lshr(left, context.new_rvalue_from_int(typ, 1));
544 let right = self.and(step2, context.new_rvalue_from_int(typ, 0x55));
545 let right = self.shl(right, context.new_rvalue_from_int(typ, 1));
546 let step3 = self.or(left, right);
552 let left = self.and(value, context.new_rvalue_from_int(typ, 0x5555));
553 let left = self.shl(left, context.new_rvalue_from_int(typ, 1));
554 let right = self.and(value, context.new_rvalue_from_int(typ, 0xAAAA));
555 let right = self.lshr(right, context.new_rvalue_from_int(typ, 1));
556 let step1 = self.or(left, right);
559 let left = self.and(step1, context.new_rvalue_from_int(typ, 0x3333));
560 let left = self.shl(left, context.new_rvalue_from_int(typ, 2));
561 let right = self.and(step1, context.new_rvalue_from_int(typ, 0xCCCC));
562 let right = self.lshr(right, context.new_rvalue_from_int(typ, 2));
563 let step2 = self.or(left, right);
566 let left = self.and(step2, context.new_rvalue_from_int(typ, 0x0F0F));
567 let left = self.shl(left, context.new_rvalue_from_int(typ, 4));
568 let right = self.and(step2, context.new_rvalue_from_int(typ, 0xF0F0));
569 let right = self.lshr(right, context.new_rvalue_from_int(typ, 4));
570 let step3 = self.or(left, right);
573 let left = self.and(step3, context.new_rvalue_from_int(typ, 0x00FF));
574 let left = self.shl(left, context.new_rvalue_from_int(typ, 8));
575 let right = self.and(step3, context.new_rvalue_from_int(typ, 0xFF00));
576 let right = self.lshr(right, context.new_rvalue_from_int(typ, 8));
577 let step4 = self.or(left, right);
582 // TODO(antoyo): Refactor with other implementations.
584 let left = self.and(value, context.new_rvalue_from_long(typ, 0x55555555));
585 let left = self.shl(left, context.new_rvalue_from_long(typ, 1));
586 let right = self.and(value, context.new_rvalue_from_long(typ, 0xAAAAAAAA));
587 let right = self.lshr(right, context.new_rvalue_from_long(typ, 1));
588 let step1 = self.or(left, right);
591 let left = self.and(step1, context.new_rvalue_from_long(typ, 0x33333333));
592 let left = self.shl(left, context.new_rvalue_from_long(typ, 2));
593 let right = self.and(step1, context.new_rvalue_from_long(typ, 0xCCCCCCCC));
594 let right = self.lshr(right, context.new_rvalue_from_long(typ, 2));
595 let step2 = self.or(left, right);
598 let left = self.and(step2, context.new_rvalue_from_long(typ, 0x0F0F0F0F));
599 let left = self.shl(left, context.new_rvalue_from_long(typ, 4));
600 let right = self.and(step2, context.new_rvalue_from_long(typ, 0xF0F0F0F0));
601 let right = self.lshr(right, context.new_rvalue_from_long(typ, 4));
602 let step3 = self.or(left, right);
605 let left = self.and(step3, context.new_rvalue_from_long(typ, 0x00FF00FF));
606 let left = self.shl(left, context.new_rvalue_from_long(typ, 8));
607 let right = self.and(step3, context.new_rvalue_from_long(typ, 0xFF00FF00));
608 let right = self.lshr(right, context.new_rvalue_from_long(typ, 8));
609 let step4 = self.or(left, right);
612 let left = self.and(step4, context.new_rvalue_from_long(typ, 0x0000FFFF));
613 let left = self.shl(left, context.new_rvalue_from_long(typ, 16));
614 let right = self.and(step4, context.new_rvalue_from_long(typ, 0xFFFF0000));
615 let right = self.lshr(right, context.new_rvalue_from_long(typ, 16));
616 let step5 = self.or(left, right);
622 let left = self.shl(value, context.new_rvalue_from_long(typ, 32));
623 let right = self.lshr(value, context.new_rvalue_from_long(typ, 32));
624 let step1 = self.or(left, right);
627 let left = self.and(step1, context.new_rvalue_from_long(typ, 0x0001FFFF0001FFFF));
628 let left = self.shl(left, context.new_rvalue_from_long(typ, 15));
629 let right = self.and(step1, context.new_rvalue_from_long(typ, 0xFFFE0000FFFE0000u64 as i64)); // TODO(antoyo): transmute the number instead?
630 let right = self.lshr(right, context.new_rvalue_from_long(typ, 17));
631 let step2 = self.or(left, right);
634 let left = self.lshr(step2, context.new_rvalue_from_long(typ, 10));
635 let left = self.xor(step2, left);
636 let temp = self.and(left, context.new_rvalue_from_long(typ, 0x003F801F003F801F));
638 let left = self.shl(temp, context.new_rvalue_from_long(typ, 10));
639 let left = self.or(temp, left);
640 let step3 = self.xor(left, step2);
643 let left = self.lshr(step3, context.new_rvalue_from_long(typ, 4));
644 let left = self.xor(step3, left);
645 let temp = self.and(left, context.new_rvalue_from_long(typ, 0x0E0384210E038421));
647 let left = self.shl(temp, context.new_rvalue_from_long(typ, 4));
648 let left = self.or(temp, left);
649 let step4 = self.xor(left, step3);
652 let left = self.lshr(step4, context.new_rvalue_from_long(typ, 2));
653 let left = self.xor(step4, left);
654 let temp = self.and(left, context.new_rvalue_from_long(typ, 0x2248884222488842));
656 let left = self.shl(temp, context.new_rvalue_from_long(typ, 2));
657 let left = self.or(temp, left);
658 let step5 = self.xor(left, step4);
663 // TODO(antoyo): find a more efficient implementation?
664 let sixty_four = self.gcc_int(typ, 64);
665 let right_shift = self.gcc_lshr(value, sixty_four);
666 let high = self.gcc_int_cast(right_shift, self.u64_type);
667 let low = self.gcc_int_cast(value, self.u64_type);
669 let reversed_high = self.bit_reverse(64, high);
670 let reversed_low = self.bit_reverse(64, low);
672 let new_low = self.gcc_int_cast(reversed_high, typ);
673 let new_high = self.shl(self.gcc_int_cast(reversed_low, typ), sixty_four);
675 self.gcc_or(new_low, new_high)
678 panic!("cannot bit reverse with width = {}", width);
682 self.gcc_int_cast(result, result_type)
685 fn count_leading_zeroes(&mut self, width: u64, arg: RValue<'gcc>) -> RValue<'gcc> {
686 // TODO(antoyo): use width?
687 let arg_type = arg.get_type();
688 let count_leading_zeroes =
689 // TODO(antoyo): write a new function Type::is_compatible_with(&Type) and use it here
690 // instead of using is_uint().
691 if arg_type.is_uint(&self.cx) {
694 else if arg_type.is_ulong(&self.cx) {
697 else if arg_type.is_ulonglong(&self.cx) {
700 else if width == 128 {
701 // Algorithm from: https://stackoverflow.com/a/28433850/389119
702 let array_type = self.context.new_array_type(None, arg_type, 3);
703 let result = self.current_func()
704 .new_local(None, array_type, "count_loading_zeroes_results");
706 let sixty_four = self.const_uint(arg_type, 64);
707 let shift = self.lshr(arg, sixty_four);
708 let high = self.gcc_int_cast(shift, self.u64_type);
709 let low = self.gcc_int_cast(arg, self.u64_type);
711 let zero = self.context.new_rvalue_zero(self.usize_type);
712 let one = self.context.new_rvalue_one(self.usize_type);
713 let two = self.context.new_rvalue_from_long(self.usize_type, 2);
715 let clzll = self.context.get_builtin_function("__builtin_clzll");
717 let first_elem = self.context.new_array_access(None, result, zero);
718 let first_value = self.gcc_int_cast(self.context.new_call(None, clzll, &[high]), arg_type);
720 .add_assignment(None, first_elem, first_value);
722 let second_elem = self.context.new_array_access(None, result, one);
723 let cast = self.gcc_int_cast(self.context.new_call(None, clzll, &[low]), arg_type);
724 let second_value = self.add(cast, sixty_four);
726 .add_assignment(None, second_elem, second_value);
728 let third_elem = self.context.new_array_access(None, result, two);
729 let third_value = self.const_uint(arg_type, 128);
731 .add_assignment(None, third_elem, third_value);
733 let not_high = self.context.new_unary_op(None, UnaryOp::LogicalNegate, self.u64_type, high);
734 let not_low = self.context.new_unary_op(None, UnaryOp::LogicalNegate, self.u64_type, low);
735 let not_low_and_not_high = not_low & not_high;
736 let index = not_high + not_low_and_not_high;
737 // NOTE: the following cast is necessary to avoid a GIMPLE verification failure in
739 // TODO(antoyo): do the correct verification in libgccjit to avoid an error at the
740 // compilation stage.
741 let index = self.context.new_cast(None, index, self.i32_type);
743 let res = self.context.new_array_access(None, result, index);
745 return self.gcc_int_cast(res.to_rvalue(), arg_type);
748 let count_leading_zeroes = self.context.get_builtin_function("__builtin_clzll");
749 let arg = self.context.new_cast(None, arg, self.ulonglong_type);
750 let diff = self.ulonglong_type.get_size() as i64 - arg_type.get_size() as i64;
751 let diff = self.context.new_rvalue_from_long(self.int_type, diff * 8);
752 let res = self.context.new_call(None, count_leading_zeroes, &[arg]) - diff;
753 return self.context.new_cast(None, res, arg_type);
755 let count_leading_zeroes = self.context.get_builtin_function(count_leading_zeroes);
756 let res = self.context.new_call(None, count_leading_zeroes, &[arg]);
757 self.context.new_cast(None, res, arg_type)
760 fn count_trailing_zeroes(&mut self, _width: u64, arg: RValue<'gcc>) -> RValue<'gcc> {
761 let result_type = arg.get_type();
763 if result_type.is_signed(self.cx) {
764 let new_type = result_type.to_unsigned(self.cx);
765 self.gcc_int_cast(arg, new_type)
770 let arg_type = arg.get_type();
771 let (count_trailing_zeroes, expected_type) =
772 // TODO(antoyo): write a new function Type::is_compatible_with(&Type) and use it here
773 // instead of using is_uint().
774 if arg_type.is_uchar(&self.cx) || arg_type.is_ushort(&self.cx) || arg_type.is_uint(&self.cx) {
775 // NOTE: we don't need to & 0xFF for uchar because the result is undefined on zero.
776 ("__builtin_ctz", self.cx.uint_type)
778 else if arg_type.is_ulong(&self.cx) {
779 ("__builtin_ctzl", self.cx.ulong_type)
781 else if arg_type.is_ulonglong(&self.cx) {
782 ("__builtin_ctzll", self.cx.ulonglong_type)
784 else if arg_type.is_u128(&self.cx) {
785 // Adapted from the algorithm to count leading zeroes from: https://stackoverflow.com/a/28433850/389119
786 let array_type = self.context.new_array_type(None, arg_type, 3);
787 let result = self.current_func()
788 .new_local(None, array_type, "count_loading_zeroes_results");
790 let sixty_four = self.gcc_int(arg_type, 64);
791 let shift = self.gcc_lshr(arg, sixty_four);
792 let high = self.gcc_int_cast(shift, self.u64_type);
793 let low = self.gcc_int_cast(arg, self.u64_type);
795 let zero = self.context.new_rvalue_zero(self.usize_type);
796 let one = self.context.new_rvalue_one(self.usize_type);
797 let two = self.context.new_rvalue_from_long(self.usize_type, 2);
799 let ctzll = self.context.get_builtin_function("__builtin_ctzll");
801 let first_elem = self.context.new_array_access(None, result, zero);
802 let first_value = self.gcc_int_cast(self.context.new_call(None, ctzll, &[low]), arg_type);
804 .add_assignment(None, first_elem, first_value);
806 let second_elem = self.context.new_array_access(None, result, one);
807 let second_value = self.gcc_add(self.gcc_int_cast(self.context.new_call(None, ctzll, &[high]), arg_type), sixty_four);
809 .add_assignment(None, second_elem, second_value);
811 let third_elem = self.context.new_array_access(None, result, two);
812 let third_value = self.gcc_int(arg_type, 128);
814 .add_assignment(None, third_elem, third_value);
816 let not_low = self.context.new_unary_op(None, UnaryOp::LogicalNegate, self.u64_type, low);
817 let not_high = self.context.new_unary_op(None, UnaryOp::LogicalNegate, self.u64_type, high);
818 let not_low_and_not_high = not_low & not_high;
819 let index = not_low + not_low_and_not_high;
820 // NOTE: the following cast is necessary to avoid a GIMPLE verification failure in
822 // TODO(antoyo): do the correct verification in libgccjit to avoid an error at the
823 // compilation stage.
824 let index = self.context.new_cast(None, index, self.i32_type);
826 let res = self.context.new_array_access(None, result, index);
828 return self.gcc_int_cast(res.to_rvalue(), result_type);
831 let count_trailing_zeroes = self.context.get_builtin_function("__builtin_ctzll");
832 let arg_size = arg_type.get_size();
833 let casted_arg = self.context.new_cast(None, arg, self.ulonglong_type);
834 let byte_diff = self.ulonglong_type.get_size() as i64 - arg_size as i64;
835 let diff = self.context.new_rvalue_from_long(self.int_type, byte_diff * 8);
836 let mask = self.context.new_rvalue_from_long(arg_type, -1); // To get the value with all bits set.
837 let masked = mask & self.context.new_unary_op(None, UnaryOp::BitwiseNegate, arg_type, arg);
838 let cond = self.context.new_comparison(None, ComparisonOp::Equals, masked, mask);
839 let diff = diff * self.context.new_cast(None, cond, self.int_type);
840 let res = self.context.new_call(None, count_trailing_zeroes, &[casted_arg]) - diff;
841 return self.context.new_cast(None, res, result_type);
843 let count_trailing_zeroes = self.context.get_builtin_function(count_trailing_zeroes);
845 if arg_type != expected_type {
846 self.context.new_cast(None, arg, expected_type)
851 let res = self.context.new_call(None, count_trailing_zeroes, &[arg]);
852 self.context.new_cast(None, res, result_type)
855 fn pop_count(&mut self, value: RValue<'gcc>) -> RValue<'gcc> {
856 // TODO(antoyo): use the optimized version with fewer operations.
857 let result_type = value.get_type();
858 let value_type = result_type.to_unsigned(self.cx);
861 if result_type.is_signed(self.cx) {
862 self.gcc_int_cast(value, value_type)
868 if value_type.is_u128(&self.cx) {
869 // TODO(antoyo): implement in the normal algorithm below to have a more efficient
870 // implementation (that does not require a call to __popcountdi2).
871 let popcount = self.context.get_builtin_function("__builtin_popcountll");
872 let sixty_four = self.gcc_int(value_type, 64);
873 let right_shift = self.gcc_lshr(value, sixty_four);
874 let high = self.gcc_int_cast(right_shift, self.cx.ulonglong_type);
875 let high = self.context.new_call(None, popcount, &[high]);
876 let low = self.gcc_int_cast(value, self.cx.ulonglong_type);
877 let low = self.context.new_call(None, popcount, &[low]);
878 let res = high + low;
879 return self.gcc_int_cast(res, result_type);
883 let mask = self.context.new_rvalue_from_long(value_type, 0x5555555555555555);
884 let left = value & mask;
885 let shifted = value >> self.context.new_rvalue_from_int(value_type, 1);
886 let right = shifted & mask;
887 let value = left + right;
890 let mask = self.context.new_rvalue_from_long(value_type, 0x3333333333333333);
891 let left = value & mask;
892 let shifted = value >> self.context.new_rvalue_from_int(value_type, 2);
893 let right = shifted & mask;
894 let value = left + right;
897 let mask = self.context.new_rvalue_from_long(value_type, 0x0F0F0F0F0F0F0F0F);
898 let left = value & mask;
899 let shifted = value >> self.context.new_rvalue_from_int(value_type, 4);
900 let right = shifted & mask;
901 let value = left + right;
903 if value_type.is_u8(&self.cx) {
904 return self.context.new_cast(None, value, result_type);
908 let mask = self.context.new_rvalue_from_long(value_type, 0x00FF00FF00FF00FF);
909 let left = value & mask;
910 let shifted = value >> self.context.new_rvalue_from_int(value_type, 8);
911 let right = shifted & mask;
912 let value = left + right;
914 if value_type.is_u16(&self.cx) {
915 return self.context.new_cast(None, value, result_type);
919 let mask = self.context.new_rvalue_from_long(value_type, 0x0000FFFF0000FFFF);
920 let left = value & mask;
921 let shifted = value >> self.context.new_rvalue_from_int(value_type, 16);
922 let right = shifted & mask;
923 let value = left + right;
925 if value_type.is_u32(&self.cx) {
926 return self.context.new_cast(None, value, result_type);
930 let mask = self.context.new_rvalue_from_long(value_type, 0x00000000FFFFFFFF);
931 let left = value & mask;
932 let shifted = value >> self.context.new_rvalue_from_int(value_type, 32);
933 let right = shifted & mask;
934 let value = left + right;
936 self.context.new_cast(None, value, result_type)
939 // Algorithm from: https://blog.regehr.org/archives/1063
940 fn rotate_left(&mut self, value: RValue<'gcc>, shift: RValue<'gcc>, width: u64) -> RValue<'gcc> {
941 let max = self.const_uint(shift.get_type(), width);
942 let shift = self.urem(shift, max);
943 let lhs = self.shl(value, shift);
944 let result_neg = self.neg(shift);
948 self.const_uint(shift.get_type(), width - 1),
950 let rhs = self.lshr(value, result_and);
954 // Algorithm from: https://blog.regehr.org/archives/1063
955 fn rotate_right(&mut self, value: RValue<'gcc>, shift: RValue<'gcc>, width: u64) -> RValue<'gcc> {
956 let max = self.const_uint(shift.get_type(), width);
957 let shift = self.urem(shift, max);
958 let lhs = self.lshr(value, shift);
959 let result_neg = self.neg(shift);
963 self.const_uint(shift.get_type(), width - 1),
965 let rhs = self.shl(value, result_and);
969 fn saturating_add(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>, signed: bool, width: u64) -> RValue<'gcc> {
970 let result_type = lhs.get_type();
972 // Based on algorithm from: https://stackoverflow.com/a/56531252/389119
973 let func = self.current_func.borrow().expect("func");
974 let res = func.new_local(None, result_type, "saturating_sum");
975 let supports_native_type = self.is_native_int_type(result_type);
977 if supports_native_type {
980 8 => "__builtin_add_overflow",
981 16 => "__builtin_add_overflow",
982 32 => "__builtin_sadd_overflow",
983 64 => "__builtin_saddll_overflow",
984 128 => "__builtin_add_overflow",
987 let overflow_func = self.context.get_builtin_function(func_name);
988 self.overflow_call(overflow_func, &[lhs, rhs, res.get_address(None)], None)
993 128 => "__rust_i128_addo",
996 let param_a = self.context.new_parameter(None, result_type, "a");
997 let param_b = self.context.new_parameter(None, result_type, "b");
998 let result_field = self.context.new_field(None, result_type, "result");
999 let overflow_field = self.context.new_field(None, self.bool_type, "overflow");
1000 let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]);
1001 let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false);
1002 let result = self.context.new_call(None, func, &[lhs, rhs]);
1003 let overflow = result.access_field(None, overflow_field);
1004 let int_result = result.access_field(None, result_field);
1005 self.llbb().add_assignment(None, res, int_result);
1009 let then_block = func.new_block("then");
1010 let after_block = func.new_block("after");
1012 // Return `result_type`'s maximum or minimum value on overflow
1013 // NOTE: convert the type to unsigned to have an unsigned shift.
1014 let unsigned_type = result_type.to_unsigned(&self.cx);
1015 let shifted = self.gcc_lshr(self.gcc_int_cast(lhs, unsigned_type), self.gcc_int(unsigned_type, width as i64 - 1));
1016 let uint_max = self.gcc_not(self.gcc_int(unsigned_type, 0));
1017 let int_max = self.gcc_lshr(uint_max, self.gcc_int(unsigned_type, 1));
1018 then_block.add_assignment(None, res, self.gcc_int_cast(self.gcc_add(shifted, int_max), result_type));
1019 then_block.end_with_jump(None, after_block);
1021 self.llbb().end_with_conditional(None, overflow, then_block, after_block);
1023 // NOTE: since jumps were added in a place rustc does not
1024 // expect, the current block in the state need to be updated.
1025 self.switch_to_block(after_block);
1030 // Algorithm from: http://locklessinc.com/articles/sat_arithmetic/
1031 let res = self.gcc_add(lhs, rhs);
1032 let cond = self.gcc_icmp(IntPredicate::IntULT, res, lhs);
1033 let value = self.gcc_neg(self.gcc_int_cast(cond, result_type));
1034 self.gcc_or(res, value)
1038 // Algorithm from: https://locklessinc.com/articles/sat_arithmetic/
1039 fn saturating_sub(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>, signed: bool, width: u64) -> RValue<'gcc> {
1040 let result_type = lhs.get_type();
1042 // Based on algorithm from: https://stackoverflow.com/a/56531252/389119
1043 let func = self.current_func.borrow().expect("func");
1044 let res = func.new_local(None, result_type, "saturating_diff");
1045 let supports_native_type = self.is_native_int_type(result_type);
1047 if supports_native_type {
1050 8 => "__builtin_sub_overflow",
1051 16 => "__builtin_sub_overflow",
1052 32 => "__builtin_ssub_overflow",
1053 64 => "__builtin_ssubll_overflow",
1054 128 => "__builtin_sub_overflow",
1055 _ => unreachable!(),
1057 let overflow_func = self.context.get_builtin_function(func_name);
1058 self.overflow_call(overflow_func, &[lhs, rhs, res.get_address(None)], None)
1063 128 => "__rust_i128_subo",
1064 _ => unreachable!(),
1066 let param_a = self.context.new_parameter(None, result_type, "a");
1067 let param_b = self.context.new_parameter(None, result_type, "b");
1068 let result_field = self.context.new_field(None, result_type, "result");
1069 let overflow_field = self.context.new_field(None, self.bool_type, "overflow");
1070 let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]);
1071 let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false);
1072 let result = self.context.new_call(None, func, &[lhs, rhs]);
1073 let overflow = result.access_field(None, overflow_field);
1074 let int_result = result.access_field(None, result_field);
1075 self.llbb().add_assignment(None, res, int_result);
1079 let then_block = func.new_block("then");
1080 let after_block = func.new_block("after");
1082 // Return `result_type`'s maximum or minimum value on overflow
1083 // NOTE: convert the type to unsigned to have an unsigned shift.
1084 let unsigned_type = result_type.to_unsigned(&self.cx);
1085 let shifted = self.gcc_lshr(self.gcc_int_cast(lhs, unsigned_type), self.gcc_int(unsigned_type, width as i64 - 1));
1086 let uint_max = self.gcc_not(self.gcc_int(unsigned_type, 0));
1087 let int_max = self.gcc_lshr(uint_max, self.gcc_int(unsigned_type, 1));
1088 then_block.add_assignment(None, res, self.gcc_int_cast(self.gcc_add(shifted, int_max), result_type));
1089 then_block.end_with_jump(None, after_block);
1091 self.llbb().end_with_conditional(None, overflow, then_block, after_block);
1093 // NOTE: since jumps were added in a place rustc does not
1094 // expect, the current block in the state need to be updated.
1095 self.switch_to_block(after_block);
1100 let res = self.gcc_sub(lhs, rhs);
1101 let comparison = self.gcc_icmp(IntPredicate::IntULE, res, lhs);
1102 let value = self.gcc_neg(self.gcc_int_cast(comparison, result_type));
1103 self.gcc_and(res, value)
1108 fn try_intrinsic<'gcc, 'tcx>(bx: &mut Builder<'_, 'gcc, 'tcx>, try_func: RValue<'gcc>, data: RValue<'gcc>, _catch_func: RValue<'gcc>, dest: RValue<'gcc>) {
1109 // NOTE: the `|| true` here is to use the panic=abort strategy with panic=unwind too
1110 if bx.sess().panic_strategy() == PanicStrategy::Abort || true {
1111 // TODO(bjorn3): Properly implement unwinding and remove the `|| true` once this is done.
1112 bx.call(bx.type_void(), try_func, &[data], None);
1113 // Return 0 unconditionally from the intrinsic call;
1114 // we can never unwind.
1115 let ret_align = bx.tcx.data_layout.i32_align.abi;
1116 bx.store(bx.const_i32(0), dest, ret_align);
1118 else if wants_msvc_seh(bx.sess()) {