1 //! Codegen of a single function
3 use rustc_ast::InlineAsmOptions;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiOf;
7 use rustc_middle::ty::print::with_no_trimmed_paths;
9 use indexmap::IndexSet;
11 use crate::constant::ConstantCx;
12 use crate::prelude::*;
13 use crate::pretty_clif::CommentWriter;
15 pub(crate) fn codegen_fn<'tcx>(
16 cx: &mut crate::CodegenCx<'tcx>,
17 module: &mut dyn Module,
18 instance: Instance<'tcx>,
23 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
24 debug_assert!(!instance.substs.needs_infer());
26 let mir = tcx.instance_mir(instance.def);
27 let _mir_guard = crate::PrintOnPanic(|| {
28 let mut buf = Vec::new();
29 with_no_trimmed_paths!({
30 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
33 String::from_utf8_lossy(&buf).into_owned()
37 let symbol_name = tcx.symbol_name(instance);
38 let sig = get_function_sig(tcx, module.isa().triple(), instance);
39 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
41 cx.cached_context.clear();
43 // Make the FunctionBuilder
44 let mut func_ctx = FunctionBuilderContext::new();
45 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
46 func.name = ExternalName::user(0, func_id.as_u32());
48 func.collect_debug_info();
50 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
53 let start_block = bcx.create_block();
54 let block_map: IndexVec<BasicBlock, Block> =
55 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
58 let target_config = module.target_config();
59 let pointer_type = target_config.pointer_type();
60 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
62 let mut fx = FunctionCx {
68 constants_cx: ConstantCx::new(),
73 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
77 local_map: IndexVec::with_capacity(mir.local_decls.len()),
78 caller_location: None, // set by `codegen_fn_prelude`
81 source_info_set: indexmap::IndexSet::new(),
85 let arg_uninhabited = fx
88 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
90 if !crate::constant::check_constants(&mut fx) {
91 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
92 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
93 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
94 } else if arg_uninhabited {
95 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
96 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
97 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
99 tcx.sess.time("codegen clif ir", || {
101 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
102 codegen_fn_content(&mut fx);
106 // Recover all necessary data from fx, before accessing func will prevent future access to it.
107 let instance = fx.instance;
108 let clif_comments = fx.clif_comments;
109 let source_info_set = fx.source_info_set;
110 let local_map = fx.local_map;
112 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
114 crate::pretty_clif::write_clif_file(
124 verify_func(tcx, &clif_comments, &func);
140 cx: &mut crate::CodegenCx<'tcx>,
141 module: &mut dyn Module,
142 instance: Instance<'tcx>,
146 mut clif_comments: CommentWriter,
147 source_info_set: IndexSet<SourceInfo>,
148 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
152 // Store function in context
153 let context = &mut cx.cached_context;
157 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
158 // instruction, which doesn't have an encoding.
159 context.compute_cfg();
160 context.compute_domtree();
161 context.eliminate_unreachable_code(module.isa()).unwrap();
162 context.dce(module.isa()).unwrap();
163 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
164 // invalidate it when it would change.
165 context.domtree.clear();
167 // Perform rust specific optimizations
168 tcx.sess.time("optimize clif ir", || {
169 crate::optimize::optimize_function(
178 #[cfg(any())] // This is never true
182 let func_clone = context.func.clone();
183 let clif_comments_clone = clif_comments.clone();
184 let mut clif = String::new();
185 for flag in module.isa().flags().iter() {
186 writeln!(clif, "set {}", flag).unwrap();
188 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
189 for isa_flag in module.isa().isa_flags().iter() {
190 write!(clif, " {}", isa_flag).unwrap();
192 writeln!(clif, "\n").unwrap();
193 crate::PrintOnPanic(move || {
194 let mut clif = clif.clone();
195 ::cranelift_codegen::write::decorate_function(
196 &mut &clif_comments_clone,
206 tcx.sess.time("define function", || {
207 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
208 module.define_function(func_id, context).unwrap();
211 // Write optimized function to file for debugging
212 crate::pretty_clif::write_clif_file(
221 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
222 crate::pretty_clif::write_ir_file(
224 || format!("{}.vcode", tcx.symbol_name(instance).name),
225 |file| file.write_all(disasm.as_bytes()),
229 // Define debuginfo for function
230 let isa = module.isa();
231 let debug_context = &mut cx.debug_context;
232 let unwind_context = &mut cx.unwind_context;
233 tcx.sess.time("generate debug info", || {
234 if let Some(debug_context) = debug_context {
235 debug_context.define_function(
245 unwind_context.add_function(func_id, &context, isa);
249 pub(crate) fn verify_func(
251 writer: &crate::pretty_clif::CommentWriter,
254 tcx.sess.time("verify clif ir", || {
255 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
256 match cranelift_codegen::verify_function(&func, &flags) {
259 tcx.sess.err(&format!("{:?}", err));
260 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
262 Some(Box::new(writer)),
265 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
271 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
272 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
273 let block = fx.get_block(bb);
274 fx.bcx.switch_to_block(block);
276 if bb_data.is_cleanup {
277 // Unwinding after panicking is not supported
280 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
281 // so for cleanup blocks.
285 for stmt in &bb_data.statements {
286 fx.set_debug_loc(stmt.source_info);
287 codegen_stmt(fx, block, stmt);
290 if fx.clif_comments.enabled() {
291 let mut terminator_head = "\n".to_string();
292 with_no_trimmed_paths!({
293 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
295 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
296 fx.add_comment(inst, terminator_head);
299 let source_info = bb_data.terminator().source_info;
300 fx.set_debug_loc(source_info);
302 match &bb_data.terminator().kind {
303 TerminatorKind::Goto { target } => {
304 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
305 let mut can_immediately_return = true;
306 for stmt in &fx.mir[*target].statements {
307 if let StatementKind::StorageDead(_) = stmt.kind {
309 // FIXME Can sometimes happen, see rust-lang/rust#70531
310 can_immediately_return = false;
315 if can_immediately_return {
316 crate::abi::codegen_return(fx);
321 let block = fx.get_block(*target);
322 fx.bcx.ins().jump(block, &[]);
324 TerminatorKind::Return => {
325 crate::abi::codegen_return(fx);
327 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
328 if !fx.tcx.sess.overflow_checks() {
329 if let mir::AssertKind::OverflowNeg(_) = *msg {
330 let target = fx.get_block(*target);
331 fx.bcx.ins().jump(target, &[]);
335 let cond = codegen_operand(fx, cond).load_scalar(fx);
337 let target = fx.get_block(*target);
338 let failure = fx.bcx.create_block();
339 fx.bcx.set_cold_block(failure);
342 fx.bcx.ins().brz(cond, failure, &[]);
344 fx.bcx.ins().brnz(cond, failure, &[]);
346 fx.bcx.ins().jump(target, &[]);
348 fx.bcx.switch_to_block(failure);
352 AssertKind::BoundsCheck { ref len, ref index } => {
353 let len = codegen_operand(fx, len).load_scalar(fx);
354 let index = codegen_operand(fx, index).load_scalar(fx);
355 let location = fx.get_caller_location(source_info).load_scalar(fx);
359 rustc_hir::LangItem::PanicBoundsCheck,
360 &[index, len, location],
365 let msg_str = msg.description();
366 codegen_panic(fx, msg_str, source_info);
371 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
372 let discr = codegen_operand(fx, discr).load_scalar(fx);
374 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
375 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
377 assert_eq!(targets.iter().count(), 1);
378 let (then_value, then_block) = targets.iter().next().unwrap();
379 let then_block = fx.get_block(then_block);
380 let else_block = fx.get_block(targets.otherwise());
381 let test_zero = match then_value {
384 _ => unreachable!("{:?}", targets),
387 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
388 let (discr, is_inverted) =
389 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
390 let test_zero = if is_inverted { !test_zero } else { test_zero };
391 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
392 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
393 &fx.bcx, discr, test_zero,
396 fx.bcx.ins().jump(then_block, &[]);
398 fx.bcx.ins().jump(else_block, &[]);
402 fx.bcx.ins().brz(discr, then_block, &[]);
403 fx.bcx.ins().jump(else_block, &[]);
405 fx.bcx.ins().brnz(discr, then_block, &[]);
406 fx.bcx.ins().jump(else_block, &[]);
410 let mut switch = ::cranelift_frontend::Switch::new();
411 for (value, block) in targets.iter() {
412 let block = fx.get_block(block);
413 switch.set_entry(value, block);
415 let otherwise_block = fx.get_block(targets.otherwise());
416 switch.emit(&mut fx.bcx, discr, otherwise_block);
419 TerminatorKind::Call {
428 fx.tcx.sess.time("codegen call", || {
429 crate::abi::codegen_terminator_call(
431 mir::SourceInfo { span: *fn_span, ..source_info },
439 TerminatorKind::InlineAsm {
447 if options.contains(InlineAsmOptions::MAY_UNWIND) {
448 fx.tcx.sess.span_fatal(
450 "cranelift doesn't support unwinding from inline assembly.",
454 crate::inline_asm::codegen_inline_asm(
463 Some(destination) => {
464 let destination_block = fx.get_block(destination);
465 fx.bcx.ins().jump(destination_block, &[]);
468 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
472 TerminatorKind::Resume | TerminatorKind::Abort => {
473 // FIXME implement unwinding
474 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
476 TerminatorKind::Unreachable => {
477 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
479 TerminatorKind::Yield { .. }
480 | TerminatorKind::FalseEdge { .. }
481 | TerminatorKind::FalseUnwind { .. }
482 | TerminatorKind::DropAndReplace { .. }
483 | TerminatorKind::GeneratorDrop => {
484 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
486 TerminatorKind::Drop { place, target, unwind: _ } => {
487 let drop_place = codegen_place(fx, *place);
488 crate::abi::codegen_drop(fx, source_info, drop_place);
490 let target_block = fx.get_block(*target);
491 fx.bcx.ins().jump(target_block, &[]);
496 fx.bcx.seal_all_blocks();
500 fn codegen_stmt<'tcx>(
501 fx: &mut FunctionCx<'_, '_, 'tcx>,
502 #[allow(unused_variables)] cur_block: Block,
503 stmt: &Statement<'tcx>,
505 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
507 fx.set_debug_loc(stmt.source_info);
509 #[cfg(any())] // This is never true
511 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
513 if fx.clif_comments.enabled() {
514 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
515 fx.add_comment(inst, format!("{:?}", stmt));
521 StatementKind::SetDiscriminant { place, variant_index } => {
522 let place = codegen_place(fx, **place);
523 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
525 StatementKind::Assign(to_place_and_rval) => {
526 let lval = codegen_place(fx, to_place_and_rval.0);
527 let dest_layout = lval.layout();
528 match to_place_and_rval.1 {
529 Rvalue::Use(ref operand) => {
530 let val = codegen_operand(fx, operand);
531 lval.write_cvalue(fx, val);
533 Rvalue::CopyForDeref(place) => {
534 let cplace = codegen_place(fx, place);
535 let val = cplace.to_cvalue(fx);
536 lval.write_cvalue(fx, val)
538 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
539 let place = codegen_place(fx, place);
540 let ref_ = place.place_ref(fx, lval.layout());
541 lval.write_cvalue(fx, ref_);
543 Rvalue::ThreadLocalRef(def_id) => {
544 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
545 lval.write_cvalue(fx, val);
547 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
548 let lhs = codegen_operand(fx, &lhs_rhs.0);
549 let rhs = codegen_operand(fx, &lhs_rhs.1);
551 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
552 lval.write_cvalue(fx, res);
554 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
555 let lhs = codegen_operand(fx, &lhs_rhs.0);
556 let rhs = codegen_operand(fx, &lhs_rhs.1);
558 let res = if !fx.tcx.sess.overflow_checks() {
560 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
561 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
562 CValue::by_val_pair(val, is_overflow, lval.layout())
564 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
567 lval.write_cvalue(fx, res);
569 Rvalue::UnaryOp(un_op, ref operand) => {
570 let operand = codegen_operand(fx, operand);
571 let layout = operand.layout();
572 let val = operand.load_scalar(fx);
573 let res = match un_op {
574 UnOp::Not => match layout.ty.kind() {
576 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
577 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
579 ty::Uint(_) | ty::Int(_) => {
580 CValue::by_val(fx.bcx.ins().bnot(val), layout)
582 _ => unreachable!("un op Not for {:?}", layout.ty),
584 UnOp::Neg => match layout.ty.kind() {
585 ty::Int(IntTy::I128) => {
586 // FIXME remove this case once ineg.i128 works
588 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
589 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
591 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
592 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
593 _ => unreachable!("un op Neg for {:?}", layout.ty),
596 lval.write_cvalue(fx, res);
599 CastKind::Pointer(PointerCast::ReifyFnPointer),
603 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
604 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
605 match *from_ty.kind() {
606 ty::FnDef(def_id, substs) => {
607 let func_ref = fx.get_function_ref(
608 Instance::resolve_for_fn_ptr(
610 ParamEnv::reveal_all(),
615 .polymorphize(fx.tcx),
617 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
618 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
620 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
624 CastKind::Pointer(PointerCast::UnsafeFnPointer),
629 CastKind::Pointer(PointerCast::MutToConstPointer),
634 CastKind::Pointer(PointerCast::ArrayToPointer),
638 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
639 let operand = codegen_operand(fx, operand);
640 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
644 | CastKind::PointerExposeAddress
645 | CastKind::PointerFromExposedAddress,
649 let operand = codegen_operand(fx, operand);
650 let from_ty = operand.layout().ty;
651 let to_ty = fx.monomorphize(to_ty);
653 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
654 ty.builtin_deref(true)
655 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
656 has_ptr_meta(fx.tcx, pointee_ty)
661 if is_fat_ptr(fx, from_ty) {
662 if is_fat_ptr(fx, to_ty) {
663 // fat-ptr -> fat-ptr
664 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
666 // fat-ptr -> thin-ptr
667 let (ptr, _extra) = operand.load_scalar_pair(fx);
668 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
671 let to_clif_ty = fx.clif_type(to_ty).unwrap();
672 let from = operand.load_scalar(fx);
674 let res = clif_int_or_float_cast(
681 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
685 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
689 let operand = codegen_operand(fx, operand);
690 match *operand.layout().ty.kind() {
691 ty::Closure(def_id, substs) => {
692 let instance = Instance::resolve_closure(
696 ty::ClosureKind::FnOnce,
698 .expect("failed to normalize and resolve closure during codegen")
699 .polymorphize(fx.tcx);
700 let func_ref = fx.get_function_ref(instance);
701 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
702 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
704 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
707 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
708 let operand = codegen_operand(fx, operand);
709 operand.unsize_value(fx, lval);
711 Rvalue::Discriminant(place) => {
712 let place = codegen_place(fx, place);
713 let value = place.to_cvalue(fx);
715 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
716 lval.write_cvalue(fx, discr);
718 Rvalue::Repeat(ref operand, times) => {
719 let operand = codegen_operand(fx, operand);
722 .eval(fx.tcx, ParamEnv::reveal_all())
724 .try_to_bits(fx.tcx.data_layout.pointer_size)
726 if operand.layout().size.bytes() == 0 {
727 // Do nothing for ZST's
728 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
729 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
730 // FIXME use emit_small_memset where possible
731 let addr = lval.to_ptr().get_addr(fx);
732 let val = operand.load_scalar(fx);
733 fx.bcx.call_memset(fx.target_config, addr, val, times);
735 let loop_block = fx.bcx.create_block();
736 let loop_block2 = fx.bcx.create_block();
737 let done_block = fx.bcx.create_block();
738 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
739 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
740 fx.bcx.ins().jump(loop_block, &[zero]);
742 fx.bcx.switch_to_block(loop_block);
743 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
744 fx.bcx.ins().brnz(done, done_block, &[]);
745 fx.bcx.ins().jump(loop_block2, &[]);
747 fx.bcx.switch_to_block(loop_block2);
748 let to = lval.place_index(fx, index);
749 to.write_cvalue(fx, operand);
750 let index = fx.bcx.ins().iadd_imm(index, 1);
751 fx.bcx.ins().jump(loop_block, &[index]);
753 fx.bcx.switch_to_block(done_block);
757 Rvalue::Len(place) => {
758 let place = codegen_place(fx, place);
759 let usize_layout = fx.layout_of(fx.tcx.types.usize);
760 let len = codegen_array_len(fx, place);
761 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
763 Rvalue::ShallowInitBox(ref operand, content_ty) => {
764 let content_ty = fx.monomorphize(content_ty);
765 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
766 let operand = codegen_operand(fx, operand);
767 let operand = operand.load_scalar(fx);
768 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
770 Rvalue::NullaryOp(null_op, ty) => {
774 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
776 let layout = fx.layout_of(fx.monomorphize(ty));
777 let val = match null_op {
778 NullOp::SizeOf => layout.size.bytes(),
779 NullOp::AlignOf => layout.align.abi.bytes(),
781 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
782 lval.write_cvalue(fx, val);
784 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
785 AggregateKind::Array(_ty) => {
786 for (i, operand) in operands.iter().enumerate() {
787 let operand = codegen_operand(fx, operand);
788 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
789 let to = lval.place_index(fx, index);
790 to.write_cvalue(fx, operand);
793 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
797 StatementKind::StorageLive(_)
798 | StatementKind::StorageDead(_)
799 | StatementKind::Deinit(_)
801 | StatementKind::FakeRead(..)
802 | StatementKind::Retag { .. }
803 | StatementKind::AscribeUserType(..) => {}
805 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
806 StatementKind::CopyNonOverlapping(inner) => {
807 let dst = codegen_operand(fx, &inner.dst);
810 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
811 .expect("Expected pointer");
812 let dst = dst.load_scalar(fx);
813 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
814 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
815 let elem_size: u64 = pointee.size.bytes();
817 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
818 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
823 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
824 match *place.layout().ty.kind() {
825 ty::Array(_elem_ty, len) => {
826 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
827 fx.bcx.ins().iconst(fx.pointer_type, len)
829 ty::Slice(_elem_ty) => {
830 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
832 _ => bug!("Rvalue::Len({:?})", place),
836 pub(crate) fn codegen_place<'tcx>(
837 fx: &mut FunctionCx<'_, '_, 'tcx>,
840 let mut cplace = fx.get_local_place(place.local);
842 for elem in place.projection {
844 PlaceElem::Deref => {
845 cplace = cplace.place_deref(fx);
847 PlaceElem::OpaqueCast(ty) => cplace = cplace.place_opaque_cast(fx, ty),
848 PlaceElem::Field(field, _ty) => {
849 cplace = cplace.place_field(fx, field);
851 PlaceElem::Index(local) => {
852 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
853 cplace = cplace.place_index(fx, index);
855 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
856 let offset: u64 = offset;
857 let index = if !from_end {
858 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
860 let len = codegen_array_len(fx, cplace);
861 fx.bcx.ins().iadd_imm(len, -(offset as i64))
863 cplace = cplace.place_index(fx, index);
865 PlaceElem::Subslice { from, to, from_end } => {
866 // These indices are generated by slice patterns.
867 // slice[from:-to] in Python terms.
869 let from: u64 = from;
872 match cplace.layout().ty.kind() {
873 ty::Array(elem_ty, _len) => {
874 assert!(!from_end, "array subslices are never `from_end`");
875 let elem_layout = fx.layout_of(*elem_ty);
876 let ptr = cplace.to_ptr();
877 cplace = CPlace::for_ptr(
878 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
879 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
882 ty::Slice(elem_ty) => {
883 assert!(from_end, "slice subslices should be `from_end`");
884 let elem_layout = fx.layout_of(*elem_ty);
885 let (ptr, len) = cplace.to_ptr_maybe_unsized();
886 let len = len.unwrap();
887 cplace = CPlace::for_ptr_with_extra(
888 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
889 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
896 PlaceElem::Downcast(_adt_def, variant) => {
897 cplace = cplace.downcast_variant(fx, variant);
905 pub(crate) fn codegen_operand<'tcx>(
906 fx: &mut FunctionCx<'_, '_, 'tcx>,
907 operand: &Operand<'tcx>,
910 Operand::Move(place) | Operand::Copy(place) => {
911 let cplace = codegen_place(fx, *place);
914 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
918 pub(crate) fn codegen_panic<'tcx>(
919 fx: &mut FunctionCx<'_, '_, 'tcx>,
921 source_info: mir::SourceInfo,
923 let location = fx.get_caller_location(source_info).load_scalar(fx);
925 let msg_ptr = fx.anonymous_str(msg_str);
926 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
927 let args = [msg_ptr, msg_len, location];
929 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
932 pub(crate) fn codegen_panic_inner<'tcx>(
933 fx: &mut FunctionCx<'_, '_, 'tcx>,
934 lang_item: rustc_hir::LangItem,
939 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
941 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
942 let symbol_name = fx.tcx.symbol_name(instance).name;
947 AbiParam::new(fx.pointer_type),
948 AbiParam::new(fx.pointer_type),
949 AbiParam::new(fx.pointer_type),
955 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);