1 use rustc_middle::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'tcx, B>,
8 instance: Instance<'tcx>,
13 let mir = tcx.instance_mir(instance.def);
16 let (name, sig) = get_function_name_and_sig(tcx, cx.module.isa().triple(), instance, false);
17 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
19 // Make FunctionBuilder
20 let context = &mut cx.cached_context;
22 context.func.name = ExternalName::user(0, func_id.as_u32());
23 context.func.signature = sig;
24 context.func.collect_debug_info();
25 let mut func_ctx = FunctionBuilderContext::new();
26 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
29 let start_block = bcx.create_block();
30 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
33 let pointer_type = cx.module.target_config().pointer_type();
34 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
36 let mut fx = FunctionCx {
38 module: &mut cx.module,
46 local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
47 caller_location: None, // set by `codegen_fn_prelude`
48 cold_blocks: EntitySet::new(),
51 constants_cx: &mut cx.constants_cx,
52 vtables: &mut cx.vtables,
53 source_info_set: indexmap::IndexSet::new(),
56 let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
59 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
60 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
61 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
63 tcx.sess.time("codegen clif ir", || {
64 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block, true));
65 codegen_fn_content(&mut fx);
69 // Recover all necessary data from fx, before accessing func will prevent future access to it.
70 let instance = fx.instance;
71 let mut clif_comments = fx.clif_comments;
72 let source_info_set = fx.source_info_set;
73 let local_map = fx.local_map;
74 let cold_blocks = fx.cold_blocks;
76 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
79 verify_func(tcx, &clif_comments, &context.func);
81 // Perform rust specific optimizations
82 tcx.sess.time("optimize clif ir", || {
83 crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
86 // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
87 // instruction, which doesn't have an encoding.
88 context.compute_cfg();
89 context.compute_domtree();
90 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
93 let module = &mut cx.module;
96 || module.define_function(
99 &mut cranelift_codegen::binemit::NullTrapSink {},
103 // Write optimized function to file for debugging
105 let value_ranges = context
106 .build_value_labels_ranges(cx.module.isa())
107 .expect("value location ranges");
109 crate::pretty_clif::write_clif_file(
119 // Define debuginfo for function
120 let isa = cx.module.isa();
121 let debug_context = &mut cx.debug_context;
122 let unwind_context = &mut cx.unwind_context;
123 tcx.sess.time("generate debug info", || {
124 if let Some(debug_context) = debug_context {
125 debug_context.define_function(instance, func_id, &name, isa, context, &source_info_set, local_map);
127 unwind_context.add_function(func_id, &context, isa);
130 // Clear context to make it usable for the next function
134 pub(crate) fn verify_func(tcx: TyCtxt<'_>, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
135 tcx.sess.time("verify clif ir", || {
136 let flags = settings::Flags::new(settings::builder());
137 match ::cranelift_codegen::verify_function(&func, &flags) {
140 tcx.sess.err(&format!("{:?}", err));
141 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
144 Some(Box::new(writer)),
148 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
154 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
155 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
156 let block = fx.get_block(bb);
157 fx.bcx.switch_to_block(block);
159 if bb_data.is_cleanup {
160 // Unwinding after panicking is not supported
163 // FIXME once unwinding is supported uncomment next lines
164 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
165 // fx.cold_blocks.insert(block);
169 for stmt in &bb_data.statements {
170 fx.set_debug_loc(stmt.source_info);
171 trans_stmt(fx, block, stmt);
174 #[cfg(debug_assertions)]
176 let mut terminator_head = "\n".to_string();
180 .fmt_head(&mut terminator_head)
182 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
183 fx.add_comment(inst, terminator_head);
186 fx.set_debug_loc(bb_data.terminator().source_info);
188 match &bb_data.terminator().kind {
189 TerminatorKind::Goto { target } => {
190 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
191 let mut can_immediately_return = true;
192 for stmt in &fx.mir[*target].statements {
193 if let StatementKind::StorageDead(_) = stmt.kind {
195 // FIXME Can sometimes happen, see rust-lang/rust#70531
196 can_immediately_return = false;
201 if can_immediately_return {
202 crate::abi::codegen_return(fx);
207 let block = fx.get_block(*target);
208 fx.bcx.ins().jump(block, &[]);
210 TerminatorKind::Return => {
211 crate::abi::codegen_return(fx);
213 TerminatorKind::Assert {
220 if !fx.tcx.sess.overflow_checks() {
221 if let mir::AssertKind::OverflowNeg = *msg {
222 let target = fx.get_block(*target);
223 fx.bcx.ins().jump(target, &[]);
227 let cond = trans_operand(fx, cond).load_scalar(fx);
229 let target = fx.get_block(*target);
230 let failure = fx.bcx.create_block();
231 fx.cold_blocks.insert(failure);
234 fx.bcx.ins().brz(cond, failure, &[]);
236 fx.bcx.ins().brnz(cond, failure, &[]);
238 fx.bcx.ins().jump(target, &[]);
240 fx.bcx.switch_to_block(failure);
242 let location = fx.get_caller_location(bb_data.terminator().source_info.span).load_scalar(fx);
245 let lang_item = match msg {
246 AssertKind::BoundsCheck { ref len, ref index } => {
247 let len = trans_operand(fx, len).load_scalar(fx);
248 let index = trans_operand(fx, index).load_scalar(fx);
249 args = [index, len, location];
250 rustc_hir::lang_items::PanicBoundsCheckFnLangItem
253 let msg_str = msg.description();
254 let msg_ptr = fx.anonymous_str("assert", msg_str);
255 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
256 args = [msg_ptr, msg_len, location];
257 rustc_hir::lang_items::PanicFnLangItem
261 let def_id = fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| {
262 fx.tcx.sess.span_fatal(bb_data.terminator().source_info.span, &s)
265 let instance = Instance::mono(fx.tcx, def_id);
266 let symbol_name = fx.tcx.symbol_name(instance).name.as_str();
268 fx.lib_call(&*symbol_name, vec![fx.pointer_type, fx.pointer_type, fx.pointer_type], vec![], &args);
270 crate::trap::trap_unreachable(fx, "panic lang item returned");
273 TerminatorKind::SwitchInt {
279 let discr = trans_operand(fx, discr).load_scalar(fx);
280 let mut switch = ::cranelift_frontend::Switch::new();
281 for (i, value) in values.iter().enumerate() {
282 let block = fx.get_block(targets[i]);
283 switch.set_entry(*value as u64, block);
285 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
286 switch.emit(&mut fx.bcx, discr, otherwise_block);
288 TerminatorKind::Call {
296 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
305 TerminatorKind::InlineAsm {
314 assert_eq!(operands, &[]);
316 Some(destination) => {
317 let destination_block = fx.get_block(destination);
318 fx.bcx.ins().jump(destination_block, &[]);
325 _ => unimpl_fatal!(fx.tcx, bb_data.terminator().source_info.span, "Inline assembly is not supported"),
328 TerminatorKind::Resume | TerminatorKind::Abort => {
329 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
331 TerminatorKind::Unreachable => {
332 trap_unreachable(fx, "[corruption] Hit unreachable code.");
334 TerminatorKind::Yield { .. }
335 | TerminatorKind::FalseEdge { .. }
336 | TerminatorKind::FalseUnwind { .. }
337 | TerminatorKind::DropAndReplace { .. }
338 | TerminatorKind::GeneratorDrop => {
339 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
341 TerminatorKind::Drop {
346 let drop_place = trans_place(fx, *location);
347 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
349 let target_block = fx.get_block(*target);
350 fx.bcx.ins().jump(target_block, &[]);
355 fx.bcx.seal_all_blocks();
360 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
361 #[allow(unused_variables)]
363 stmt: &Statement<'tcx>,
365 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
367 fx.set_debug_loc(stmt.source_info);
369 #[cfg(false_debug_assertions)]
371 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
373 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
374 fx.add_comment(inst, format!("{:?}", stmt));
379 StatementKind::SetDiscriminant {
383 let place = trans_place(fx, **place);
384 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
386 StatementKind::Assign(to_place_and_rval) => {
387 let lval = trans_place(fx, to_place_and_rval.0);
388 let dest_layout = lval.layout();
389 match &to_place_and_rval.1 {
390 Rvalue::Use(operand) => {
391 let val = trans_operand(fx, operand);
392 lval.write_cvalue(fx, val);
394 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
395 let place = trans_place(fx, *place);
396 place.write_place_ref(fx, lval);
398 Rvalue::ThreadLocalRef(def_id) => {
399 let val = crate::constant::codegen_tls_ref(fx, *def_id, lval.layout());
400 lval.write_cvalue(fx, val);
402 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
403 let lhs = trans_operand(fx, lhs);
404 let rhs = trans_operand(fx, rhs);
406 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
407 lval.write_cvalue(fx, res);
409 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
410 let lhs = trans_operand(fx, lhs);
411 let rhs = trans_operand(fx, rhs);
413 let res = if !fx.tcx.sess.overflow_checks() {
415 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
416 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
417 CValue::by_val_pair(val, is_overflow, lval.layout())
419 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
422 lval.write_cvalue(fx, res);
424 Rvalue::UnaryOp(un_op, operand) => {
425 let operand = trans_operand(fx, operand);
426 let layout = operand.layout();
427 let val = operand.load_scalar(fx);
428 let res = match un_op {
430 match layout.ty.kind {
432 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
433 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
435 ty::Uint(_) | ty::Int(_) => {
436 CValue::by_val(fx.bcx.ins().bnot(val), layout)
438 _ => unreachable!("un op Not for {:?}", layout.ty),
441 UnOp::Neg => match layout.ty.kind {
442 ty::Int(IntTy::I128) => {
443 // FIXME remove this case once ineg.i128 works
444 let zero = CValue::const_val(fx, layout, 0);
445 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
448 CValue::by_val(fx.bcx.ins().ineg(val), layout)
451 CValue::by_val(fx.bcx.ins().fneg(val), layout)
453 _ => unreachable!("un op Neg for {:?}", layout.ty),
456 lval.write_cvalue(fx, res);
458 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
459 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
460 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
462 ty::FnDef(def_id, substs) => {
463 let func_ref = fx.get_function_ref(
464 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
467 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
468 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
470 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
473 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
474 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
475 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
476 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
477 let operand = trans_operand(fx, operand);
478 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
480 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
481 let operand = trans_operand(fx, operand);
482 let from_ty = operand.layout().ty;
483 let to_ty = fx.monomorphize(to_ty);
486 fx: &FunctionCx<'_, 'tcx, impl Backend>,
489 ty.builtin_deref(true)
494 }| has_ptr_meta(fx.tcx, pointee_ty),
499 if is_fat_ptr(fx, from_ty) {
500 if is_fat_ptr(fx, to_ty) {
501 // fat-ptr -> fat-ptr
502 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
504 // fat-ptr -> thin-ptr
505 let (ptr, _extra) = operand.load_scalar_pair(fx);
506 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
508 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
509 // enum -> discriminant value
510 assert!(adt_def.is_enum());
512 ty::Uint(_) | ty::Int(_) => {}
513 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
516 let discr = crate::discriminant::codegen_get_discriminant(
521 lval.write_cvalue(fx, discr);
523 let to_clif_ty = fx.clif_type(to_ty).unwrap();
524 let from = operand.load_scalar(fx);
526 let res = clif_int_or_float_cast(
533 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
536 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
537 let operand = trans_operand(fx, operand);
538 match operand.layout().ty.kind {
539 ty::Closure(def_id, substs) => {
540 let instance = Instance::resolve_closure(
544 ty::ClosureKind::FnOnce,
546 let func_ref = fx.get_function_ref(instance);
547 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
548 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
550 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
553 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
554 let operand = trans_operand(fx, operand);
555 operand.unsize_value(fx, lval);
557 Rvalue::Discriminant(place) => {
558 let place = trans_place(fx, *place);
559 let value = place.to_cvalue(fx);
561 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
562 lval.write_cvalue(fx, discr);
564 Rvalue::Repeat(operand, times) => {
565 let operand = trans_operand(fx, operand);
568 .eval(fx.tcx, ParamEnv::reveal_all())
570 .try_to_bits(fx.tcx.data_layout.pointer_size)
573 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
574 let to = lval.place_index(fx, index);
575 to.write_cvalue(fx, operand);
578 Rvalue::Len(place) => {
579 let place = trans_place(fx, *place);
580 let usize_layout = fx.layout_of(fx.tcx.types.usize);
581 let len = codegen_array_len(fx, place);
582 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
584 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
585 use rustc_hir::lang_items::ExchangeMallocFnLangItem;
587 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
588 let content_ty = fx.monomorphize(content_ty);
589 let layout = fx.layout_of(content_ty);
590 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
594 .iconst(usize_type, layout.align.abi.bytes() as i64);
595 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
598 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
603 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
606 let instance = ty::Instance::mono(fx.tcx, def_id);
607 let func_ref = fx.get_function_ref(instance);
608 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
609 let ptr = fx.bcx.inst_results(call)[0];
610 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
612 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
616 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
617 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
618 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
619 lval.write_cvalue(fx, val);
621 Rvalue::Aggregate(kind, operands) => match **kind {
622 AggregateKind::Array(_ty) => {
623 for (i, operand) in operands.into_iter().enumerate() {
624 let operand = trans_operand(fx, operand);
625 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
626 let to = lval.place_index(fx, index);
627 to.write_cvalue(fx, operand);
630 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
634 StatementKind::StorageLive(_)
635 | StatementKind::StorageDead(_)
637 | StatementKind::FakeRead(..)
638 | StatementKind::Retag { .. }
639 | StatementKind::AscribeUserType(..) => {}
641 StatementKind::LlvmInlineAsm(asm) => {
642 use rustc_span::symbol::Symbol;
648 let rustc_hir::LlvmInlineAsmInner {
649 asm: asm_code, // Name
650 outputs, // Vec<Name>
652 clobbers, // Vec<Name>
655 dialect: _, // rustc_ast::ast::AsmDialect
658 match &*asm_code.as_str() {
659 cpuid if cpuid.contains("cpuid") => {
660 crate::trap::trap_unimplemented(
662 "__cpuid_count arch intrinsic is not supported",
666 assert_eq!(inputs, &[Symbol::intern("{ecx}")]);
668 assert_eq!(outputs.len(), 2);
669 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
670 assert_eq!(&outputs[i].constraint.as_str(), c);
671 assert!(!outputs[i].is_rw);
672 assert!(!outputs[i].is_indirect);
675 assert_eq!(clobbers, &[]);
678 assert!(!alignstack);
680 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
682 _ => unimpl_fatal!(fx.tcx, stmt.source_info.span, "Inline assembly is not supported"),
688 fn codegen_array_len<'tcx>(
689 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
692 match place.layout().ty.kind {
693 ty::Array(_elem_ty, len) => {
694 let len = fx.monomorphize(&len)
695 .eval(fx.tcx, ParamEnv::reveal_all())
696 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
697 fx.bcx.ins().iconst(fx.pointer_type, len)
699 ty::Slice(_elem_ty) => place
700 .to_ptr_maybe_unsized()
702 .expect("Length metadata for slice place"),
703 _ => bug!("Rvalue::Len({:?})", place),
707 pub(crate) fn trans_place<'tcx>(
708 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
711 let mut cplace = fx.get_local_place(place.local);
713 for elem in place.projection {
715 PlaceElem::Deref => {
716 cplace = cplace.place_deref(fx);
718 PlaceElem::Field(field, _ty) => {
719 cplace = cplace.place_field(fx, field);
721 PlaceElem::Index(local) => {
722 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
723 cplace = cplace.place_index(fx, index);
725 PlaceElem::ConstantIndex {
730 let index = if !from_end {
731 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
733 let len = codegen_array_len(fx, cplace);
734 fx.bcx.ins().iadd_imm(len, -(offset as i64))
736 cplace = cplace.place_index(fx, index);
738 PlaceElem::Subslice { from, to, from_end } => {
739 // These indices are generated by slice patterns.
740 // slice[from:-to] in Python terms.
742 match cplace.layout().ty.kind {
743 ty::Array(elem_ty, _len) => {
744 assert!(!from_end, "array subslices are never `from_end`");
745 let elem_layout = fx.layout_of(elem_ty);
746 let ptr = cplace.to_ptr();
747 cplace = CPlace::for_ptr(
748 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
749 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
752 ty::Slice(elem_ty) => {
753 assert!(from_end, "slice subslices should be `from_end`");
754 let elem_layout = fx.layout_of(elem_ty);
755 let (ptr, len) = cplace.to_ptr_maybe_unsized();
756 let len = len.unwrap();
757 cplace = CPlace::for_ptr_with_extra(
758 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
759 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
766 PlaceElem::Downcast(_adt_def, variant) => {
767 cplace = cplace.downcast_variant(fx, variant);
775 pub(crate) fn trans_operand<'tcx>(
776 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
777 operand: &Operand<'tcx>,
780 Operand::Move(place) | Operand::Copy(place) => {
781 let cplace = trans_place(fx, *place);
784 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),