1 //! Codegen of a single function
3 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiExt;
7 use rustc_target::abi::call::FnAbi;
9 use crate::constant::ConstantCx;
10 use crate::prelude::*;
12 pub(crate) fn codegen_fn<'tcx>(
13 cx: &mut crate::CodegenCx<'tcx>,
14 module: &mut dyn Module,
15 instance: Instance<'tcx>,
20 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
21 debug_assert!(!instance.substs.needs_infer());
23 let mir = tcx.instance_mir(instance.def);
26 let symbol_name = tcx.symbol_name(instance);
27 let sig = get_function_sig(tcx, module.isa().triple(), instance);
28 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
30 cx.cached_context.clear();
32 // Make the FunctionBuilder
33 let mut func_ctx = FunctionBuilderContext::new();
34 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
35 func.name = ExternalName::user(0, func_id.as_u32());
37 func.collect_debug_info();
39 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
42 let start_block = bcx.create_block();
43 let block_map: IndexVec<BasicBlock, Block> =
44 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
47 let pointer_type = module.target_config().pointer_type();
48 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
50 let mut fx = FunctionCx {
55 vtables: FxHashMap::default(),
56 constants_cx: ConstantCx::new(),
61 fn_abi: Some(FnAbi::of_instance(&RevealAllLayoutCx(tcx), instance, &[])),
65 local_map: IndexVec::with_capacity(mir.local_decls.len()),
66 caller_location: None, // set by `codegen_fn_prelude`
69 source_info_set: indexmap::IndexSet::new(),
75 let arg_uninhabited = fx
78 .any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
80 if !crate::constant::check_constants(&mut fx) {
81 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
82 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
83 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
84 } else if arg_uninhabited {
85 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
86 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
87 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
89 tcx.sess.time("codegen clif ir", || {
91 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
92 codegen_fn_content(&mut fx);
96 // Recover all necessary data from fx, before accessing func will prevent future access to it.
97 let instance = fx.instance;
98 let mut clif_comments = fx.clif_comments;
99 let source_info_set = fx.source_info_set;
100 let local_map = fx.local_map;
102 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
104 // Store function in context
105 let context = &mut cx.cached_context;
108 crate::pretty_clif::write_clif_file(tcx, "unopt", None, instance, &context, &clif_comments);
111 verify_func(tcx, &clif_comments, &context.func);
113 // Perform rust specific optimizations
114 tcx.sess.time("optimize clif ir", || {
115 crate::optimize::optimize_function(tcx, instance, context, &mut clif_comments);
118 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
119 // instruction, which doesn't have an encoding.
120 context.compute_cfg();
121 context.compute_domtree();
122 context.eliminate_unreachable_code(module.isa()).unwrap();
123 context.dce(module.isa()).unwrap();
124 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
125 // invalidate it when it would change.
126 context.domtree.clear();
128 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
131 tcx.sess.time("define function", || {
133 .define_function(func_id, context, &mut NullTrapSink {}, &mut NullStackMapSink {})
137 // Write optimized function to file for debugging
138 crate::pretty_clif::write_clif_file(
147 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
148 crate::pretty_clif::write_ir_file(
150 || format!("{}.vcode", tcx.symbol_name(instance).name),
151 |file| file.write_all(disasm.as_bytes()),
155 // Define debuginfo for function
156 let isa = module.isa();
157 let debug_context = &mut cx.debug_context;
158 let unwind_context = &mut cx.unwind_context;
159 tcx.sess.time("generate debug info", || {
160 if let Some(debug_context) = debug_context {
161 debug_context.define_function(
171 unwind_context.add_function(func_id, &context, isa);
174 // Clear context to make it usable for the next function
178 pub(crate) fn verify_func(
180 writer: &crate::pretty_clif::CommentWriter,
183 tcx.sess.time("verify clif ir", || {
184 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
185 match cranelift_codegen::verify_function(&func, &flags) {
188 tcx.sess.err(&format!("{:?}", err));
189 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
192 Some(Box::new(writer)),
195 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
201 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
202 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
203 let block = fx.get_block(bb);
204 fx.bcx.switch_to_block(block);
206 if bb_data.is_cleanup {
207 // Unwinding after panicking is not supported
210 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
211 // so for cleanup blocks.
215 for stmt in &bb_data.statements {
216 fx.set_debug_loc(stmt.source_info);
217 codegen_stmt(fx, block, stmt);
220 if fx.clif_comments.enabled() {
221 let mut terminator_head = "\n".to_string();
222 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
223 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
224 fx.add_comment(inst, terminator_head);
227 fx.set_debug_loc(bb_data.terminator().source_info);
229 match &bb_data.terminator().kind {
230 TerminatorKind::Goto { target } => {
231 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
232 let mut can_immediately_return = true;
233 for stmt in &fx.mir[*target].statements {
234 if let StatementKind::StorageDead(_) = stmt.kind {
236 // FIXME Can sometimes happen, see rust-lang/rust#70531
237 can_immediately_return = false;
242 if can_immediately_return {
243 crate::abi::codegen_return(fx);
248 let block = fx.get_block(*target);
249 fx.bcx.ins().jump(block, &[]);
251 TerminatorKind::Return => {
252 crate::abi::codegen_return(fx);
254 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
255 if !fx.tcx.sess.overflow_checks() {
256 if let mir::AssertKind::OverflowNeg(_) = *msg {
257 let target = fx.get_block(*target);
258 fx.bcx.ins().jump(target, &[]);
262 let cond = codegen_operand(fx, cond).load_scalar(fx);
264 let target = fx.get_block(*target);
265 let failure = fx.bcx.create_block();
266 // FIXME Mark failure block as cold once Cranelift supports it
269 fx.bcx.ins().brz(cond, failure, &[]);
271 fx.bcx.ins().brnz(cond, failure, &[]);
273 fx.bcx.ins().jump(target, &[]);
275 fx.bcx.switch_to_block(failure);
279 AssertKind::BoundsCheck { ref len, ref index } => {
280 let len = codegen_operand(fx, len).load_scalar(fx);
281 let index = codegen_operand(fx, index).load_scalar(fx);
283 .get_caller_location(bb_data.terminator().source_info.span)
288 rustc_hir::LangItem::PanicBoundsCheck,
289 &[index, len, location],
290 bb_data.terminator().source_info.span,
294 let msg_str = msg.description();
295 codegen_panic(fx, msg_str, bb_data.terminator().source_info.span);
300 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
301 let discr = codegen_operand(fx, discr).load_scalar(fx);
303 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
304 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
306 assert_eq!(targets.iter().count(), 1);
307 let (then_value, then_block) = targets.iter().next().unwrap();
308 let then_block = fx.get_block(then_block);
309 let else_block = fx.get_block(targets.otherwise());
310 let test_zero = match then_value {
313 _ => unreachable!("{:?}", targets),
316 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
317 let (discr, is_inverted) =
318 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
319 let test_zero = if is_inverted { !test_zero } else { test_zero };
320 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
322 crate::optimize::peephole::make_branchable_value(&mut fx.bcx, discr);
323 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
324 &fx.bcx, discr, test_zero,
327 fx.bcx.ins().jump(then_block, &[]);
329 fx.bcx.ins().jump(else_block, &[]);
333 fx.bcx.ins().brz(discr, then_block, &[]);
334 fx.bcx.ins().jump(else_block, &[]);
336 fx.bcx.ins().brnz(discr, then_block, &[]);
337 fx.bcx.ins().jump(else_block, &[]);
341 let mut switch = ::cranelift_frontend::Switch::new();
342 for (value, block) in targets.iter() {
343 let block = fx.get_block(block);
344 switch.set_entry(value, block);
346 let otherwise_block = fx.get_block(targets.otherwise());
347 switch.emit(&mut fx.bcx, discr, otherwise_block);
350 TerminatorKind::Call {
358 fx.tcx.sess.time("codegen call", || {
359 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
362 TerminatorKind::InlineAsm {
369 crate::inline_asm::codegen_inline_asm(
371 bb_data.terminator().source_info.span,
378 Some(destination) => {
379 let destination_block = fx.get_block(destination);
380 fx.bcx.ins().jump(destination_block, &[]);
383 crate::trap::trap_unreachable(
385 "[corruption] Returned from noreturn inline asm",
390 TerminatorKind::Resume | TerminatorKind::Abort => {
391 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
393 TerminatorKind::Unreachable => {
394 trap_unreachable(fx, "[corruption] Hit unreachable code.");
396 TerminatorKind::Yield { .. }
397 | TerminatorKind::FalseEdge { .. }
398 | TerminatorKind::FalseUnwind { .. }
399 | TerminatorKind::DropAndReplace { .. }
400 | TerminatorKind::GeneratorDrop => {
401 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
403 TerminatorKind::Drop { place, target, unwind: _ } => {
404 let drop_place = codegen_place(fx, *place);
405 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
407 let target_block = fx.get_block(*target);
408 fx.bcx.ins().jump(target_block, &[]);
413 fx.bcx.seal_all_blocks();
417 fn codegen_stmt<'tcx>(
418 fx: &mut FunctionCx<'_, '_, 'tcx>,
419 #[allow(unused_variables)] cur_block: Block,
420 stmt: &Statement<'tcx>,
422 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
424 fx.set_debug_loc(stmt.source_info);
428 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
430 if fx.clif_comments.enabled() {
431 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
432 fx.add_comment(inst, format!("{:?}", stmt));
438 StatementKind::SetDiscriminant { place, variant_index } => {
439 let place = codegen_place(fx, **place);
440 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
442 StatementKind::Assign(to_place_and_rval) => {
443 let lval = codegen_place(fx, to_place_and_rval.0);
444 let dest_layout = lval.layout();
445 match to_place_and_rval.1 {
446 Rvalue::Use(ref operand) => {
447 let val = codegen_operand(fx, operand);
448 lval.write_cvalue(fx, val);
450 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
451 let place = codegen_place(fx, place);
452 let ref_ = place.place_ref(fx, lval.layout());
453 lval.write_cvalue(fx, ref_);
455 Rvalue::ThreadLocalRef(def_id) => {
456 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
457 lval.write_cvalue(fx, val);
459 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
460 let lhs = codegen_operand(fx, &lhs_rhs.0);
461 let rhs = codegen_operand(fx, &lhs_rhs.1);
463 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
464 lval.write_cvalue(fx, res);
466 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
467 let lhs = codegen_operand(fx, &lhs_rhs.0);
468 let rhs = codegen_operand(fx, &lhs_rhs.1);
470 let res = if !fx.tcx.sess.overflow_checks() {
472 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
473 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
474 CValue::by_val_pair(val, is_overflow, lval.layout())
476 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
479 lval.write_cvalue(fx, res);
481 Rvalue::UnaryOp(un_op, ref operand) => {
482 let operand = codegen_operand(fx, operand);
483 let layout = operand.layout();
484 let val = operand.load_scalar(fx);
485 let res = match un_op {
486 UnOp::Not => match layout.ty.kind() {
488 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
489 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
491 ty::Uint(_) | ty::Int(_) => {
492 CValue::by_val(fx.bcx.ins().bnot(val), layout)
494 _ => unreachable!("un op Not for {:?}", layout.ty),
496 UnOp::Neg => match layout.ty.kind() {
497 ty::Int(IntTy::I128) => {
498 // FIXME remove this case once ineg.i128 works
500 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
501 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
503 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
504 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
505 _ => unreachable!("un op Neg for {:?}", layout.ty),
508 lval.write_cvalue(fx, res);
511 CastKind::Pointer(PointerCast::ReifyFnPointer),
515 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
516 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
517 match *from_ty.kind() {
518 ty::FnDef(def_id, substs) => {
519 let func_ref = fx.get_function_ref(
520 Instance::resolve_for_fn_ptr(
522 ParamEnv::reveal_all(),
527 .polymorphize(fx.tcx),
529 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
530 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
532 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
536 CastKind::Pointer(PointerCast::UnsafeFnPointer),
541 CastKind::Pointer(PointerCast::MutToConstPointer),
546 CastKind::Pointer(PointerCast::ArrayToPointer),
550 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
551 let operand = codegen_operand(fx, operand);
552 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
554 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
555 let operand = codegen_operand(fx, operand);
556 let from_ty = operand.layout().ty;
557 let to_ty = fx.monomorphize(to_ty);
559 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
560 ty.builtin_deref(true)
561 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
562 has_ptr_meta(fx.tcx, pointee_ty)
567 if is_fat_ptr(fx, from_ty) {
568 if is_fat_ptr(fx, to_ty) {
569 // fat-ptr -> fat-ptr
570 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
572 // fat-ptr -> thin-ptr
573 let (ptr, _extra) = operand.load_scalar_pair(fx);
574 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
576 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
577 // enum -> discriminant value
578 assert!(adt_def.is_enum());
580 ty::Uint(_) | ty::Int(_) => {}
581 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
583 let to_clif_ty = fx.clif_type(to_ty).unwrap();
585 let discriminant = crate::discriminant::codegen_get_discriminant(
588 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
592 let res = crate::cast::clif_intcast(
598 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
600 let to_clif_ty = fx.clif_type(to_ty).unwrap();
601 let from = operand.load_scalar(fx);
603 let res = clif_int_or_float_cast(
610 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
614 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
618 let operand = codegen_operand(fx, operand);
619 match *operand.layout().ty.kind() {
620 ty::Closure(def_id, substs) => {
621 let instance = Instance::resolve_closure(
625 ty::ClosureKind::FnOnce,
627 .polymorphize(fx.tcx);
628 let func_ref = fx.get_function_ref(instance);
629 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
630 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
632 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
635 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
636 let operand = codegen_operand(fx, operand);
637 operand.unsize_value(fx, lval);
639 Rvalue::Discriminant(place) => {
640 let place = codegen_place(fx, place);
641 let value = place.to_cvalue(fx);
643 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
644 lval.write_cvalue(fx, discr);
646 Rvalue::Repeat(ref operand, times) => {
647 let operand = codegen_operand(fx, operand);
650 .eval(fx.tcx, ParamEnv::reveal_all())
652 .try_to_bits(fx.tcx.data_layout.pointer_size)
654 if operand.layout().size.bytes() == 0 {
655 // Do nothing for ZST's
656 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
657 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
658 // FIXME use emit_small_memset where possible
659 let addr = lval.to_ptr().get_addr(fx);
660 let val = operand.load_scalar(fx);
661 fx.bcx.call_memset(fx.module.target_config(), addr, val, times);
663 let loop_block = fx.bcx.create_block();
664 let loop_block2 = fx.bcx.create_block();
665 let done_block = fx.bcx.create_block();
666 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
667 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
668 fx.bcx.ins().jump(loop_block, &[zero]);
670 fx.bcx.switch_to_block(loop_block);
671 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
672 fx.bcx.ins().brnz(done, done_block, &[]);
673 fx.bcx.ins().jump(loop_block2, &[]);
675 fx.bcx.switch_to_block(loop_block2);
676 let to = lval.place_index(fx, index);
677 to.write_cvalue(fx, operand);
678 let index = fx.bcx.ins().iadd_imm(index, 1);
679 fx.bcx.ins().jump(loop_block, &[index]);
681 fx.bcx.switch_to_block(done_block);
685 Rvalue::Len(place) => {
686 let place = codegen_place(fx, place);
687 let usize_layout = fx.layout_of(fx.tcx.types.usize);
688 let len = codegen_array_len(fx, place);
689 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
691 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
692 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
693 let content_ty = fx.monomorphize(content_ty);
694 let layout = fx.layout_of(content_ty);
695 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
696 let llalign = fx.bcx.ins().iconst(usize_type, layout.align.abi.bytes() as i64);
697 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
701 match fx.tcx.lang_items().require(rustc_hir::LangItem::ExchangeMalloc) {
706 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
709 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
710 let func_ref = fx.get_function_ref(instance);
711 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
712 let ptr = fx.bcx.inst_results(call)[0];
713 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
715 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
719 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
721 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
723 CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
724 lval.write_cvalue(fx, val);
726 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
727 AggregateKind::Array(_ty) => {
728 for (i, operand) in operands.iter().enumerate() {
729 let operand = codegen_operand(fx, operand);
730 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
731 let to = lval.place_index(fx, index);
732 to.write_cvalue(fx, operand);
735 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
739 StatementKind::StorageLive(_)
740 | StatementKind::StorageDead(_)
742 | StatementKind::FakeRead(..)
743 | StatementKind::Retag { .. }
744 | StatementKind::AscribeUserType(..) => {}
746 StatementKind::LlvmInlineAsm(asm) => {
747 match asm.asm.asm.as_str().trim() {
751 _ => fx.tcx.sess.span_fatal(
752 stmt.source_info.span,
753 "Legacy `llvm_asm!` inline assembly is not supported. \
754 Try using the new `asm!` instead.",
758 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
759 StatementKind::CopyNonOverlapping(inner) => {
760 let dst = codegen_operand(fx, &inner.dst);
763 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
764 .expect("Expected pointer");
765 let dst = dst.load_scalar(fx);
766 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
767 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
768 let elem_size: u64 = pointee.size.bytes();
770 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
771 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, bytes);
776 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
777 match *place.layout().ty.kind() {
778 ty::Array(_elem_ty, len) => {
779 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
780 fx.bcx.ins().iconst(fx.pointer_type, len)
782 ty::Slice(_elem_ty) => {
783 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
785 _ => bug!("Rvalue::Len({:?})", place),
789 pub(crate) fn codegen_place<'tcx>(
790 fx: &mut FunctionCx<'_, '_, 'tcx>,
793 let mut cplace = fx.get_local_place(place.local);
795 for elem in place.projection {
797 PlaceElem::Deref => {
798 cplace = cplace.place_deref(fx);
800 PlaceElem::Field(field, _ty) => {
801 cplace = cplace.place_field(fx, field);
803 PlaceElem::Index(local) => {
804 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
805 cplace = cplace.place_index(fx, index);
807 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
808 let offset: u64 = offset;
809 let index = if !from_end {
810 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
812 let len = codegen_array_len(fx, cplace);
813 fx.bcx.ins().iadd_imm(len, -(offset as i64))
815 cplace = cplace.place_index(fx, index);
817 PlaceElem::Subslice { from, to, from_end } => {
818 // These indices are generated by slice patterns.
819 // slice[from:-to] in Python terms.
821 let from: u64 = from;
824 match cplace.layout().ty.kind() {
825 ty::Array(elem_ty, _len) => {
826 assert!(!from_end, "array subslices are never `from_end`");
827 let elem_layout = fx.layout_of(elem_ty);
828 let ptr = cplace.to_ptr();
829 cplace = CPlace::for_ptr(
830 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
831 fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)),
834 ty::Slice(elem_ty) => {
835 assert!(from_end, "slice subslices should be `from_end`");
836 let elem_layout = fx.layout_of(elem_ty);
837 let (ptr, len) = cplace.to_ptr_maybe_unsized();
838 let len = len.unwrap();
839 cplace = CPlace::for_ptr_with_extra(
840 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
841 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
848 PlaceElem::Downcast(_adt_def, variant) => {
849 cplace = cplace.downcast_variant(fx, variant);
857 pub(crate) fn codegen_operand<'tcx>(
858 fx: &mut FunctionCx<'_, '_, 'tcx>,
859 operand: &Operand<'tcx>,
862 Operand::Move(place) | Operand::Copy(place) => {
863 let cplace = codegen_place(fx, *place);
866 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
870 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
871 let location = fx.get_caller_location(span).load_scalar(fx);
873 let msg_ptr = fx.anonymous_str("assert", msg_str);
874 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
875 let args = [msg_ptr, msg_len, location];
877 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
880 pub(crate) fn codegen_panic_inner<'tcx>(
881 fx: &mut FunctionCx<'_, '_, 'tcx>,
882 lang_item: rustc_hir::LangItem,
887 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
889 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
890 let symbol_name = fx.tcx.symbol_name(instance).name;
895 AbiParam::new(fx.pointer_type),
896 AbiParam::new(fx.pointer_type),
897 AbiParam::new(fx.pointer_type),
903 crate::trap::trap_unreachable(fx, "panic lang item returned");