3 use rustc_target::spec::{HasTargetSpec, Target};
5 use cranelift_module::Module;
9 pub fn mir_var(loc: Local) -> Variable {
10 Variable::with_u32(loc.index() as u32)
13 pub fn pointer_ty(tcx: TyCtxt) -> types::Type {
14 match tcx.data_layout.pointer_size.bits() {
18 bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
22 fn scalar_to_clif_type(tcx: TyCtxt, scalar: &Scalar) -> Type {
23 match scalar.value.size(&tcx).bits() {
28 size => bug!("Unsupported scalar size {}", size),
32 pub fn clif_type_from_ty<'a, 'tcx: 'a>(
33 tcx: TyCtxt<'a, 'tcx, 'tcx>,
35 ) -> Option<types::Type> {
37 ty::Bool => types::I8,
38 ty::Uint(size) => match size {
39 UintTy::U8 => types::I8,
40 UintTy::U16 => types::I16,
41 UintTy::U32 => types::I32,
42 UintTy::U64 => types::I64,
43 UintTy::U128 => unimpl!("u128"),
44 UintTy::Usize => pointer_ty(tcx),
46 ty::Int(size) => match size {
47 IntTy::I8 => types::I8,
48 IntTy::I16 => types::I16,
49 IntTy::I32 => types::I32,
50 IntTy::I64 => types::I64,
51 IntTy::I128 => unimpl!("i128"),
52 IntTy::Isize => pointer_ty(tcx),
54 ty::Char => types::I32,
55 ty::Float(size) => match size {
56 FloatTy::F32 => types::F32,
57 FloatTy::F64 => types::F64,
59 ty::FnPtr(_) => pointer_ty(tcx),
60 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) | ty::Ref(_, ty, _) => {
61 if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
67 ty::Param(_) => bug!("{:?}: {:?}", ty, ty.sty),
72 pub fn codegen_select(bcx: &mut FunctionBuilder, cond: Value, lhs: Value, rhs: Value) -> Value {
73 let lhs_ty = bcx.func.dfg.value_type(lhs);
74 let rhs_ty = bcx.func.dfg.value_type(rhs);
75 assert_eq!(lhs_ty, rhs_ty);
76 if lhs_ty == types::I8 || lhs_ty == types::I16 {
77 // FIXME workaround for missing enocding for select.i8
78 let lhs = bcx.ins().uextend(types::I32, lhs);
79 let rhs = bcx.ins().uextend(types::I32, rhs);
80 let res = bcx.ins().select(cond, lhs, rhs);
81 bcx.ins().ireduce(lhs_ty, res)
83 bcx.ins().select(cond, lhs, rhs)
87 fn codegen_field<'a, 'tcx: 'a>(
88 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
90 layout: TyLayout<'tcx>,
92 ) -> (Value, TyLayout<'tcx>) {
93 let field_offset = layout.fields.offset(field.index());
94 let field_ty = layout.field(&*fx, field.index());
95 if field_offset.bytes() > 0 {
97 fx.bcx.ins().iadd_imm(base, field_offset.bytes() as i64),
105 /// A read-only value
106 #[derive(Debug, Copy, Clone)]
107 pub enum CValue<'tcx> {
108 ByRef(Value, TyLayout<'tcx>),
109 ByVal(Value, TyLayout<'tcx>),
110 ByValPair(Value, Value, TyLayout<'tcx>),
113 impl<'tcx> CValue<'tcx> {
114 pub fn layout(&self) -> TyLayout<'tcx> {
116 CValue::ByRef(_, layout)
117 | CValue::ByVal(_, layout)
118 | CValue::ByValPair(_, _, layout) => layout,
122 pub fn force_stack<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
127 CValue::ByRef(value, _layout) => value,
128 CValue::ByVal(value, layout) => {
129 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
130 kind: StackSlotKind::ExplicitSlot,
131 size: layout.size.bytes() as u32,
134 let addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
135 fx.bcx.ins().store(MemFlags::new(), value, addr, 0);
138 CValue::ByValPair(value, extra, layout) => {
139 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
140 kind: StackSlotKind::ExplicitSlot,
141 size: layout.size.bytes() as u32,
144 let base = fx.bcx.ins().stack_addr(types::I64, stack_slot, 0);
145 let a_addr = codegen_field(fx, base, layout, mir::Field::new(0)).0;
146 let b_addr = codegen_field(fx, base, layout, mir::Field::new(1)).0;
147 fx.bcx.ins().store(MemFlags::new(), value, a_addr, 0);
148 fx.bcx.ins().store(MemFlags::new(), extra, b_addr, 0);
154 /// Load a value with layout.abi of scalar
155 pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
160 CValue::ByRef(addr, layout) => {
161 let scalar = match layout.abi {
162 layout::Abi::Scalar(ref scalar) => scalar.clone(),
165 let clif_ty = crate::abi::scalar_to_clif_type(fx.tcx, scalar);
166 fx.bcx.ins().load(clif_ty, MemFlags::new(), addr, 0)
168 CValue::ByVal(value, _layout) => value,
169 CValue::ByValPair(_, _, _layout) => bug!("Please use load_value_pair for ByValPair"),
173 pub fn load_value_pair<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> (Value, Value)
178 CValue::ByRef(addr, layout) => {
181 fx.tcx.data_layout.pointer_size.bytes() * 2
183 let val1_offset = layout.fields.offset(0).bytes() as i32;
184 let val2_offset = layout.fields.offset(1).bytes() as i32;
188 .load(fx.pointer_type, MemFlags::new(), addr, val1_offset);
192 .load(fx.pointer_type, MemFlags::new(), addr, val2_offset);
195 CValue::ByVal(_, _layout) => bug!("Please use load_value for ByVal"),
196 CValue::ByValPair(val1, val2, _layout) => (val1, val2),
200 pub fn value_field<'a>(
202 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
208 let (base, layout) = match self {
209 CValue::ByRef(addr, layout) => (addr, layout),
210 _ => bug!("place_field for {:?}", self),
213 let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
214 CValue::ByRef(field_ptr, field_layout)
217 pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
218 crate::unsize::coerce_unsized_into(fx, self, dest);
221 pub fn const_val<'a>(
222 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
229 let clif_ty = fx.clif_type(ty).unwrap();
230 let layout = fx.layout_of(ty);
231 CValue::ByVal(fx.bcx.ins().iconst(clif_ty, const_val), layout)
234 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
236 CValue::ByRef(addr, _) => CValue::ByRef(addr, layout),
237 CValue::ByVal(val, _) => CValue::ByVal(val, layout),
238 CValue::ByValPair(val, extra, _) => CValue::ByValPair(val, extra, layout),
243 /// A place where you can write a value to or read a value from
244 #[derive(Debug, Copy, Clone)]
245 pub enum CPlace<'tcx> {
246 Var(Local, TyLayout<'tcx>),
247 Addr(Value, Option<Value>, TyLayout<'tcx>),
248 Stack(StackSlot, TyLayout<'tcx>),
249 NoPlace(TyLayout<'tcx>)
252 impl<'a, 'tcx: 'a> CPlace<'tcx> {
253 pub fn layout(&self) -> TyLayout<'tcx> {
255 CPlace::Var(_, layout)
256 | CPlace::Addr(_, _, layout)
257 | CPlace::Stack(_, layout)
258 | CPlace::NoPlace(layout) => layout,
262 pub fn new_stack_slot(fx: &mut FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> CPlace<'tcx> {
263 let layout = fx.layout_of(ty);
264 assert!(!layout.is_unsized());
265 if layout.size.bytes() == 0 {
266 return CPlace::NoPlace(layout);
269 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
270 kind: StackSlotKind::ExplicitSlot,
271 size: layout.size.bytes() as u32,
274 CPlace::Stack(stack_slot, layout)
277 pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CValue<'tcx> {
279 CPlace::Var(var, layout) => CValue::ByVal(fx.bcx.use_var(mir_var(var)), layout),
280 CPlace::Addr(addr, extra, layout) => {
281 assert!(extra.is_none(), "unsized values are not yet supported");
282 CValue::ByRef(addr, layout)
284 CPlace::Stack(stack_slot, layout) => {
285 CValue::ByRef(fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0), layout)
287 CPlace::NoPlace(layout) => {
288 CValue::ByRef(fx.bcx.ins().iconst(fx.pointer_type, 0), layout)
293 pub fn to_addr(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value {
294 match self.to_addr_maybe_unsized(fx) {
295 (addr, None) => addr,
296 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
300 pub fn to_addr_maybe_unsized(
302 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
303 ) -> (Value, Option<Value>) {
305 CPlace::Addr(addr, extra, _layout) => (addr, extra),
306 CPlace::Stack(stack_slot, _layout) => {
307 (fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0), None)
309 CPlace::NoPlace(_) => (fx.bcx.ins().iconst(fx.pointer_type, 0), None),
310 CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
314 pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, from: CValue<'tcx>) {
315 let from_ty = from.layout().ty;
316 let to_ty = self.layout().ty;
317 match (&from_ty.sty, &to_ty.sty) {
318 (ty::Ref(_, t, src_mut), ty::Ref(_, u, dest_mut))
319 if (if *dest_mut != crate::rustc::hir::Mutability::MutImmutable
320 && src_mut != dest_mut
329 // &mut T -> &T is allowed
330 // &'a T -> &'b T is allowed
332 (ty::FnPtr(_), ty::FnPtr(_)) => {
333 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
334 ParamEnv::reveal_all(),
335 &from_ty.fn_sig(fx.tcx),
337 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
338 ParamEnv::reveal_all(),
339 &to_ty.fn_sig(fx.tcx),
343 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
344 from_sig, to_sig, fx,
346 // fn(&T) -> for<'l> fn(&'l T) is allowed
352 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
360 let (addr, dst_layout) = match self {
361 CPlace::Var(var, _) => {
362 let data = from.load_scalar(fx);
363 fx.bcx.def_var(mir_var(var), data);
366 CPlace::Addr(addr, None, dst_layout) => (addr, dst_layout),
367 CPlace::Stack(stack_slot, dst_layout) => {
368 (fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0), dst_layout)
370 CPlace::NoPlace(layout) => {
371 assert!(layout.size.bytes() == 0);
372 assert!(from.layout().size.bytes() == 0);
375 CPlace::Addr(_, _, _) => bug!("Can't write value to unsized place {:?}", self),
379 CValue::ByVal(val, _src_layout) => {
380 fx.bcx.ins().store(MemFlags::new(), val, addr, 0);
382 CValue::ByValPair(val1, val2, _src_layout) => {
383 let val1_offset = dst_layout.fields.offset(0).bytes() as i32;
384 let val2_offset = dst_layout.fields.offset(1).bytes() as i32;
385 fx.bcx.ins().store(MemFlags::new(), val1, addr, val1_offset);
386 fx.bcx.ins().store(MemFlags::new(), val2, addr, val2_offset);
388 CValue::ByRef(from, src_layout) => {
389 let size = dst_layout.size.bytes();
390 let src_align = src_layout.align.abi.bytes() as u8;
391 let dst_align = dst_layout.align.abi.bytes() as u8;
392 fx.bcx.emit_small_memcpy(fx.module.target_config(), addr, from, size, dst_align, src_align);
399 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
402 let layout = self.layout();
403 let (base, extra) = self.to_addr_maybe_unsized(fx);
405 let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
406 let extra = if field_layout.is_unsized() {
407 assert!(extra.is_some());
412 CPlace::Addr(field_ptr, extra, field_layout)
417 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
420 let (elem_layout, addr) = match self.layout().ty.sty {
421 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_addr(fx)),
422 ty::Slice(elem_ty) => (
423 fx.layout_of(elem_ty),
424 self.to_addr_maybe_unsized(fx).0,
426 _ => bug!("place_index({:?})", self.layout().ty),
432 .imul_imm(index, elem_layout.size.bytes() as i64);
434 CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
437 pub fn place_deref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CPlace<'tcx> {
438 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
439 if !inner_layout.is_unsized() {
440 CPlace::Addr(self.to_cvalue(fx).load_scalar(fx), None, inner_layout)
442 match self.layout().abi {
443 Abi::ScalarPair(ref a, ref b) => {
444 let addr = self.to_addr(fx);
448 .load(scalar_to_clif_type(fx.tcx, a), MemFlags::new(), addr, 0);
449 let extra = fx.bcx.ins().load(
450 scalar_to_clif_type(fx.tcx, b),
453 a.value.size(&fx.tcx).bytes() as u32 as i32,
455 CPlace::Addr(ptr, Some(extra), inner_layout)
458 "Fat ptr doesn't have abi ScalarPair, but it has {:?}",
465 pub fn write_place_ref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
466 if !self.layout().is_unsized() {
467 let ptr = CValue::ByVal(self.to_addr(fx), dest.layout());
468 dest.write_cvalue(fx, ptr);
470 let (value, extra) = self.to_addr_maybe_unsized(fx);
472 match dest.layout().abi {
473 Abi::ScalarPair(ref a, _) => {
474 let dest_addr = dest.to_addr(fx);
477 .store(MemFlags::new(), value, dest_addr, 0);
480 extra.expect("unsized type without metadata"),
482 a.value.size(&fx.tcx).bytes() as u32 as i32,
486 "Non ScalarPair abi {:?} in write_place_ref dest",
493 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
494 assert!(!self.layout().is_unsized());
496 CPlace::Var(var, _) => CPlace::Var(var, layout),
497 CPlace::Addr(addr, extra, _) => {
498 CPlace::Addr(addr, extra, layout)
500 CPlace::Stack(stack_slot, _) => {
501 CPlace::Stack(stack_slot, layout)
503 CPlace::NoPlace(_) => {
504 assert!(layout.size.bytes() == 0);
505 CPlace::NoPlace(layout)
510 pub fn downcast_variant(
512 fx: &FunctionCx<'a, 'tcx, impl Backend>,
515 let layout = self.layout().for_variant(fx, variant);
516 self.unchecked_cast_to(layout)
520 pub fn clif_intcast<'a, 'tcx: 'a>(
521 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
526 let from = fx.bcx.func.dfg.value_type(val);
530 if to.wider_or_equal(from) {
532 fx.bcx.ins().sextend(to, val)
534 fx.bcx.ins().uextend(to, val)
537 fx.bcx.ins().ireduce(to, val)
541 pub struct FunctionCx<'a, 'tcx: 'a, B: Backend> {
542 // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
543 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
544 pub module: &'a mut Module<B>,
545 pub pointer_type: Type, // Cached from module
547 pub instance: Instance<'tcx>,
548 pub mir: &'tcx Mir<'tcx>,
550 pub bcx: FunctionBuilder<'a>,
551 pub ebb_map: HashMap<BasicBlock, Ebb>,
552 pub local_map: HashMap<Local, CPlace<'tcx>>,
554 pub clif_comments: crate::pretty_clif::CommentWriter,
555 pub constants: &'a mut crate::constant::ConstantCx,
556 pub caches: &'a mut Caches<'tcx>,
557 pub source_info_set: indexmap::IndexSet<SourceInfo>,
560 impl<'a, 'tcx: 'a, B: Backend + 'a> fmt::Debug for FunctionCx<'a, 'tcx, B> {
561 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562 writeln!(f, "{:?}", self.instance.substs)?;
563 writeln!(f, "{:?}", self.local_map)?;
565 let mut clif = String::new();
566 ::cranelift::codegen::write::decorate_function(
567 &mut &self.clif_comments,
573 writeln!(f, "\n{}", clif)
577 impl<'a, 'tcx: 'a, B: Backend> LayoutOf for FunctionCx<'a, 'tcx, B> {
579 type TyLayout = TyLayout<'tcx>;
581 fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
582 let ty = self.monomorphize(&ty);
583 self.tcx.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap()
587 impl<'a, 'tcx, B: Backend + 'a> layout::HasTyCtxt<'tcx> for FunctionCx<'a, 'tcx, B> {
588 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
593 impl<'a, 'tcx, B: Backend + 'a> layout::HasDataLayout for FunctionCx<'a, 'tcx, B> {
594 fn data_layout(&self) -> &layout::TargetDataLayout {
595 &self.tcx.data_layout
599 impl<'a, 'tcx, B: Backend + 'a> HasTargetSpec for FunctionCx<'a, 'tcx, B> {
600 fn target_spec(&self) -> &Target {
601 &self.tcx.sess.target.target
605 impl<'a, 'tcx, B: Backend> BackendTypes for FunctionCx<'a, 'tcx, B> {
607 type BasicBlock = Ebb;
613 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
614 pub fn monomorphize<T>(&self, value: &T) -> T
616 T: TypeFoldable<'tcx>,
618 self.tcx.subst_and_normalize_erasing_regions(
619 self.instance.substs,
620 ty::ParamEnv::reveal_all(),
625 pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
626 clif_type_from_ty(self.tcx, self.monomorphize(&ty))
629 pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
630 *self.ebb_map.get(&bb).unwrap()
633 pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
634 *self.local_map.get(&local).unwrap()
637 pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
638 let (index, _) = self.source_info_set.insert_full(source_info);
639 self.bcx.set_srcloc(SourceLoc::new(index as u32));