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(
263 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
266 let layout = fx.layout_of(ty);
267 assert!(!layout.is_unsized());
268 if layout.size.bytes() == 0 {
269 return CPlace::NoPlace(layout);
272 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
273 kind: StackSlotKind::ExplicitSlot,
274 size: layout.size.bytes() as u32,
277 CPlace::Stack(stack_slot, layout)
280 pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CValue<'tcx> {
282 CPlace::Var(var, layout) => CValue::ByVal(fx.bcx.use_var(mir_var(var)), layout),
283 CPlace::Addr(addr, extra, layout) => {
284 assert!(extra.is_none(), "unsized values are not yet supported");
285 CValue::ByRef(addr, layout)
287 CPlace::Stack(stack_slot, layout) => CValue::ByRef(
288 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
291 CPlace::NoPlace(layout) => CValue::ByRef(
294 .iconst(fx.pointer_type, fx.pointer_type.bytes() as i64),
300 pub fn to_addr(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value {
301 match self.to_addr_maybe_unsized(fx) {
302 (addr, None) => addr,
303 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
307 pub fn to_addr_maybe_unsized(
309 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
310 ) -> (Value, Option<Value>) {
312 CPlace::Addr(addr, extra, _layout) => (addr, extra),
313 CPlace::Stack(stack_slot, _layout) => (
314 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
317 CPlace::NoPlace(_) => (fx.bcx.ins().iconst(fx.pointer_type, 45), None),
318 CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
322 pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, from: CValue<'tcx>) {
323 let from_ty = from.layout().ty;
324 let to_ty = self.layout().ty;
325 match (&from_ty.sty, &to_ty.sty) {
326 (ty::Ref(_, t, src_mut), ty::Ref(_, u, dest_mut))
327 if (if *dest_mut != crate::rustc::hir::Mutability::MutImmutable
328 && src_mut != dest_mut
337 // &mut T -> &T is allowed
338 // &'a T -> &'b T is allowed
340 (ty::FnPtr(_), ty::FnPtr(_)) => {
341 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
342 ParamEnv::reveal_all(),
343 &from_ty.fn_sig(fx.tcx),
345 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
346 ParamEnv::reveal_all(),
347 &to_ty.fn_sig(fx.tcx),
351 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
352 from_sig, to_sig, fx,
354 // fn(&T) -> for<'l> fn(&'l T) is allowed
360 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
368 let (addr, dst_layout) = match self {
369 CPlace::Var(var, _) => {
370 let data = from.load_scalar(fx);
371 fx.bcx.def_var(mir_var(var), data);
374 CPlace::Addr(addr, None, dst_layout) => (addr, dst_layout),
375 CPlace::Stack(stack_slot, dst_layout) => (
376 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
379 CPlace::NoPlace(layout) => {
380 assert!(layout.size.bytes() == 0);
381 assert!(from.layout().size.bytes() == 0);
384 CPlace::Addr(_, _, _) => bug!("Can't write value to unsized place {:?}", self),
388 CValue::ByVal(val, _src_layout) => {
389 fx.bcx.ins().store(MemFlags::new(), val, addr, 0);
391 CValue::ByValPair(val1, val2, _src_layout) => {
392 let val1_offset = dst_layout.fields.offset(0).bytes() as i32;
393 let val2_offset = dst_layout.fields.offset(1).bytes() as i32;
394 fx.bcx.ins().store(MemFlags::new(), val1, addr, val1_offset);
395 fx.bcx.ins().store(MemFlags::new(), val2, addr, val2_offset);
397 CValue::ByRef(from, src_layout) => {
398 let size = dst_layout.size.bytes();
399 let src_align = src_layout.align.abi.bytes() as u8;
400 let dst_align = dst_layout.align.abi.bytes() as u8;
401 fx.bcx.emit_small_memcpy(
402 fx.module.target_config(),
415 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
418 let layout = self.layout();
419 let (base, extra) = self.to_addr_maybe_unsized(fx);
421 let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
422 let extra = if field_layout.is_unsized() {
423 assert!(extra.is_some());
428 CPlace::Addr(field_ptr, extra, field_layout)
433 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
436 let (elem_layout, addr) = match self.layout().ty.sty {
437 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_addr(fx)),
438 ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_addr_maybe_unsized(fx).0),
439 _ => bug!("place_index({:?})", self.layout().ty),
445 .imul_imm(index, elem_layout.size.bytes() as i64);
447 CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
450 pub fn place_deref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CPlace<'tcx> {
451 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
452 if !inner_layout.is_unsized() {
453 CPlace::Addr(self.to_cvalue(fx).load_scalar(fx), None, inner_layout)
455 match self.layout().abi {
456 Abi::ScalarPair(ref a, ref b) => {
457 let addr = self.to_addr(fx);
461 .load(scalar_to_clif_type(fx.tcx, a), MemFlags::new(), addr, 0);
462 let extra = fx.bcx.ins().load(
463 scalar_to_clif_type(fx.tcx, b),
466 a.value.size(&fx.tcx).bytes() as u32 as i32,
468 CPlace::Addr(ptr, Some(extra), inner_layout)
471 "Fat ptr doesn't have abi ScalarPair, but it has {:?}",
478 pub fn write_place_ref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
479 if !self.layout().is_unsized() {
480 let ptr = CValue::ByVal(self.to_addr(fx), dest.layout());
481 dest.write_cvalue(fx, ptr);
483 let (value, extra) = self.to_addr_maybe_unsized(fx);
485 match dest.layout().abi {
486 Abi::ScalarPair(ref a, _) => {
487 let dest_addr = dest.to_addr(fx);
488 fx.bcx.ins().store(MemFlags::new(), value, dest_addr, 0);
491 extra.expect("unsized type without metadata"),
493 a.value.size(&fx.tcx).bytes() as u32 as i32,
497 "Non ScalarPair abi {:?} in write_place_ref dest",
504 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
505 assert!(!self.layout().is_unsized());
507 CPlace::Var(var, _) => CPlace::Var(var, layout),
508 CPlace::Addr(addr, extra, _) => CPlace::Addr(addr, extra, layout),
509 CPlace::Stack(stack_slot, _) => CPlace::Stack(stack_slot, layout),
510 CPlace::NoPlace(_) => {
511 assert!(layout.size.bytes() == 0);
512 CPlace::NoPlace(layout)
517 pub fn downcast_variant(
519 fx: &FunctionCx<'a, 'tcx, impl Backend>,
522 let layout = self.layout().for_variant(fx, variant);
523 self.unchecked_cast_to(layout)
527 pub fn clif_intcast<'a, 'tcx: 'a>(
528 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
533 let from = fx.bcx.func.dfg.value_type(val);
537 if to.wider_or_equal(from) {
539 fx.bcx.ins().sextend(to, val)
541 fx.bcx.ins().uextend(to, val)
544 fx.bcx.ins().ireduce(to, val)
548 pub struct FunctionCx<'a, 'tcx: 'a, B: Backend> {
549 // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
550 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
551 pub module: &'a mut Module<B>,
552 pub pointer_type: Type, // Cached from module
554 pub instance: Instance<'tcx>,
555 pub mir: &'tcx Mir<'tcx>,
557 pub bcx: FunctionBuilder<'a>,
558 pub ebb_map: HashMap<BasicBlock, Ebb>,
559 pub local_map: HashMap<Local, CPlace<'tcx>>,
561 pub clif_comments: crate::pretty_clif::CommentWriter,
562 pub constants: &'a mut crate::constant::ConstantCx,
563 pub caches: &'a mut Caches<'tcx>,
564 pub source_info_set: indexmap::IndexSet<SourceInfo>,
567 impl<'a, 'tcx: 'a, B: Backend + 'a> fmt::Debug for FunctionCx<'a, 'tcx, B> {
568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569 writeln!(f, "{:?}", self.instance.substs)?;
570 writeln!(f, "{:?}", self.local_map)?;
572 let mut clif = String::new();
573 ::cranelift::codegen::write::decorate_function(
574 &mut &self.clif_comments,
580 writeln!(f, "\n{}", clif)
584 impl<'a, 'tcx: 'a, B: Backend> LayoutOf for FunctionCx<'a, 'tcx, B> {
586 type TyLayout = TyLayout<'tcx>;
588 fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
589 let ty = self.monomorphize(&ty);
590 self.tcx.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap()
594 impl<'a, 'tcx, B: Backend + 'a> layout::HasTyCtxt<'tcx> for FunctionCx<'a, 'tcx, B> {
595 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
600 impl<'a, 'tcx, B: Backend + 'a> layout::HasDataLayout for FunctionCx<'a, 'tcx, B> {
601 fn data_layout(&self) -> &layout::TargetDataLayout {
602 &self.tcx.data_layout
606 impl<'a, 'tcx, B: Backend + 'a> HasTargetSpec for FunctionCx<'a, 'tcx, B> {
607 fn target_spec(&self) -> &Target {
608 &self.tcx.sess.target.target
612 impl<'a, 'tcx, B: Backend> BackendTypes for FunctionCx<'a, 'tcx, B> {
614 type BasicBlock = Ebb;
620 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
621 pub fn monomorphize<T>(&self, value: &T) -> T
623 T: TypeFoldable<'tcx>,
625 self.tcx.subst_and_normalize_erasing_regions(
626 self.instance.substs,
627 ty::ParamEnv::reveal_all(),
632 pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
633 clif_type_from_ty(self.tcx, self.monomorphize(&ty))
636 pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
637 *self.ebb_map.get(&bb).unwrap()
640 pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
641 *self.local_map.get(&local).unwrap()
644 pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
645 let (index, _) = self.source_info_set.insert_full(source_info);
646 self.bcx.set_srcloc(SourceLoc::new(index as u32));