3 use std::convert::TryFrom;
18 use rustc_codegen_ssa::MemFlags;
19 use rustc_codegen_ssa::common::{AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope};
20 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
21 use rustc_codegen_ssa::mir::place::PlaceRef;
22 use rustc_codegen_ssa::traits::{
33 use rustc_data_structures::fx::FxHashSet;
34 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
35 use rustc_middle::ty::layout::{FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasParamEnv, HasTyCtxt, LayoutError, LayoutOfHelpers, TyAndLayout};
37 use rustc_span::def_id::DefId;
38 use rustc_target::abi::{
47 use rustc_target::spec::{HasTargetSpec, Target};
49 use crate::common::{SignType, TypeReflection, type_is_pointer};
50 use crate::context::CodegenCx;
51 use crate::intrinsic::llvm;
52 use crate::type_of::LayoutGccExt;
57 // TODO(antoyo): remove this variable.
58 static mut RETURN_VALUE_COUNT: usize = 0;
60 enum ExtremumOperation {
65 pub struct Builder<'a: 'gcc, 'gcc, 'tcx> {
66 pub cx: &'a CodegenCx<'gcc, 'tcx>,
67 pub block: Block<'gcc>,
68 stack_var_count: Cell<usize>,
71 impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
72 fn with_cx(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Self {
76 stack_var_count: Cell::new(0),
80 fn atomic_extremum(&mut self, operation: ExtremumOperation, dst: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering) -> RValue<'gcc> {
81 let size = src.get_type().get_size();
83 let func = self.current_func();
87 // TODO(antoyo): does this make sense?
88 AtomicOrdering::AcquireRelease | AtomicOrdering::Release => AtomicOrdering::Acquire,
91 let previous_value = self.atomic_load(dst.get_type(), dst, load_ordering, Size::from_bytes(size));
92 let previous_var = func.new_local(None, previous_value.get_type(), "previous_value");
93 let return_value = func.new_local(None, previous_value.get_type(), "return_value");
94 self.llbb().add_assignment(None, previous_var, previous_value);
95 self.llbb().add_assignment(None, return_value, previous_var.to_rvalue());
97 let while_block = func.new_block("while");
98 let after_block = func.new_block("after_while");
99 self.llbb().end_with_jump(None, while_block);
101 // NOTE: since jumps were added and compare_exchange doesn't expect this, the current block in the
102 // state need to be updated.
103 self.switch_to_block(while_block);
105 let comparison_operator =
107 ExtremumOperation::Max => ComparisonOp::LessThan,
108 ExtremumOperation::Min => ComparisonOp::GreaterThan,
111 let cond1 = self.context.new_comparison(None, comparison_operator, previous_var.to_rvalue(), self.context.new_cast(None, src, previous_value.get_type()));
112 let compare_exchange = self.compare_exchange(dst, previous_var, src, order, load_ordering, false);
113 let cond2 = self.cx.context.new_unary_op(None, UnaryOp::LogicalNegate, compare_exchange.get_type(), compare_exchange);
114 let cond = self.cx.context.new_binary_op(None, BinaryOp::LogicalAnd, self.cx.bool_type, cond1, cond2);
116 while_block.end_with_conditional(None, cond, while_block, after_block);
118 // NOTE: since jumps were added in a place rustc does not expect, the current block in the
119 // state need to be updated.
120 self.switch_to_block(after_block);
122 return_value.to_rvalue()
125 fn compare_exchange(&self, dst: RValue<'gcc>, cmp: LValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering, failure_order: AtomicOrdering, weak: bool) -> RValue<'gcc> {
126 let size = src.get_type().get_size();
127 let compare_exchange = self.context.get_builtin_function(&format!("__atomic_compare_exchange_{}", size));
128 let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
129 let failure_order = self.context.new_rvalue_from_int(self.i32_type, failure_order.to_gcc());
130 let weak = self.context.new_rvalue_from_int(self.bool_type, weak as i32);
132 let void_ptr_type = self.context.new_type::<*mut ()>();
133 let volatile_void_ptr_type = void_ptr_type.make_volatile();
134 let dst = self.context.new_cast(None, dst, volatile_void_ptr_type);
135 let expected = self.context.new_cast(None, cmp.get_address(None), void_ptr_type);
137 // NOTE: not sure why, but we have the wrong type here.
138 let int_type = compare_exchange.get_param(2).to_rvalue().get_type();
139 let src = self.context.new_cast(None, src, int_type);
140 self.context.new_call(None, compare_exchange, &[dst, expected, src, weak, order, failure_order])
143 pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) {
144 self.llbb().add_assignment(None, lvalue, value);
147 fn check_call<'b>(&mut self, _typ: &str, func: Function<'gcc>, args: &'b [RValue<'gcc>]) -> Cow<'b, [RValue<'gcc>]> {
148 let mut all_args_match = true;
149 let mut param_types = vec![];
150 let param_count = func.get_param_count();
151 for (index, arg) in args.iter().enumerate().take(param_count) {
152 let param = func.get_param(index as i32);
153 let param = param.to_rvalue().get_type();
154 if param != arg.get_type() {
155 all_args_match = false;
157 param_types.push(param);
161 return Cow::Borrowed(args);
164 let casted_args: Vec<_> = param_types
168 .map(|(_i, (expected_ty, &actual_val))| {
169 let actual_ty = actual_val.get_type();
170 if expected_ty != actual_ty {
171 self.bitcast(actual_val, expected_ty)
179 Cow::Owned(casted_args)
182 fn check_ptr_call<'b>(&mut self, _typ: &str, func_ptr: RValue<'gcc>, args: &'b [RValue<'gcc>]) -> Cow<'b, [RValue<'gcc>]> {
183 let mut all_args_match = true;
184 let mut param_types = vec![];
185 let gcc_func = func_ptr.get_type().dyncast_function_ptr_type().expect("function ptr");
186 for (index, arg) in args.iter().enumerate().take(gcc_func.get_param_count()) {
187 let param = gcc_func.get_param_type(index);
188 if param != arg.get_type() {
189 all_args_match = false;
191 param_types.push(param);
194 let mut on_stack_param_indices = FxHashSet::default();
195 if let Some(indices) = self.on_stack_params.borrow().get(&gcc_func) {
196 on_stack_param_indices = indices.clone();
200 return Cow::Borrowed(args);
203 let func_name = format!("{:?}", func_ptr);
205 let casted_args: Vec<_> = param_types
209 .map(|(index, (expected_ty, &actual_val))| {
210 if llvm::ignore_arg_cast(&func_name, index, args.len()) {
214 let actual_ty = actual_val.get_type();
215 if expected_ty != actual_ty {
216 if !actual_ty.is_vector() && !expected_ty.is_vector() && actual_ty.is_integral() && expected_ty.is_integral() && actual_ty.get_size() != expected_ty.get_size() {
217 self.context.new_cast(None, actual_val, expected_ty)
219 else if on_stack_param_indices.contains(&index) {
220 actual_val.dereference(None).to_rvalue()
223 assert!(!((actual_ty.is_vector() && !expected_ty.is_vector()) || (!actual_ty.is_vector() && expected_ty.is_vector())), "{:?} ({}) -> {:?} ({}), index: {:?}[{}]", actual_ty, actual_ty.is_vector(), expected_ty, expected_ty.is_vector(), func_ptr, index);
224 // TODO(antoyo): perhaps use __builtin_convertvector for vector casting.
225 self.bitcast(actual_val, expected_ty)
234 Cow::Owned(casted_args)
237 fn check_store(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> {
238 let dest_ptr_ty = self.cx.val_ty(ptr).make_pointer(); // TODO(antoyo): make sure make_pointer() is okay here.
239 let stored_ty = self.cx.val_ty(val);
240 let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
242 if dest_ptr_ty == stored_ptr_ty {
246 self.bitcast(ptr, stored_ptr_ty)
250 pub fn current_func(&self) -> Function<'gcc> {
251 self.block.get_function()
254 fn function_call(&mut self, func: RValue<'gcc>, args: &[RValue<'gcc>], _funclet: Option<&Funclet>) -> RValue<'gcc> {
255 // TODO(antoyo): remove when the API supports a different type for functions.
256 let func: Function<'gcc> = self.cx.rvalue_as_function(func);
257 let args = self.check_call("call", func, args);
259 // gccjit requires to use the result of functions, even when it's not used.
260 // That's why we assign the result to a local or call add_eval().
261 let return_type = func.get_return_type();
262 let void_type = self.context.new_type::<()>();
263 let current_func = self.block.get_function();
264 if return_type != void_type {
265 unsafe { RETURN_VALUE_COUNT += 1 };
266 let result = current_func.new_local(None, return_type, &format!("returnValue{}", unsafe { RETURN_VALUE_COUNT }));
267 self.block.add_assignment(None, result, self.cx.context.new_call(None, func, &args));
271 self.block.add_eval(None, self.cx.context.new_call(None, func, &args));
272 // Return dummy value when not having return value.
273 self.context.new_rvalue_from_long(self.isize_type, 0)
277 fn function_ptr_call(&mut self, func_ptr: RValue<'gcc>, args: &[RValue<'gcc>], _funclet: Option<&Funclet>) -> RValue<'gcc> {
278 let args = self.check_ptr_call("call", func_ptr, args);
280 // gccjit requires to use the result of functions, even when it's not used.
281 // That's why we assign the result to a local or call add_eval().
282 let gcc_func = func_ptr.get_type().dyncast_function_ptr_type().expect("function ptr");
283 let return_type = gcc_func.get_return_type();
284 let void_type = self.context.new_type::<()>();
285 let current_func = self.block.get_function();
287 if return_type != void_type {
288 unsafe { RETURN_VALUE_COUNT += 1 };
289 let result = current_func.new_local(None, return_type, &format!("ptrReturnValue{}", unsafe { RETURN_VALUE_COUNT }));
290 let func_name = format!("{:?}", func_ptr);
291 let args = llvm::adjust_intrinsic_arguments(&self, gcc_func, args, &func_name);
292 self.block.add_assignment(None, result, self.cx.context.new_call_through_ptr(None, func_ptr, &args));
296 #[cfg(not(feature="master"))]
297 if gcc_func.get_param_count() == 0 {
298 // FIXME(antoyo): As a temporary workaround for unsupported LLVM intrinsics.
299 self.block.add_eval(None, self.cx.context.new_call_through_ptr(None, func_ptr, &[]));
302 self.block.add_eval(None, self.cx.context.new_call_through_ptr(None, func_ptr, &args));
304 #[cfg(feature="master")]
305 self.block.add_eval(None, self.cx.context.new_call_through_ptr(None, func_ptr, &args));
306 // Return dummy value when not having return value.
307 let result = current_func.new_local(None, self.isize_type, "dummyValueThatShouldNeverBeUsed");
308 self.block.add_assignment(None, result, self.context.new_rvalue_from_long(self.isize_type, 0));
313 pub fn overflow_call(&self, func: Function<'gcc>, args: &[RValue<'gcc>], _funclet: Option<&Funclet>) -> RValue<'gcc> {
314 // gccjit requires to use the result of functions, even when it's not used.
315 // That's why we assign the result to a local.
316 let return_type = self.context.new_type::<bool>();
317 let current_func = self.block.get_function();
318 // TODO(antoyo): return the new_call() directly? Since the overflow function has no side-effects.
319 unsafe { RETURN_VALUE_COUNT += 1 };
320 let result = current_func.new_local(None, return_type, &format!("overflowReturnValue{}", unsafe { RETURN_VALUE_COUNT }));
321 self.block.add_assignment(None, result, self.cx.context.new_call(None, func, &args));
326 impl<'gcc, 'tcx> HasCodegen<'tcx> for Builder<'_, 'gcc, 'tcx> {
327 type CodegenCx = CodegenCx<'gcc, 'tcx>;
330 impl<'tcx> HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
331 fn tcx(&self) -> TyCtxt<'tcx> {
336 impl HasDataLayout for Builder<'_, '_, '_> {
337 fn data_layout(&self) -> &TargetDataLayout {
338 self.cx.data_layout()
342 impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
343 type LayoutOfResult = TyAndLayout<'tcx>;
346 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
347 self.cx.handle_layout_err(err, span, ty)
351 impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
352 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
355 fn handle_fn_abi_err(
357 err: FnAbiError<'tcx>,
359 fn_abi_request: FnAbiRequest<'tcx>,
361 self.cx.handle_fn_abi_err(err, span, fn_abi_request)
365 impl<'gcc, 'tcx> Deref for Builder<'_, 'gcc, 'tcx> {
366 type Target = CodegenCx<'gcc, 'tcx>;
368 fn deref(&self) -> &Self::Target {
373 impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> {
374 type Value = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Value;
375 type Function = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Function;
376 type BasicBlock = <CodegenCx<'gcc, 'tcx> as BackendTypes>::BasicBlock;
377 type Type = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Type;
378 type Funclet = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Funclet;
380 type DIScope = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIScope;
381 type DILocation = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DILocation;
382 type DIVariable = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIVariable;
385 impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
386 fn build(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Self {
387 Builder::with_cx(cx, block)
390 fn llbb(&self) -> Block<'gcc> {
394 fn append_block(cx: &'a CodegenCx<'gcc, 'tcx>, func: RValue<'gcc>, name: &str) -> Block<'gcc> {
395 let func = cx.rvalue_as_function(func);
399 fn append_sibling_block(&mut self, name: &str) -> Block<'gcc> {
400 let func = self.current_func();
404 fn switch_to_block(&mut self, block: Self::BasicBlock) {
408 fn ret_void(&mut self) {
409 self.llbb().end_with_void_return(None)
412 fn ret(&mut self, value: RValue<'gcc>) {
414 if self.structs_as_pointer.borrow().contains(&value) {
415 // NOTE: hack to workaround a limitation of the rustc API: see comment on
416 // CodegenCx.structs_as_pointer
417 value.dereference(None).to_rvalue()
422 self.llbb().end_with_return(None, value);
425 fn br(&mut self, dest: Block<'gcc>) {
426 self.llbb().end_with_jump(None, dest)
429 fn cond_br(&mut self, cond: RValue<'gcc>, then_block: Block<'gcc>, else_block: Block<'gcc>) {
430 self.llbb().end_with_conditional(None, cond, then_block, else_block)
433 fn switch(&mut self, value: RValue<'gcc>, default_block: Block<'gcc>, cases: impl ExactSizeIterator<Item = (u128, Block<'gcc>)>) {
434 let mut gcc_cases = vec![];
435 let typ = self.val_ty(value);
436 for (on_val, dest) in cases {
437 let on_val = self.const_uint_big(typ, on_val);
438 gcc_cases.push(self.context.new_case(on_val, on_val, dest));
440 self.block.end_with_switch(None, value, default_block, &gcc_cases);
443 fn invoke(&mut self, typ: Type<'gcc>, func: RValue<'gcc>, args: &[RValue<'gcc>], then: Block<'gcc>, catch: Block<'gcc>, _funclet: Option<&Funclet>) -> RValue<'gcc> {
444 // TODO(bjorn3): Properly implement unwinding.
445 let call_site = self.call(typ, func, args, None);
446 let condition = self.context.new_rvalue_from_int(self.bool_type, 1);
447 self.llbb().end_with_conditional(None, condition, then, catch);
451 fn unreachable(&mut self) {
452 let func = self.context.get_builtin_function("__builtin_unreachable");
453 self.block.add_eval(None, self.context.new_call(None, func, &[]));
454 let return_type = self.block.get_function().get_return_type();
455 let void_type = self.context.new_type::<()>();
456 if return_type == void_type {
457 self.block.end_with_void_return(None)
460 let return_value = self.current_func()
461 .new_local(None, return_type, "unreachableReturn");
462 self.block.end_with_return(None, return_value)
466 fn add(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
470 fn fadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
474 fn sub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
478 fn fsub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
482 fn mul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
486 fn fmul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
490 fn udiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
494 fn exactudiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
495 // TODO(antoyo): poison if not exact.
496 let a_type = a.get_type().to_unsigned(self);
497 let a = self.gcc_int_cast(a, a_type);
498 let b_type = b.get_type().to_unsigned(self);
499 let b = self.gcc_int_cast(b, b_type);
503 fn sdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
507 fn exactsdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
508 // TODO(antoyo): poison if not exact.
509 // FIXME(antoyo): rustc_codegen_ssa::mir::intrinsic uses different types for a and b but they
510 // should be the same.
511 let typ = a.get_type().to_signed(self);
512 let b = self.context.new_cast(None, b, typ);
516 fn fdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
520 fn urem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
524 fn srem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
528 fn frem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
529 if a.get_type().is_compatible_with(self.cx.float_type) {
530 let fmodf = self.context.get_builtin_function("fmodf");
531 // FIXME(antoyo): this seems to produce the wrong result.
532 return self.context.new_call(None, fmodf, &[a, b]);
534 assert_eq!(a.get_type().unqualified(), self.cx.double_type);
536 let fmod = self.context.get_builtin_function("fmod");
537 return self.context.new_call(None, fmod, &[a, b]);
540 fn shl(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
544 fn lshr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
548 fn ashr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
549 // TODO(antoyo): check whether behavior is an arithmetic shift for >> .
550 // It seems to be if the value is signed.
554 fn and(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
558 fn or(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
562 fn xor(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
566 fn neg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
570 fn fneg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
571 self.cx.context.new_unary_op(None, UnaryOp::Minus, a.get_type(), a)
574 fn not(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
578 fn unchecked_sadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
582 fn unchecked_uadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
586 fn unchecked_ssub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
590 fn unchecked_usub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
591 // TODO(antoyo): should generate poison value?
595 fn unchecked_smul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
599 fn unchecked_umul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
603 fn fadd_fast(&mut self, _lhs: RValue<'gcc>, _rhs: RValue<'gcc>) -> RValue<'gcc> {
607 fn fsub_fast(&mut self, _lhs: RValue<'gcc>, _rhs: RValue<'gcc>) -> RValue<'gcc> {
611 fn fmul_fast(&mut self, _lhs: RValue<'gcc>, _rhs: RValue<'gcc>) -> RValue<'gcc> {
615 fn fdiv_fast(&mut self, _lhs: RValue<'gcc>, _rhs: RValue<'gcc>) -> RValue<'gcc> {
619 fn frem_fast(&mut self, _lhs: RValue<'gcc>, _rhs: RValue<'gcc>) -> RValue<'gcc> {
623 fn checked_binop(&mut self, oop: OverflowOp, typ: Ty<'_>, lhs: Self::Value, rhs: Self::Value) -> (Self::Value, Self::Value) {
624 self.gcc_checked_binop(oop, typ, lhs, rhs)
627 fn alloca(&mut self, ty: Type<'gcc>, align: Align) -> RValue<'gcc> {
628 // FIXME(antoyo): this check that we don't call get_aligned() a second time on a type.
629 // Ideally, we shouldn't need to do this check.
631 if ty == self.cx.u128_type || ty == self.cx.i128_type {
635 ty.get_aligned(align.bytes())
637 // TODO(antoyo): It might be better to return a LValue, but fixing the rustc API is non-trivial.
638 self.stack_var_count.set(self.stack_var_count.get() + 1);
639 self.current_func().new_local(None, aligned_type, &format!("stack_var_{}", self.stack_var_count.get())).get_address(None)
642 fn dynamic_alloca(&mut self, _ty: Type<'gcc>, _align: Align) -> RValue<'gcc> {
646 fn array_alloca(&mut self, _ty: Type<'gcc>, _len: RValue<'gcc>, _align: Align) -> RValue<'gcc> {
650 fn load(&mut self, pointee_ty: Type<'gcc>, ptr: RValue<'gcc>, _align: Align) -> RValue<'gcc> {
651 let block = self.llbb();
652 let function = block.get_function();
653 // NOTE: instead of returning the dereference here, we have to assign it to a variable in
654 // the current basic block. Otherwise, it could be used in another basic block, causing a
655 // dereference after a drop, for instance.
656 // TODO(antoyo): handle align of the load instruction.
657 let ptr = self.context.new_cast(None, ptr, pointee_ty.make_pointer());
658 let deref = ptr.dereference(None).to_rvalue();
659 unsafe { RETURN_VALUE_COUNT += 1 };
660 let loaded_value = function.new_local(None, pointee_ty, &format!("loadedValue{}", unsafe { RETURN_VALUE_COUNT }));
661 block.add_assignment(None, loaded_value, deref);
662 loaded_value.to_rvalue()
665 fn volatile_load(&mut self, _ty: Type<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> {
666 // TODO(antoyo): use ty.
667 let ptr = self.context.new_cast(None, ptr, ptr.get_type().make_volatile());
668 ptr.dereference(None).to_rvalue()
671 fn atomic_load(&mut self, _ty: Type<'gcc>, ptr: RValue<'gcc>, order: AtomicOrdering, size: Size) -> RValue<'gcc> {
672 // TODO(antoyo): use ty.
673 // TODO(antoyo): handle alignment.
674 let atomic_load = self.context.get_builtin_function(&format!("__atomic_load_{}", size.bytes()));
675 let ordering = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
677 let volatile_const_void_ptr_type = self.context.new_type::<()>()
681 let ptr = self.context.new_cast(None, ptr, volatile_const_void_ptr_type);
682 self.context.new_call(None, atomic_load, &[ptr, ordering])
685 fn load_operand(&mut self, place: PlaceRef<'tcx, RValue<'gcc>>) -> OperandRef<'tcx, RValue<'gcc>> {
686 assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
688 if place.layout.is_zst() {
689 return OperandRef::new_zst(self, place.layout);
692 fn scalar_load_metadata<'a, 'gcc, 'tcx>(bx: &mut Builder<'a, 'gcc, 'tcx>, load: RValue<'gcc>, scalar: &abi::Scalar) {
693 let vr = scalar.valid_range(bx);
694 match scalar.primitive() {
696 if !scalar.is_always_valid(bx) {
697 bx.range_metadata(load, vr);
700 abi::Pointer if vr.start < vr.end && !vr.contains(0) => {
701 bx.nonnull_metadata(load);
708 if let Some(llextra) = place.llextra {
709 OperandValue::Ref(place.llval, Some(llextra), place.align)
711 else if place.layout.is_gcc_immediate() {
712 let load = self.load(
713 place.layout.gcc_type(self, false),
717 if let abi::Abi::Scalar(ref scalar) = place.layout.abi {
718 scalar_load_metadata(self, load, scalar);
720 OperandValue::Immediate(self.to_immediate(load, place.layout))
722 else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
723 let b_offset = a.size(self).align_to(b.align(self).abi);
724 let pair_type = place.layout.gcc_type(self, false);
726 let mut load = |i, scalar: &abi::Scalar, align| {
727 let llptr = self.struct_gep(pair_type, place.llval, i as u64);
728 let llty = place.layout.scalar_pair_element_gcc_type(self, i, false);
729 let load = self.load(llty, llptr, align);
730 scalar_load_metadata(self, load, scalar);
731 if scalar.is_bool() { self.trunc(load, self.type_i1()) } else { load }
735 load(0, a, place.align),
736 load(1, b, place.align.restrict_for_offset(b_offset)),
740 OperandValue::Ref(place.llval, None, place.align)
743 OperandRef { val, layout: place.layout }
746 fn write_operand_repeatedly(mut self, cg_elem: OperandRef<'tcx, RValue<'gcc>>, count: u64, dest: PlaceRef<'tcx, RValue<'gcc>>) -> Self {
747 let zero = self.const_usize(0);
748 let count = self.const_usize(count);
749 let start = dest.project_index(&mut self, zero).llval;
750 let end = dest.project_index(&mut self, count).llval;
752 let header_bb = self.append_sibling_block("repeat_loop_header");
753 let body_bb = self.append_sibling_block("repeat_loop_body");
754 let next_bb = self.append_sibling_block("repeat_loop_next");
756 let ptr_type = start.get_type();
757 let current = self.llbb().get_function().new_local(None, ptr_type, "loop_var");
758 let current_val = current.to_rvalue();
759 self.assign(current, start);
763 self.switch_to_block(header_bb);
764 let keep_going = self.icmp(IntPredicate::IntNE, current_val, end);
765 self.cond_br(keep_going, body_bb, next_bb);
767 self.switch_to_block(body_bb);
768 let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
769 cg_elem.val.store(&mut self, PlaceRef::new_sized_aligned(current_val, cg_elem.layout, align));
771 let next = self.inbounds_gep(self.backend_type(cg_elem.layout), current.to_rvalue(), &[self.const_usize(1)]);
772 self.llbb().add_assignment(None, current, next);
775 self.switch_to_block(next_bb);
779 fn range_metadata(&mut self, _load: RValue<'gcc>, _range: WrappingRange) {
783 fn nonnull_metadata(&mut self, _load: RValue<'gcc>) {
787 fn store(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> {
788 self.store_with_flags(val, ptr, align, MemFlags::empty())
791 fn store_with_flags(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>, align: Align, _flags: MemFlags) -> RValue<'gcc> {
792 let ptr = self.check_store(val, ptr);
793 let destination = ptr.dereference(None);
794 // NOTE: libgccjit does not support specifying the alignment on the assignment, so we cast
795 // to type so it gets the proper alignment.
796 let destination_type = destination.to_rvalue().get_type().unqualified();
797 let aligned_type = destination_type.get_aligned(align.bytes()).make_pointer();
798 let aligned_destination = self.cx.context.new_bitcast(None, ptr, aligned_type);
799 let aligned_destination = aligned_destination.dereference(None);
800 self.llbb().add_assignment(None, aligned_destination, val);
801 // TODO(antoyo): handle align and flags.
802 // NOTE: dummy value here since it's never used. FIXME(antoyo): API should not return a value here?
803 self.cx.context.new_rvalue_zero(self.type_i32())
806 fn atomic_store(&mut self, value: RValue<'gcc>, ptr: RValue<'gcc>, order: AtomicOrdering, size: Size) {
807 // TODO(antoyo): handle alignment.
808 let atomic_store = self.context.get_builtin_function(&format!("__atomic_store_{}", size.bytes()));
809 let ordering = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
810 let volatile_const_void_ptr_type = self.context.new_type::<()>()
813 let ptr = self.context.new_cast(None, ptr, volatile_const_void_ptr_type);
815 // FIXME(antoyo): fix libgccjit to allow comparing an integer type with an aligned integer type because
816 // the following cast is required to avoid this error:
817 // gcc_jit_context_new_call: mismatching types for argument 2 of function "__atomic_store_4": assignment to param arg1 (type: int) from loadedValue3577 (type: unsigned int __attribute__((aligned(4))))
818 let int_type = atomic_store.get_param(1).to_rvalue().get_type();
819 let value = self.context.new_cast(None, value, int_type);
821 .add_eval(None, self.context.new_call(None, atomic_store, &[ptr, value, ordering]));
824 fn gep(&mut self, _typ: Type<'gcc>, ptr: RValue<'gcc>, indices: &[RValue<'gcc>]) -> RValue<'gcc> {
825 let mut result = ptr;
826 for index in indices {
827 result = self.context.new_array_access(None, result, *index).get_address(None).to_rvalue();
832 fn inbounds_gep(&mut self, _typ: Type<'gcc>, ptr: RValue<'gcc>, indices: &[RValue<'gcc>]) -> RValue<'gcc> {
833 // FIXME(antoyo): would be safer if doing the same thing (loop) as gep.
834 // TODO(antoyo): specify inbounds somehow.
835 match indices.len() {
837 self.context.new_array_access(None, ptr, indices[0]).get_address(None)
840 let array = ptr.dereference(None); // TODO(antoyo): assert that first index is 0?
841 self.context.new_array_access(None, array, indices[1]).get_address(None)
843 _ => unimplemented!(),
847 fn struct_gep(&mut self, value_type: Type<'gcc>, ptr: RValue<'gcc>, idx: u64) -> RValue<'gcc> {
848 // FIXME(antoyo): it would be better if the API only called this on struct, not on arrays.
849 assert_eq!(idx as usize as u64, idx);
850 let value = ptr.dereference(None).to_rvalue();
852 if value_type.dyncast_array().is_some() {
853 let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from"));
854 let element = self.context.new_array_access(None, value, index);
855 element.get_address(None)
857 else if let Some(vector_type) = value_type.dyncast_vector() {
858 let array_type = vector_type.get_element_type().make_pointer();
859 let array = self.bitcast(ptr, array_type);
860 let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from"));
861 let element = self.context.new_array_access(None, array, index);
862 element.get_address(None)
864 else if let Some(struct_type) = value_type.is_struct() {
865 ptr.dereference_field(None, struct_type.get_field(idx as i32)).get_address(None)
868 panic!("Unexpected type {:?}", value_type);
873 fn trunc(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
874 // TODO(antoyo): check that it indeed truncate the value.
875 self.gcc_int_cast(value, dest_ty)
878 fn sext(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
879 // TODO(antoyo): check that it indeed sign extend the value.
880 if dest_ty.dyncast_vector().is_some() {
881 // TODO(antoyo): nothing to do as it is only for LLVM?
884 self.context.new_cast(None, value, dest_ty)
887 fn fptoui(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
888 self.gcc_float_to_uint_cast(value, dest_ty)
891 fn fptosi(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
892 self.gcc_float_to_int_cast(value, dest_ty)
895 fn uitofp(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
896 self.gcc_uint_to_float_cast(value, dest_ty)
899 fn sitofp(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
900 self.gcc_int_to_float_cast(value, dest_ty)
903 fn fptrunc(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
904 // TODO(antoyo): make sure it truncates.
905 self.context.new_cast(None, value, dest_ty)
908 fn fpext(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
909 self.context.new_cast(None, value, dest_ty)
912 fn ptrtoint(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
913 let usize_value = self.cx.const_bitcast(value, self.cx.type_isize());
914 self.intcast(usize_value, dest_ty, false)
917 fn inttoptr(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
918 let usize_value = self.intcast(value, self.cx.type_isize(), false);
919 self.cx.const_bitcast(usize_value, dest_ty)
922 fn bitcast(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
923 self.cx.const_bitcast(value, dest_ty)
926 fn intcast(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>, _is_signed: bool) -> RValue<'gcc> {
927 // NOTE: is_signed is for value, not dest_typ.
928 self.gcc_int_cast(value, dest_typ)
931 fn pointercast(&mut self, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
932 let val_type = value.get_type();
933 match (type_is_pointer(val_type), type_is_pointer(dest_ty)) {
935 // NOTE: Projecting a field of a pointer type will attempt a cast from a signed char to
936 // a pointer, which is not supported by gccjit.
937 return self.cx.context.new_cast(None, self.inttoptr(value, val_type.make_pointer()), dest_ty);
940 // When they are not pointers, we want a transmute (or reinterpret_cast).
941 self.bitcast(value, dest_ty)
943 (true, true) => self.cx.context.new_cast(None, value, dest_ty),
944 (true, false) => unimplemented!(),
949 fn icmp(&mut self, op: IntPredicate, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
950 self.gcc_icmp(op, lhs, rhs)
953 fn fcmp(&mut self, op: RealPredicate, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
954 self.context.new_comparison(None, op.to_gcc_comparison(), lhs, rhs)
957 /* Miscellaneous instructions */
958 fn memcpy(&mut self, dst: RValue<'gcc>, _dst_align: Align, src: RValue<'gcc>, _src_align: Align, size: RValue<'gcc>, flags: MemFlags) {
959 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
960 let size = self.intcast(size, self.type_size_t(), false);
961 let _is_volatile = flags.contains(MemFlags::VOLATILE);
962 let dst = self.pointercast(dst, self.type_i8p());
963 let src = self.pointercast(src, self.type_ptr_to(self.type_void()));
964 let memcpy = self.context.get_builtin_function("memcpy");
965 // TODO(antoyo): handle aligns and is_volatile.
966 self.block.add_eval(None, self.context.new_call(None, memcpy, &[dst, src, size]));
969 fn memmove(&mut self, dst: RValue<'gcc>, dst_align: Align, src: RValue<'gcc>, src_align: Align, size: RValue<'gcc>, flags: MemFlags) {
970 if flags.contains(MemFlags::NONTEMPORAL) {
971 // HACK(nox): This is inefficient but there is no nontemporal memmove.
972 let val = self.load(src.get_type().get_pointee().expect("get_pointee"), src, src_align);
973 let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
974 self.store_with_flags(val, ptr, dst_align, flags);
977 let size = self.intcast(size, self.type_size_t(), false);
978 let _is_volatile = flags.contains(MemFlags::VOLATILE);
979 let dst = self.pointercast(dst, self.type_i8p());
980 let src = self.pointercast(src, self.type_ptr_to(self.type_void()));
982 let memmove = self.context.get_builtin_function("memmove");
983 // TODO(antoyo): handle is_volatile.
984 self.block.add_eval(None, self.context.new_call(None, memmove, &[dst, src, size]));
987 fn memset(&mut self, ptr: RValue<'gcc>, fill_byte: RValue<'gcc>, size: RValue<'gcc>, _align: Align, flags: MemFlags) {
988 let _is_volatile = flags.contains(MemFlags::VOLATILE);
989 let ptr = self.pointercast(ptr, self.type_i8p());
990 let memset = self.context.get_builtin_function("memset");
991 // TODO(antoyo): handle align and is_volatile.
992 let fill_byte = self.context.new_cast(None, fill_byte, self.i32_type);
993 let size = self.intcast(size, self.type_size_t(), false);
994 self.block.add_eval(None, self.context.new_call(None, memset, &[ptr, fill_byte, size]));
997 fn select(&mut self, cond: RValue<'gcc>, then_val: RValue<'gcc>, mut else_val: RValue<'gcc>) -> RValue<'gcc> {
998 let func = self.current_func();
999 let variable = func.new_local(None, then_val.get_type(), "selectVar");
1000 let then_block = func.new_block("then");
1001 let else_block = func.new_block("else");
1002 let after_block = func.new_block("after");
1003 self.llbb().end_with_conditional(None, cond, then_block, else_block);
1005 then_block.add_assignment(None, variable, then_val);
1006 then_block.end_with_jump(None, after_block);
1008 if !then_val.get_type().is_compatible_with(else_val.get_type()) {
1009 else_val = self.context.new_cast(None, else_val, then_val.get_type());
1011 else_block.add_assignment(None, variable, else_val);
1012 else_block.end_with_jump(None, after_block);
1014 // NOTE: since jumps were added in a place rustc does not expect, the current block in the
1015 // state need to be updated.
1016 self.switch_to_block(after_block);
1018 variable.to_rvalue()
1022 fn va_arg(&mut self, _list: RValue<'gcc>, _ty: Type<'gcc>) -> RValue<'gcc> {
1026 fn extract_element(&mut self, _vec: RValue<'gcc>, _idx: RValue<'gcc>) -> RValue<'gcc> {
1030 fn vector_splat(&mut self, _num_elts: usize, _elt: RValue<'gcc>) -> RValue<'gcc> {
1034 fn extract_value(&mut self, aggregate_value: RValue<'gcc>, idx: u64) -> RValue<'gcc> {
1035 // FIXME(antoyo): it would be better if the API only called this on struct, not on arrays.
1036 assert_eq!(idx as usize as u64, idx);
1037 let value_type = aggregate_value.get_type();
1039 if value_type.dyncast_array().is_some() {
1040 let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from"));
1041 let element = self.context.new_array_access(None, aggregate_value, index);
1042 element.get_address(None)
1044 else if value_type.dyncast_vector().is_some() {
1047 else if let Some(pointer_type) = value_type.get_pointee() {
1048 if let Some(struct_type) = pointer_type.is_struct() {
1049 // NOTE: hack to workaround a limitation of the rustc API: see comment on
1050 // CodegenCx.structs_as_pointer
1051 aggregate_value.dereference_field(None, struct_type.get_field(idx as i32)).to_rvalue()
1054 panic!("Unexpected type {:?}", value_type);
1057 else if let Some(struct_type) = value_type.is_struct() {
1058 aggregate_value.access_field(None, struct_type.get_field(idx as i32)).to_rvalue()
1061 panic!("Unexpected type {:?}", value_type);
1065 fn insert_value(&mut self, aggregate_value: RValue<'gcc>, value: RValue<'gcc>, idx: u64) -> RValue<'gcc> {
1066 // FIXME(antoyo): it would be better if the API only called this on struct, not on arrays.
1067 assert_eq!(idx as usize as u64, idx);
1068 let value_type = aggregate_value.get_type();
1071 if value_type.dyncast_array().is_some() {
1072 let index = self.context.new_rvalue_from_long(self.u64_type, i64::try_from(idx).expect("i64::try_from"));
1073 self.context.new_array_access(None, aggregate_value, index)
1075 else if value_type.dyncast_vector().is_some() {
1078 else if let Some(pointer_type) = value_type.get_pointee() {
1079 if let Some(struct_type) = pointer_type.is_struct() {
1080 // NOTE: hack to workaround a limitation of the rustc API: see comment on
1081 // CodegenCx.structs_as_pointer
1082 aggregate_value.dereference_field(None, struct_type.get_field(idx as i32))
1085 panic!("Unexpected type {:?}", value_type);
1089 panic!("Unexpected type {:?}", value_type);
1092 let lvalue_type = lvalue.to_rvalue().get_type();
1094 // NOTE: sometimes, rustc will create a value with the wrong type.
1095 if lvalue_type != value.get_type() {
1096 self.context.new_cast(None, value, lvalue_type)
1102 self.llbb().add_assignment(None, lvalue, value);
1107 fn set_personality_fn(&mut self, _personality: RValue<'gcc>) {
1111 fn cleanup_landing_pad(&mut self, _ty: Type<'gcc>, _pers_fn: RValue<'gcc>) -> RValue<'gcc> {
1112 let field1 = self.context.new_field(None, self.u8_type.make_pointer(), "landing_pad_field_1");
1113 let field2 = self.context.new_field(None, self.i32_type, "landing_pad_field_1");
1114 let struct_type = self.context.new_struct_type(None, "landing_pad", &[field1, field2]);
1115 self.current_func().new_local(None, struct_type.as_type(), "landing_pad")
1117 // TODO(antoyo): Properly implement unwinding.
1118 // the above is just to make the compilation work as it seems
1119 // rustc_codegen_ssa now calls the unwinding builder methods even on panic=abort.
1122 fn resume(&mut self, _exn: RValue<'gcc>) {
1123 // TODO(bjorn3): Properly implement unwinding.
1127 fn cleanup_pad(&mut self, _parent: Option<RValue<'gcc>>, _args: &[RValue<'gcc>]) -> Funclet {
1131 fn cleanup_ret(&mut self, _funclet: &Funclet, _unwind: Option<Block<'gcc>>) {
1135 fn catch_pad(&mut self, _parent: RValue<'gcc>, _args: &[RValue<'gcc>]) -> Funclet {
1141 _parent: Option<RValue<'gcc>>,
1142 _unwind: Option<Block<'gcc>>,
1143 _handlers: &[Block<'gcc>],
1148 // Atomic Operations
1149 fn atomic_cmpxchg(&mut self, dst: RValue<'gcc>, cmp: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering, failure_order: AtomicOrdering, weak: bool) -> RValue<'gcc> {
1150 let expected = self.current_func().new_local(None, cmp.get_type(), "expected");
1151 self.llbb().add_assignment(None, expected, cmp);
1152 let success = self.compare_exchange(dst, expected, src, order, failure_order, weak);
1154 let pair_type = self.cx.type_struct(&[src.get_type(), self.bool_type], false);
1155 let result = self.current_func().new_local(None, pair_type, "atomic_cmpxchg_result");
1156 let align = Align::from_bits(64).expect("align"); // TODO(antoyo): use good align.
1158 let value_type = result.to_rvalue().get_type();
1159 if let Some(struct_type) = value_type.is_struct() {
1160 self.store(success, result.access_field(None, struct_type.get_field(1)).get_address(None), align);
1161 // NOTE: since success contains the call to the intrinsic, it must be stored before
1162 // expected so that we store expected after the call.
1163 self.store(expected.to_rvalue(), result.access_field(None, struct_type.get_field(0)).get_address(None), align);
1165 // TODO(antoyo): handle when value is not a struct.
1170 fn atomic_rmw(&mut self, op: AtomicRmwBinOp, dst: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering) -> RValue<'gcc> {
1171 let size = src.get_type().get_size();
1174 AtomicRmwBinOp::AtomicXchg => format!("__atomic_exchange_{}", size),
1175 AtomicRmwBinOp::AtomicAdd => format!("__atomic_fetch_add_{}", size),
1176 AtomicRmwBinOp::AtomicSub => format!("__atomic_fetch_sub_{}", size),
1177 AtomicRmwBinOp::AtomicAnd => format!("__atomic_fetch_and_{}", size),
1178 AtomicRmwBinOp::AtomicNand => format!("__atomic_fetch_nand_{}", size),
1179 AtomicRmwBinOp::AtomicOr => format!("__atomic_fetch_or_{}", size),
1180 AtomicRmwBinOp::AtomicXor => format!("__atomic_fetch_xor_{}", size),
1181 AtomicRmwBinOp::AtomicMax => return self.atomic_extremum(ExtremumOperation::Max, dst, src, order),
1182 AtomicRmwBinOp::AtomicMin => return self.atomic_extremum(ExtremumOperation::Min, dst, src, order),
1183 AtomicRmwBinOp::AtomicUMax => return self.atomic_extremum(ExtremumOperation::Max, dst, src, order),
1184 AtomicRmwBinOp::AtomicUMin => return self.atomic_extremum(ExtremumOperation::Min, dst, src, order),
1188 let atomic_function = self.context.get_builtin_function(name);
1189 let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
1191 let void_ptr_type = self.context.new_type::<*mut ()>();
1192 let volatile_void_ptr_type = void_ptr_type.make_volatile();
1193 let dst = self.context.new_cast(None, dst, volatile_void_ptr_type);
1194 // FIXME(antoyo): not sure why, but we have the wrong type here.
1195 let new_src_type = atomic_function.get_param(1).to_rvalue().get_type();
1196 let src = self.context.new_cast(None, src, new_src_type);
1197 let res = self.context.new_call(None, atomic_function, &[dst, src, order]);
1198 self.context.new_cast(None, res, src.get_type())
1201 fn atomic_fence(&mut self, order: AtomicOrdering, scope: SynchronizationScope) {
1204 SynchronizationScope::SingleThread => "__atomic_signal_fence",
1205 SynchronizationScope::CrossThread => "__atomic_thread_fence",
1207 let thread_fence = self.context.get_builtin_function(name);
1208 let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
1209 self.llbb().add_eval(None, self.context.new_call(None, thread_fence, &[order]));
1212 fn set_invariant_load(&mut self, load: RValue<'gcc>) {
1213 // NOTE: Hack to consider vtable function pointer as non-global-variable function pointer.
1214 self.normal_function_addresses.borrow_mut().insert(load);
1218 fn lifetime_start(&mut self, _ptr: RValue<'gcc>, _size: Size) {
1222 fn lifetime_end(&mut self, _ptr: RValue<'gcc>, _size: Size) {
1226 fn call(&mut self, _typ: Type<'gcc>, func: RValue<'gcc>, args: &[RValue<'gcc>], funclet: Option<&Funclet>) -> RValue<'gcc> {
1227 // FIXME(antoyo): remove when having a proper API.
1228 let gcc_func = unsafe { std::mem::transmute(func) };
1229 if self.functions.borrow().values().find(|value| **value == gcc_func).is_some() {
1230 self.function_call(func, args, funclet)
1233 // If it's a not function that was defined, it's a function pointer.
1234 self.function_ptr_call(func, args, funclet)
1238 fn zext(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>) -> RValue<'gcc> {
1239 // FIXME(antoyo): this does not zero-extend.
1240 if value.get_type().is_bool() && dest_typ.is_i8(&self.cx) {
1241 // FIXME(antoyo): hack because base::from_immediate converts i1 to i8.
1242 // Fix the code in codegen_ssa::base::from_immediate.
1245 self.gcc_int_cast(value, dest_typ)
1248 fn cx(&self) -> &CodegenCx<'gcc, 'tcx> {
1252 fn do_not_inline(&mut self, _llret: RValue<'gcc>) {
1253 // FIXME(bjorn3): implement
1256 fn set_span(&mut self, _span: Span) {}
1258 fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
1259 if self.cx().val_ty(val) == self.cx().type_i1() {
1260 self.zext(val, self.cx().type_i8())
1267 fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
1268 if scalar.is_bool() {
1269 return self.trunc(val, self.cx().type_i1());
1274 fn fptoui_sat(&mut self, _val: RValue<'gcc>, _dest_ty: Type<'gcc>) -> Option<RValue<'gcc>> {
1278 fn fptosi_sat(&mut self, _val: RValue<'gcc>, _dest_ty: Type<'gcc>) -> Option<RValue<'gcc>> {
1282 fn instrprof_increment(&mut self, _fn_name: RValue<'gcc>, _hash: RValue<'gcc>, _num_counters: RValue<'gcc>, _index: RValue<'gcc>) {
1287 impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
1288 #[cfg(feature="master")]
1289 pub fn shuffle_vector(&mut self, v1: RValue<'gcc>, v2: RValue<'gcc>, mask: RValue<'gcc>) -> RValue<'gcc> {
1290 let struct_type = mask.get_type().is_struct().expect("mask of struct type");
1292 // TODO(antoyo): use a recursive unqualified() here.
1293 let vector_type = v1.get_type().unqualified().dyncast_vector().expect("vector type");
1294 let element_type = vector_type.get_element_type();
1295 let vec_num_units = vector_type.get_num_units();
1297 let mask_num_units = struct_type.get_field_count();
1298 let mut vector_elements = vec![];
1299 let mask_element_type =
1300 if element_type.is_integral() {
1304 #[cfg(feature="master")]
1306 self.cx.type_ix(element_type.get_size() as u64 * 8)
1308 #[cfg(not(feature="master"))]
1311 for i in 0..mask_num_units {
1312 let field = struct_type.get_field(i as i32);
1313 vector_elements.push(self.context.new_cast(None, mask.access_field(None, field).to_rvalue(), mask_element_type));
1316 // NOTE: the mask needs to be the same length as the input vectors, so add the missing
1317 // elements in the mask if needed.
1318 for _ in mask_num_units..vec_num_units {
1319 vector_elements.push(self.context.new_rvalue_zero(mask_element_type));
1322 let array_type = self.context.new_array_type(None, element_type, vec_num_units as i32);
1323 let result_type = self.context.new_vector_type(element_type, mask_num_units as u64);
1325 if vec_num_units < mask_num_units {
1326 // NOTE: the mask needs to be the same length as the input vectors, so join the 2
1327 // vectors and create a dummy second vector.
1328 // TODO(antoyo): switch to using new_vector_access.
1329 let array = self.context.new_bitcast(None, v1, array_type);
1330 let mut elements = vec![];
1331 for i in 0..vec_num_units {
1332 elements.push(self.context.new_array_access(None, array, self.context.new_rvalue_from_int(self.int_type, i as i32)).to_rvalue());
1334 // TODO(antoyo): switch to using new_vector_access.
1335 let array = self.context.new_bitcast(None, v2, array_type);
1336 for i in 0..(mask_num_units - vec_num_units) {
1337 elements.push(self.context.new_array_access(None, array, self.context.new_rvalue_from_int(self.int_type, i as i32)).to_rvalue());
1339 let v1 = self.context.new_rvalue_from_vector(None, result_type, &elements);
1340 let zero = self.context.new_rvalue_zero(element_type);
1341 let v2 = self.context.new_rvalue_from_vector(None, result_type, &vec![zero; mask_num_units]);
1348 let new_mask_num_units = std::cmp::max(mask_num_units, vec_num_units);
1349 let mask_type = self.context.new_vector_type(mask_element_type, new_mask_num_units as u64);
1350 let mask = self.context.new_rvalue_from_vector(None, mask_type, &vector_elements);
1351 let result = self.context.new_rvalue_vector_perm(None, v1, v2, mask);
1353 if vec_num_units != mask_num_units {
1354 // NOTE: if padding was added, only select the number of elements of the masks to
1355 // remove that padding in the result.
1356 let mut elements = vec![];
1357 // TODO(antoyo): switch to using new_vector_access.
1358 let array = self.context.new_bitcast(None, result, array_type);
1359 for i in 0..mask_num_units {
1360 elements.push(self.context.new_array_access(None, array, self.context.new_rvalue_from_int(self.int_type, i as i32)).to_rvalue());
1362 self.context.new_rvalue_from_vector(None, result_type, &elements)
1369 #[cfg(not(feature="master"))]
1370 pub fn shuffle_vector(&mut self, _v1: RValue<'gcc>, _v2: RValue<'gcc>, _mask: RValue<'gcc>) -> RValue<'gcc> {
1374 #[cfg(feature="master")]
1375 pub fn vector_reduce<F>(&mut self, src: RValue<'gcc>, op: F) -> RValue<'gcc>
1376 where F: Fn(RValue<'gcc>, RValue<'gcc>, &'gcc Context<'gcc>) -> RValue<'gcc>
1378 let vector_type = src.get_type().unqualified().dyncast_vector().expect("vector type");
1379 let element_count = vector_type.get_num_units();
1380 let mut vector_elements = vec![];
1381 for i in 0..element_count {
1382 vector_elements.push(i);
1384 let mask_type = self.context.new_vector_type(self.int_type, element_count as u64);
1387 while shift < element_count {
1388 let vector_elements: Vec<_> =
1389 vector_elements.iter()
1390 .map(|i| self.context.new_rvalue_from_int(self.int_type, ((i + shift) % element_count) as i32))
1392 let mask = self.context.new_rvalue_from_vector(None, mask_type, &vector_elements);
1393 let shifted = self.context.new_rvalue_vector_perm(None, res, res, mask);
1395 res = op(res, shifted, &self.context);
1397 self.context.new_vector_access(None, res, self.context.new_rvalue_zero(self.int_type))
1401 #[cfg(not(feature="master"))]
1402 pub fn vector_reduce<F>(&mut self, src: RValue<'gcc>, op: F) -> RValue<'gcc>
1403 where F: Fn(RValue<'gcc>, RValue<'gcc>, &'gcc Context<'gcc>) -> RValue<'gcc>
1408 pub fn vector_reduce_op(&mut self, src: RValue<'gcc>, op: BinaryOp) -> RValue<'gcc> {
1409 self.vector_reduce(src, |a, b, context| context.new_binary_op(None, op, a.get_type(), a, b))
1412 pub fn vector_reduce_fadd_fast(&mut self, _acc: RValue<'gcc>, _src: RValue<'gcc>) -> RValue<'gcc> {
1416 pub fn vector_reduce_fmul_fast(&mut self, _acc: RValue<'gcc>, _src: RValue<'gcc>) -> RValue<'gcc> {
1420 // Inspired by Hacker's Delight min implementation.
1421 pub fn vector_reduce_min(&mut self, src: RValue<'gcc>) -> RValue<'gcc> {
1422 self.vector_reduce(src, |a, b, context| {
1423 let differences_or_zeros = difference_or_zero(a, b, context);
1424 context.new_binary_op(None, BinaryOp::Minus, a.get_type(), a, differences_or_zeros)
1428 // Inspired by Hacker's Delight max implementation.
1429 pub fn vector_reduce_max(&mut self, src: RValue<'gcc>) -> RValue<'gcc> {
1430 self.vector_reduce(src, |a, b, context| {
1431 let differences_or_zeros = difference_or_zero(a, b, context);
1432 context.new_binary_op(None, BinaryOp::Plus, b.get_type(), b, differences_or_zeros)
1436 pub fn vector_select(&mut self, cond: RValue<'gcc>, then_val: RValue<'gcc>, else_val: RValue<'gcc>) -> RValue<'gcc> {
1437 // cond is a vector of integers, not of bools.
1438 let cond_type = cond.get_type();
1439 let vector_type = cond_type.unqualified().dyncast_vector().expect("vector type");
1440 let num_units = vector_type.get_num_units();
1441 let element_type = vector_type.get_element_type();
1442 let zeros = vec![self.context.new_rvalue_zero(element_type); num_units];
1443 let zeros = self.context.new_rvalue_from_vector(None, cond_type, &zeros);
1445 let masks = self.context.new_comparison(None, ComparisonOp::NotEquals, cond, zeros);
1446 let then_vals = masks & then_val;
1448 let ones = vec![self.context.new_rvalue_one(element_type); num_units];
1449 let ones = self.context.new_rvalue_from_vector(None, cond_type, &ones);
1450 let inverted_masks = masks + ones;
1451 // NOTE: sometimes, the type of else_val can be different than the type of then_val in
1452 // libgccjit (vector of int vs vector of int32_t), but they should be the same for the AND
1453 // operation to work.
1454 let else_val = self.context.new_bitcast(None, else_val, then_val.get_type());
1455 let else_vals = inverted_masks & else_val;
1457 then_vals | else_vals
1461 fn difference_or_zero<'gcc>(a: RValue<'gcc>, b: RValue<'gcc>, context: &'gcc Context<'gcc>) -> RValue<'gcc> {
1462 let difference = a - b;
1463 let masks = context.new_comparison(None, ComparisonOp::GreaterThanEquals, b, a);
1467 impl<'a, 'gcc, 'tcx> StaticBuilderMethods for Builder<'a, 'gcc, 'tcx> {
1468 fn get_static(&mut self, def_id: DefId) -> RValue<'gcc> {
1469 // Forward to the `get_static` method of `CodegenCx`
1470 self.cx().get_static(def_id).get_address(None)
1474 impl<'tcx> HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
1475 fn param_env(&self) -> ParamEnv<'tcx> {
1480 impl<'tcx> HasTargetSpec for Builder<'_, '_, 'tcx> {
1481 fn target_spec(&self) -> &Target {
1482 &self.cx.target_spec()
1486 pub trait ToGccComp {
1487 fn to_gcc_comparison(&self) -> ComparisonOp;
1490 impl ToGccComp for IntPredicate {
1491 fn to_gcc_comparison(&self) -> ComparisonOp {
1493 IntPredicate::IntEQ => ComparisonOp::Equals,
1494 IntPredicate::IntNE => ComparisonOp::NotEquals,
1495 IntPredicate::IntUGT => ComparisonOp::GreaterThan,
1496 IntPredicate::IntUGE => ComparisonOp::GreaterThanEquals,
1497 IntPredicate::IntULT => ComparisonOp::LessThan,
1498 IntPredicate::IntULE => ComparisonOp::LessThanEquals,
1499 IntPredicate::IntSGT => ComparisonOp::GreaterThan,
1500 IntPredicate::IntSGE => ComparisonOp::GreaterThanEquals,
1501 IntPredicate::IntSLT => ComparisonOp::LessThan,
1502 IntPredicate::IntSLE => ComparisonOp::LessThanEquals,
1507 impl ToGccComp for RealPredicate {
1508 fn to_gcc_comparison(&self) -> ComparisonOp {
1509 // TODO(antoyo): check that ordered vs non-ordered is respected.
1511 RealPredicate::RealPredicateFalse => unreachable!(),
1512 RealPredicate::RealOEQ => ComparisonOp::Equals,
1513 RealPredicate::RealOGT => ComparisonOp::GreaterThan,
1514 RealPredicate::RealOGE => ComparisonOp::GreaterThanEquals,
1515 RealPredicate::RealOLT => ComparisonOp::LessThan,
1516 RealPredicate::RealOLE => ComparisonOp::LessThanEquals,
1517 RealPredicate::RealONE => ComparisonOp::NotEquals,
1518 RealPredicate::RealORD => unreachable!(),
1519 RealPredicate::RealUNO => unreachable!(),
1520 RealPredicate::RealUEQ => ComparisonOp::Equals,
1521 RealPredicate::RealUGT => ComparisonOp::GreaterThan,
1522 RealPredicate::RealUGE => ComparisonOp::GreaterThan,
1523 RealPredicate::RealULT => ComparisonOp::LessThan,
1524 RealPredicate::RealULE => ComparisonOp::LessThan,
1525 RealPredicate::RealUNE => ComparisonOp::NotEquals,
1526 RealPredicate::RealPredicateTrue => unreachable!(),
1532 #[allow(non_camel_case_types)]
1542 trait ToGccOrdering {
1543 fn to_gcc(self) -> i32;
1546 impl ToGccOrdering for AtomicOrdering {
1547 fn to_gcc(self) -> i32 {
1552 AtomicOrdering::Unordered => __ATOMIC_RELAXED,
1553 AtomicOrdering::Relaxed => __ATOMIC_RELAXED, // TODO(antoyo): check if that's the same.
1554 AtomicOrdering::Acquire => __ATOMIC_ACQUIRE,
1555 AtomicOrdering::Release => __ATOMIC_RELEASE,
1556 AtomicOrdering::AcquireRelease => __ATOMIC_ACQ_REL,
1557 AtomicOrdering::SequentiallyConsistent => __ATOMIC_SEQ_CST,