1 use rustc_middle::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub(crate) fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'clif, '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();
18 let mut debug_context = cx
21 .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
23 // Make FunctionBuilder
24 let context = &mut cx.cached_context;
26 context.func.name = ExternalName::user(0, func_id.as_u32());
27 context.func.signature = sig;
28 context.func.collect_debug_info();
29 let mut func_ctx = FunctionBuilderContext::new();
30 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
33 let start_block = bcx.create_block();
34 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
37 let pointer_type = cx.module.target_config().pointer_type();
38 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
40 let mut fx = FunctionCx {
50 local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
51 caller_location: None, // set by `codegen_fn_prelude`
52 cold_blocks: EntitySet::new(),
55 constants_cx: &mut cx.constants_cx,
56 vtables: &mut cx.vtables,
57 source_info_set: indexmap::IndexSet::new(),
60 let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
63 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
64 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
65 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
67 tcx.sess.time("codegen clif ir", || {
68 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block, true));
69 codegen_fn_content(&mut fx);
73 // Recover all necessary data from fx, before accessing func will prevent future access to it.
74 let instance = fx.instance;
75 let mut clif_comments = fx.clif_comments;
76 let source_info_set = fx.source_info_set;
77 let local_map = fx.local_map;
78 let cold_blocks = fx.cold_blocks;
80 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
83 verify_func(tcx, &clif_comments, &context.func);
85 // Perform rust specific optimizations
86 tcx.sess.time("optimize clif ir", || {
87 crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
90 // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
91 // instruction, which doesn't have an encoding.
92 context.compute_cfg();
93 context.compute_domtree();
94 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
97 let module = &mut cx.module;
100 || module.define_function(
103 &mut cranelift_codegen::binemit::NullTrapSink {},
107 // Write optimized function to file for debugging
109 let value_ranges = context
110 .build_value_labels_ranges(cx.module.isa())
111 .expect("value location ranges");
113 crate::pretty_clif::write_clif_file(
123 // Define debuginfo for function
124 let isa = cx.module.isa();
125 let unwind_context = &mut cx.unwind_context;
126 tcx.sess.time("generate debug info", || {
129 .map(|x| x.define(context, isa, &source_info_set, local_map));
130 unwind_context.add_function(func_id, &context, isa);
133 // Clear context to make it usable for the next function
137 pub(crate) fn verify_func(tcx: TyCtxt<'_>, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
138 tcx.sess.time("verify clif ir", || {
139 let flags = settings::Flags::new(settings::builder());
140 match ::cranelift_codegen::verify_function(&func, &flags) {
143 tcx.sess.err(&format!("{:?}", err));
144 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
147 Some(Box::new(writer)),
151 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
157 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
158 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
159 let block = fx.get_block(bb);
160 fx.bcx.switch_to_block(block);
162 if bb_data.is_cleanup {
163 // Unwinding after panicking is not supported
166 // FIXME once unwinding is supported uncomment next lines
167 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
168 // fx.cold_blocks.insert(block);
172 for stmt in &bb_data.statements {
173 fx.set_debug_loc(stmt.source_info);
174 trans_stmt(fx, block, stmt);
177 #[cfg(debug_assertions)]
179 let mut terminator_head = "\n".to_string();
183 .fmt_head(&mut terminator_head)
185 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
186 fx.add_comment(inst, terminator_head);
189 fx.set_debug_loc(bb_data.terminator().source_info);
191 match &bb_data.terminator().kind {
192 TerminatorKind::Goto { target } => {
193 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
194 let mut can_immediately_return = true;
195 for stmt in &fx.mir[*target].statements {
196 if let StatementKind::StorageDead(_) = stmt.kind {
198 // FIXME Can sometimes happen, see rust-lang/rust#70531
199 can_immediately_return = false;
204 if can_immediately_return {
205 crate::abi::codegen_return(fx);
210 let block = fx.get_block(*target);
211 fx.bcx.ins().jump(block, &[]);
213 TerminatorKind::Return => {
214 crate::abi::codegen_return(fx);
216 TerminatorKind::Assert {
223 if !fx.tcx.sess.overflow_checks() {
224 if let mir::AssertKind::OverflowNeg = *msg {
225 let target = fx.get_block(*target);
226 fx.bcx.ins().jump(target, &[]);
230 let cond = trans_operand(fx, cond).load_scalar(fx);
232 let target = fx.get_block(*target);
233 let failure = fx.bcx.create_block();
234 fx.cold_blocks.insert(failure);
237 fx.bcx.ins().brz(cond, failure, &[]);
239 fx.bcx.ins().brnz(cond, failure, &[]);
241 fx.bcx.ins().jump(target, &[]);
243 fx.bcx.switch_to_block(failure);
245 let location = fx.get_caller_location(bb_data.terminator().source_info.span).load_scalar(fx);
248 let lang_item = match msg {
249 AssertKind::BoundsCheck { ref len, ref index } => {
250 let len = trans_operand(fx, len).load_scalar(fx);
251 let index = trans_operand(fx, index).load_scalar(fx);
252 args = [index, len, location];
253 rustc_hir::lang_items::PanicBoundsCheckFnLangItem
256 let msg_str = msg.description();
257 let msg_ptr = fx.anonymous_str("assert", msg_str);
258 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
259 args = [msg_ptr, msg_len, location];
260 rustc_hir::lang_items::PanicFnLangItem
264 let def_id = fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| {
265 fx.tcx.sess.span_fatal(bb_data.terminator().source_info.span, &s)
268 let instance = Instance::mono(fx.tcx, def_id);
269 let symbol_name = fx.tcx.symbol_name(instance).name.as_str();
271 fx.lib_call(&*symbol_name, vec![fx.pointer_type, fx.pointer_type, fx.pointer_type], vec![], &args);
273 crate::trap::trap_unreachable(fx, "panic lang item returned");
276 TerminatorKind::SwitchInt {
282 let discr = trans_operand(fx, discr).load_scalar(fx);
283 let mut switch = ::cranelift_frontend::Switch::new();
284 for (i, value) in values.iter().enumerate() {
285 let block = fx.get_block(targets[i]);
286 switch.set_entry(*value as u64, block);
288 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
289 switch.emit(&mut fx.bcx, discr, otherwise_block);
291 TerminatorKind::Call {
298 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
300 bb_data.terminator().source_info.span,
307 TerminatorKind::InlineAsm {
315 assert_eq!(operands, &[]);
317 Some(destination) => {
318 let destination_block = fx.get_block(destination);
319 fx.bcx.ins().jump(destination_block, &[]);
326 _ => unimpl_fatal!(fx.tcx, bb_data.terminator().source_info.span, "Inline assembly is not supported"),
329 TerminatorKind::Resume | TerminatorKind::Abort => {
330 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
332 TerminatorKind::Unreachable => {
333 trap_unreachable(fx, "[corruption] Hit unreachable code.");
335 TerminatorKind::Yield { .. }
336 | TerminatorKind::FalseEdges { .. }
337 | TerminatorKind::FalseUnwind { .. }
338 | TerminatorKind::DropAndReplace { .. }
339 | TerminatorKind::GeneratorDrop => {
340 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
342 TerminatorKind::Drop {
347 let drop_place = trans_place(fx, *location);
348 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
350 let target_block = fx.get_block(*target);
351 fx.bcx.ins().jump(target_block, &[]);
356 fx.bcx.seal_all_blocks();
361 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
362 #[allow(unused_variables)]
364 stmt: &Statement<'tcx>,
366 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
368 fx.set_debug_loc(stmt.source_info);
370 #[cfg(false_debug_assertions)]
372 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
374 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
375 fx.add_comment(inst, format!("{:?}", stmt));
380 StatementKind::SetDiscriminant {
384 let place = trans_place(fx, **place);
385 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
387 StatementKind::Assign(to_place_and_rval) => {
388 let lval = trans_place(fx, to_place_and_rval.0);
389 let dest_layout = lval.layout();
390 match &to_place_and_rval.1 {
391 Rvalue::Use(operand) => {
392 let val = trans_operand(fx, operand);
393 lval.write_cvalue(fx, val);
395 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
396 let place = trans_place(fx, *place);
397 place.write_place_ref(fx, lval);
399 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
400 let lhs = trans_operand(fx, lhs);
401 let rhs = trans_operand(fx, rhs);
403 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
404 lval.write_cvalue(fx, res);
406 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
407 let lhs = trans_operand(fx, lhs);
408 let rhs = trans_operand(fx, rhs);
410 let res = if !fx.tcx.sess.overflow_checks() {
412 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
413 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
414 CValue::by_val_pair(val, is_overflow, lval.layout())
416 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
419 lval.write_cvalue(fx, res);
421 Rvalue::UnaryOp(un_op, operand) => {
422 let operand = trans_operand(fx, operand);
423 let layout = operand.layout();
424 let val = operand.load_scalar(fx);
425 let res = match un_op {
427 match layout.ty.kind {
429 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
430 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
432 ty::Uint(_) | ty::Int(_) => {
433 CValue::by_val(fx.bcx.ins().bnot(val), layout)
435 _ => unreachable!("un op Not for {:?}", layout.ty),
438 UnOp::Neg => match layout.ty.kind {
439 ty::Int(IntTy::I128) => {
440 // FIXME remove this case once ineg.i128 works
441 let zero = CValue::const_val(fx, layout, 0);
442 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
445 CValue::by_val(fx.bcx.ins().ineg(val), layout)
448 CValue::by_val(fx.bcx.ins().fneg(val), layout)
450 _ => unreachable!("un op Neg for {:?}", layout.ty),
453 lval.write_cvalue(fx, res);
455 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
456 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
457 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
459 ty::FnDef(def_id, substs) => {
460 let func_ref = fx.get_function_ref(
461 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
464 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
465 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
467 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
470 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
471 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
472 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
473 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
474 let operand = trans_operand(fx, operand);
475 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
477 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
478 let operand = trans_operand(fx, operand);
479 let from_ty = operand.layout().ty;
480 let to_ty = fx.monomorphize(to_ty);
483 fx: &FunctionCx<'_, 'tcx, impl Backend>,
486 ty.builtin_deref(true)
491 }| has_ptr_meta(fx.tcx, pointee_ty),
496 if is_fat_ptr(fx, from_ty) {
497 if is_fat_ptr(fx, to_ty) {
498 // fat-ptr -> fat-ptr
499 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
501 // fat-ptr -> thin-ptr
502 let (ptr, _extra) = operand.load_scalar_pair(fx);
503 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
505 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
506 // enum -> discriminant value
507 assert!(adt_def.is_enum());
509 ty::Uint(_) | ty::Int(_) => {}
510 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
513 let discr = crate::discriminant::codegen_get_discriminant(
518 lval.write_cvalue(fx, discr);
520 let to_clif_ty = fx.clif_type(to_ty).unwrap();
521 let from = operand.load_scalar(fx);
523 let res = clif_int_or_float_cast(
530 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
533 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
534 let operand = trans_operand(fx, operand);
535 match operand.layout().ty.kind {
536 ty::Closure(def_id, substs) => {
537 let instance = Instance::resolve_closure(
541 ty::ClosureKind::FnOnce,
543 let func_ref = fx.get_function_ref(instance);
544 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
545 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
547 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
550 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
551 let operand = trans_operand(fx, operand);
552 operand.unsize_value(fx, lval);
554 Rvalue::Discriminant(place) => {
555 let place = trans_place(fx, *place);
556 let value = place.to_cvalue(fx);
558 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
559 lval.write_cvalue(fx, discr);
561 Rvalue::Repeat(operand, times) => {
562 let operand = trans_operand(fx, operand);
565 .eval(fx.tcx, ParamEnv::reveal_all())
567 .try_to_bits(fx.tcx.data_layout.pointer_size)
570 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
571 let to = lval.place_index(fx, index);
572 to.write_cvalue(fx, operand);
575 Rvalue::Len(place) => {
576 let place = trans_place(fx, *place);
577 let usize_layout = fx.layout_of(fx.tcx.types.usize);
578 let len = codegen_array_len(fx, place);
579 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
581 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
582 use rustc_hir::lang_items::ExchangeMallocFnLangItem;
584 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
585 let content_ty = fx.monomorphize(content_ty);
586 let layout = fx.layout_of(content_ty);
587 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
591 .iconst(usize_type, layout.align.abi.bytes() as i64);
592 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
595 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
600 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
603 let instance = ty::Instance::mono(fx.tcx, def_id);
604 let func_ref = fx.get_function_ref(instance);
605 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
606 let ptr = fx.bcx.inst_results(call)[0];
607 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
609 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
613 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
614 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
615 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
616 lval.write_cvalue(fx, val);
618 Rvalue::Aggregate(kind, operands) => match **kind {
619 AggregateKind::Array(_ty) => {
620 for (i, operand) in operands.into_iter().enumerate() {
621 let operand = trans_operand(fx, operand);
622 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
623 let to = lval.place_index(fx, index);
624 to.write_cvalue(fx, operand);
627 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
631 StatementKind::StorageLive(_)
632 | StatementKind::StorageDead(_)
634 | StatementKind::FakeRead(..)
635 | StatementKind::Retag { .. }
636 | StatementKind::AscribeUserType(..) => {}
638 StatementKind::LlvmInlineAsm(asm) => {
639 use rustc_span::symbol::Symbol;
645 let rustc_hir::LlvmInlineAsmInner {
646 asm: asm_code, // Name
647 outputs, // Vec<Name>
649 clobbers, // Vec<Name>
652 dialect: _, // rustc_ast::ast::AsmDialect
655 match &*asm_code.as_str() {
656 cpuid if cpuid.contains("cpuid") => {
657 crate::trap::trap_unimplemented(
659 "__cpuid_count arch intrinsic is not supported",
663 assert_eq!(inputs, &[Symbol::intern("{ecx}")]);
665 assert_eq!(outputs.len(), 2);
666 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
667 assert_eq!(&outputs[i].constraint.as_str(), c);
668 assert!(!outputs[i].is_rw);
669 assert!(!outputs[i].is_indirect);
672 assert_eq!(clobbers, &[]);
675 assert!(!alignstack);
677 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
679 _ => unimpl_fatal!(fx.tcx, stmt.source_info.span, "Inline assembly is not supported"),
685 fn codegen_array_len<'tcx>(
686 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
689 match place.layout().ty.kind {
690 ty::Array(_elem_ty, len) => {
691 let len = fx.monomorphize(&len)
692 .eval(fx.tcx, ParamEnv::reveal_all())
693 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
694 fx.bcx.ins().iconst(fx.pointer_type, len)
696 ty::Slice(_elem_ty) => place
697 .to_ptr_maybe_unsized()
699 .expect("Length metadata for slice place"),
700 _ => bug!("Rvalue::Len({:?})", place),
704 pub(crate) fn trans_place<'tcx>(
705 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
708 let mut cplace = fx.get_local_place(place.local);
710 for elem in place.projection {
712 PlaceElem::Deref => {
713 cplace = cplace.place_deref(fx);
715 PlaceElem::Field(field, _ty) => {
716 cplace = cplace.place_field(fx, field);
718 PlaceElem::Index(local) => {
719 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
720 cplace = cplace.place_index(fx, index);
722 PlaceElem::ConstantIndex {
727 let index = if !from_end {
728 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
730 let len = codegen_array_len(fx, cplace);
731 fx.bcx.ins().iadd_imm(len, -(offset as i64))
733 cplace = cplace.place_index(fx, index);
735 PlaceElem::Subslice { from, to, from_end } => {
736 // These indices are generated by slice patterns.
737 // slice[from:-to] in Python terms.
739 match cplace.layout().ty.kind {
740 ty::Array(elem_ty, _len) => {
741 assert!(!from_end, "array subslices are never `from_end`");
742 let elem_layout = fx.layout_of(elem_ty);
743 let ptr = cplace.to_ptr();
744 cplace = CPlace::for_ptr(
745 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
746 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
749 ty::Slice(elem_ty) => {
750 assert!(from_end, "slice subslices should be `from_end`");
751 let elem_layout = fx.layout_of(elem_ty);
752 let (ptr, len) = cplace.to_ptr_maybe_unsized();
753 let len = len.unwrap();
754 cplace = CPlace::for_ptr_with_extra(
755 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
756 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
763 PlaceElem::Downcast(_adt_def, variant) => {
764 cplace = cplace.downcast_variant(fx, variant);
772 pub(crate) fn trans_operand<'tcx>(
773 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
774 operand: &Operand<'tcx>,
777 Operand::Move(place) | Operand::Copy(place) => {
778 let cplace = trans_place(fx, *place);
781 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),