1 use rustc::ty::adjustment::PointerCast;
5 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
6 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7 instance: Instance<'tcx>,
12 let mir = *tcx.instance_mir(instance.def);
15 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17 let mut debug_context = cx
20 .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
22 // Make FunctionBuilder
23 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24 func.collect_debug_info();
25 let mut func_ctx = FunctionBuilderContext::new();
26 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
29 let start_ebb = bcx.create_ebb();
30 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
31 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
32 ebb_map.insert(bb, bcx.create_ebb());
36 let pointer_type = cx.module.target_config().pointer_type();
37 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
39 let mut fx = FunctionCx {
49 local_map: HashMap::new(),
52 constants_cx: &mut cx.constants_cx,
53 caches: &mut cx.caches,
54 source_info_set: indexmap::IndexSet::new(),
57 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58 codegen_fn_content(&mut fx);
60 // Recover all necessary data from fx, before accessing func will prevent future access to it.
61 let instance = fx.instance;
62 let clif_comments = fx.clif_comments;
63 let source_info_set = fx.source_info_set;
64 let local_map = fx.local_map;
66 #[cfg(debug_assertions)]
67 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
70 verify_func(tcx, &clif_comments, &func);
73 let context = &mut cx.caches.context;
75 cx.module.define_function(func_id, context).unwrap();
77 // Write optimized function to file for debugging
78 #[cfg(debug_assertions)]
80 let value_ranges = context
81 .build_value_labels_ranges(cx.module.isa())
82 .expect("value location ranges");
84 crate::pretty_clif::write_clif_file(
94 // Define debuginfo for function
95 let isa = cx.module.isa();
98 .map(|x| x.define(context, isa, &source_info_set, local_map));
100 // Clear context to make it usable for the next function
104 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
105 let flags = settings::Flags::new(settings::builder());
106 match ::cranelift::codegen::verify_function(&func, &flags) {
109 tcx.sess.err(&format!("{:?}", err));
110 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
113 Some(Box::new(writer)),
117 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
122 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
123 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
124 if bb_data.is_cleanup {
125 // Unwinding after panicking is not supported
129 let ebb = fx.get_ebb(bb);
130 fx.bcx.switch_to_block(ebb);
133 for stmt in &bb_data.statements {
134 fx.set_debug_loc(stmt.source_info);
135 trans_stmt(fx, ebb, stmt);
138 #[cfg(debug_assertions)]
140 let mut terminator_head = "\n".to_string();
144 .fmt_head(&mut terminator_head)
146 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
147 fx.add_comment(inst, terminator_head);
150 fx.set_debug_loc(bb_data.terminator().source_info);
152 match &bb_data.terminator().kind {
153 TerminatorKind::Goto { target } => {
154 let ebb = fx.get_ebb(*target);
155 fx.bcx.ins().jump(ebb, &[]);
157 TerminatorKind::Return => {
158 crate::abi::codegen_return(fx);
160 TerminatorKind::Assert {
167 if !fx.tcx.sess.overflow_checks() {
168 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
169 let target = fx.get_ebb(*target);
170 fx.bcx.ins().jump(target, &[]);
174 let cond = trans_operand(fx, cond).load_scalar(fx);
175 let target = fx.get_ebb(*target);
177 fx.bcx.ins().brnz(cond, target, &[]);
179 fx.bcx.ins().brz(cond, target, &[]);
184 "[panic] Assert {:?} at {:?} failed.",
186 bb_data.terminator().source_info.span
191 TerminatorKind::SwitchInt {
197 let discr = trans_operand(fx, discr).load_scalar(fx);
198 let mut switch = ::cranelift::frontend::Switch::new();
199 for (i, value) in values.iter().enumerate() {
200 let ebb = fx.get_ebb(targets[i]);
201 switch.set_entry(*value as u64, ebb);
203 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
204 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
206 TerminatorKind::Call {
213 crate::abi::codegen_terminator_call(
218 bb_data.terminator().source_info.span,
221 TerminatorKind::Resume | TerminatorKind::Abort => {
222 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
224 TerminatorKind::Unreachable => {
225 trap_unreachable(fx, "[corruption] Hit unreachable code.");
227 TerminatorKind::Yield { .. }
228 | TerminatorKind::FalseEdges { .. }
229 | TerminatorKind::FalseUnwind { .. }
230 | TerminatorKind::DropAndReplace { .. }
231 | TerminatorKind::GeneratorDrop => {
232 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
234 TerminatorKind::Drop {
239 let drop_place = trans_place(fx, location);
240 crate::abi::codegen_drop(fx, drop_place);
242 let target_ebb = fx.get_ebb(*target);
243 fx.bcx.ins().jump(target_ebb, &[]);
248 fx.bcx.seal_all_blocks();
253 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
255 stmt: &Statement<'tcx>,
257 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
259 fx.set_debug_loc(stmt.source_info);
261 #[cfg(debug_assertions)]
263 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
265 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
266 fx.add_comment(inst, format!("{:?}", stmt));
271 StatementKind::SetDiscriminant {
275 let place = trans_place(fx, place);
276 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
278 StatementKind::Assign(to_place_and_rval) => {
279 let lval = trans_place(fx, &to_place_and_rval.0);
280 let dest_layout = lval.layout();
281 match &to_place_and_rval.1 {
282 Rvalue::Use(operand) => {
283 let val = trans_operand(fx, operand);
284 lval.write_cvalue(fx, val);
286 Rvalue::Ref(_, _, place) => {
287 let place = trans_place(fx, place);
288 place.write_place_ref(fx, lval);
290 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
291 let lhs = trans_operand(fx, lhs);
292 let rhs = trans_operand(fx, rhs);
294 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
295 lval.write_cvalue(fx, res);
297 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
298 let lhs = trans_operand(fx, lhs);
299 let rhs = trans_operand(fx, rhs);
301 let res = if !fx.tcx.sess.overflow_checks() {
303 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
304 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
305 CValue::by_val_pair(val, is_overflow, lval.layout())
307 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
310 lval.write_cvalue(fx, res);
312 Rvalue::UnaryOp(un_op, operand) => {
313 let operand = trans_operand(fx, operand);
314 let layout = operand.layout();
315 let val = operand.load_scalar(fx);
316 let res = match un_op {
318 match layout.ty.kind {
320 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
321 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
322 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
324 ty::Uint(_) | ty::Int(_) => {
325 CValue::by_val(fx.bcx.ins().bnot(val), layout)
327 _ => unimplemented!("un op Not for {:?}", layout.ty),
330 UnOp::Neg => match layout.ty.kind {
332 let zero = CValue::const_val(fx, layout.ty, 0);
333 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
336 CValue::by_val(fx.bcx.ins().fneg(val), layout)
338 _ => unimplemented!("un op Neg for {:?}", layout.ty),
341 lval.write_cvalue(fx, res);
343 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
344 let layout = fx.layout_of(ty);
346 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
349 ty::FnDef(def_id, substs) => {
350 let func_ref = fx.get_function_ref(
351 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
354 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
355 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
357 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
360 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
361 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty)
362 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, ty) => {
363 let operand = trans_operand(fx, operand);
364 let layout = fx.layout_of(ty);
365 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
367 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
368 let operand = trans_operand(fx, operand);
369 let from_ty = operand.layout().ty;
370 let to_ty = fx.monomorphize(to_ty);
373 fx: &FunctionCx<'_, 'tcx, impl Backend>,
376 ty.builtin_deref(true)
381 }| has_ptr_meta(fx.tcx, pointee_ty),
386 if is_fat_ptr(fx, from_ty) {
387 if is_fat_ptr(fx, to_ty) {
388 // fat-ptr -> fat-ptr
389 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
391 // fat-ptr -> thin-ptr
392 let (ptr, _extra) = operand.load_scalar_pair(fx);
393 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
395 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
396 // enum -> discriminant value
397 assert!(adt_def.is_enum());
399 ty::Uint(_) | ty::Int(_) => {}
400 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
403 let discr = crate::discriminant::codegen_get_discriminant(
408 lval.write_cvalue(fx, discr);
410 let to_clif_ty = fx.clif_type(to_ty).unwrap();
411 let from = operand.load_scalar(fx);
413 let res = clif_int_or_float_cast(
420 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
423 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
424 let operand = trans_operand(fx, operand);
425 match operand.layout().ty.kind {
426 ty::Closure(def_id, substs) => {
427 let instance = Instance::resolve_closure(
431 ty::ClosureKind::FnOnce,
433 let func_ref = fx.get_function_ref(instance);
434 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
435 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
437 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
440 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
441 let operand = trans_operand(fx, operand);
442 operand.unsize_value(fx, lval);
444 Rvalue::Discriminant(place) => {
445 let place = trans_place(fx, place);
446 let value = place.to_cvalue(fx);
448 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
449 lval.write_cvalue(fx, discr);
451 Rvalue::Repeat(operand, times) => {
452 let operand = trans_operand(fx, operand);
454 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
455 let to = lval.place_index(fx, index);
456 to.write_cvalue(fx, operand);
459 Rvalue::Len(place) => {
460 let place = trans_place(fx, place);
461 let usize_layout = fx.layout_of(fx.tcx.types.usize);
462 let len = codegen_array_len(fx, place);
463 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
465 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
466 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
468 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
469 let layout = fx.layout_of(content_ty);
470 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
474 .iconst(usize_type, layout.align.abi.bytes() as i64);
475 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
478 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
483 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
486 let instance = ty::Instance::mono(fx.tcx, def_id);
487 let func_ref = fx.get_function_ref(instance);
488 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
489 let ptr = fx.bcx.inst_results(call)[0];
490 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
492 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
496 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
497 let ty_size = fx.layout_of(ty).size.bytes();
498 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
499 lval.write_cvalue(fx, val);
501 Rvalue::Aggregate(kind, operands) => match **kind {
502 AggregateKind::Array(_ty) => {
503 for (i, operand) in operands.into_iter().enumerate() {
504 let operand = trans_operand(fx, operand);
505 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
506 let to = lval.place_index(fx, index);
507 to.write_cvalue(fx, operand);
510 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
514 StatementKind::StorageLive(_)
515 | StatementKind::StorageDead(_)
517 | StatementKind::FakeRead(..)
518 | StatementKind::Retag { .. }
519 | StatementKind::AscribeUserType(..) => {}
521 StatementKind::InlineAsm(asm) => {
522 use syntax::ast::Name;
528 let rustc::hir::InlineAsmInner {
529 asm: asm_code, // Name
530 outputs, // Vec<Name>
532 clobbers, // Vec<Name>
535 dialect: _, // syntax::ast::AsmDialect
538 match &*asm_code.as_str() {
540 assert_eq!(inputs, &[Name::intern("r")]);
541 assert!(outputs.is_empty(), "{:?}", outputs);
545 "cpuid" | "cpuid\n" => {
546 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
548 assert_eq!(outputs.len(), 4);
549 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
553 assert_eq!(&outputs[i].constraint.as_str(), c);
554 assert!(!outputs[i].is_rw);
555 assert!(!outputs[i].is_indirect);
558 assert_eq!(clobbers, &[Name::intern("rbx")]);
561 assert!(!alignstack);
563 crate::trap::trap_unimplemented(
565 "__cpuid_count arch intrinsic is not supported",
569 assert_eq!(inputs, &[Name::intern("{ecx}")]);
571 assert_eq!(outputs.len(), 2);
572 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
573 assert_eq!(&outputs[i].constraint.as_str(), c);
574 assert!(!outputs[i].is_rw);
575 assert!(!outputs[i].is_indirect);
578 assert_eq!(clobbers, &[]);
581 assert!(!alignstack);
583 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
585 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
586 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
588 _ => unimpl!("Inline assembly is not supported"),
594 fn codegen_array_len<'tcx>(
595 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
598 match place.layout().ty.kind {
599 ty::Array(_elem_ty, len) => {
600 let len = crate::constant::force_eval_const(fx, len)
601 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
602 fx.bcx.ins().iconst(fx.pointer_type, len)
604 ty::Slice(_elem_ty) => place
605 .to_addr_maybe_unsized(fx)
607 .expect("Length metadata for slice place"),
608 _ => bug!("Rvalue::Len({:?})", place),
612 pub fn trans_place<'tcx>(
613 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
616 let mut cplace = match &place.base {
617 PlaceBase::Local(local) => fx.get_local_place(*local),
618 PlaceBase::Static(static_) => match static_.kind {
619 StaticKind::Static => {
620 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
622 StaticKind::Promoted(promoted, substs) => {
623 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
624 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
629 for elem in &*place.projection {
631 PlaceElem::Deref => {
632 cplace = cplace.place_deref(fx);
634 PlaceElem::Field(field, _ty) => {
635 cplace = cplace.place_field(fx, field);
637 PlaceElem::Index(local) => {
638 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
639 cplace = cplace.place_index(fx, index);
641 PlaceElem::ConstantIndex {
646 let index = if !from_end {
647 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
649 let len = codegen_array_len(fx, cplace);
650 fx.bcx.ins().iadd_imm(len, -(offset as i64))
652 cplace = cplace.place_index(fx, index);
654 PlaceElem::Subslice { from, to, from_end } => {
655 // These indices are generated by slice patterns.
656 // slice[from:-to] in Python terms.
658 match cplace.layout().ty.kind {
659 ty::Array(elem_ty, len) => {
660 let elem_layout = fx.layout_of(elem_ty);
661 let ptr = cplace.to_addr(fx);
662 let len = crate::constant::force_eval_const(fx, len)
663 .eval_usize(fx.tcx, ParamEnv::reveal_all());
664 cplace = CPlace::for_addr(
667 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
668 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
671 ty::Slice(elem_ty) => {
672 assert!(from_end, "slice subslices should be `from_end`");
673 let elem_layout = fx.layout_of(elem_ty);
674 let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
675 let len = len.unwrap();
676 cplace = CPlace::for_addr_with_extra(
679 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
680 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
687 PlaceElem::Downcast(_adt_def, variant) => {
688 cplace = cplace.downcast_variant(fx, variant);
696 pub fn trans_operand<'tcx>(
697 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
698 operand: &Operand<'tcx>,
701 Operand::Move(place) | Operand::Copy(place) => {
702 let cplace = trans_place(fx, place);
705 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),