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(
179 tcx.sess.time("define function", || {
180 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
181 module.define_function(func_id, context).unwrap()
184 // Write optimized function to file for debugging
185 crate::pretty_clif::write_clif_file(
194 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
195 crate::pretty_clif::write_ir_file(
197 || format!("{}.vcode", tcx.symbol_name(instance).name),
198 |file| file.write_all(disasm.as_bytes()),
202 // Define debuginfo for function
203 let isa = module.isa();
204 let debug_context = &mut cx.debug_context;
205 let unwind_context = &mut cx.unwind_context;
206 tcx.sess.time("generate debug info", || {
207 if let Some(debug_context) = debug_context {
208 debug_context.define_function(
218 unwind_context.add_function(func_id, &context, isa);
222 pub(crate) fn verify_func(
224 writer: &crate::pretty_clif::CommentWriter,
227 tcx.sess.time("verify clif ir", || {
228 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
229 match cranelift_codegen::verify_function(&func, &flags) {
232 tcx.sess.err(&format!("{:?}", err));
233 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
235 Some(Box::new(writer)),
238 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
244 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
245 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
246 let block = fx.get_block(bb);
247 fx.bcx.switch_to_block(block);
249 if bb_data.is_cleanup {
250 // Unwinding after panicking is not supported
253 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
254 // so for cleanup blocks.
258 for stmt in &bb_data.statements {
259 fx.set_debug_loc(stmt.source_info);
260 codegen_stmt(fx, block, stmt);
263 if fx.clif_comments.enabled() {
264 let mut terminator_head = "\n".to_string();
265 with_no_trimmed_paths!({
266 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
268 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
269 fx.add_comment(inst, terminator_head);
272 let source_info = bb_data.terminator().source_info;
273 fx.set_debug_loc(source_info);
275 match &bb_data.terminator().kind {
276 TerminatorKind::Goto { target } => {
277 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
278 let mut can_immediately_return = true;
279 for stmt in &fx.mir[*target].statements {
280 if let StatementKind::StorageDead(_) = stmt.kind {
282 // FIXME Can sometimes happen, see rust-lang/rust#70531
283 can_immediately_return = false;
288 if can_immediately_return {
289 crate::abi::codegen_return(fx);
294 let block = fx.get_block(*target);
295 fx.bcx.ins().jump(block, &[]);
297 TerminatorKind::Return => {
298 crate::abi::codegen_return(fx);
300 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
301 if !fx.tcx.sess.overflow_checks() {
302 if let mir::AssertKind::OverflowNeg(_) = *msg {
303 let target = fx.get_block(*target);
304 fx.bcx.ins().jump(target, &[]);
308 let cond = codegen_operand(fx, cond).load_scalar(fx);
310 let target = fx.get_block(*target);
311 let failure = fx.bcx.create_block();
312 fx.bcx.set_cold_block(failure);
315 fx.bcx.ins().brz(cond, failure, &[]);
317 fx.bcx.ins().brnz(cond, failure, &[]);
319 fx.bcx.ins().jump(target, &[]);
321 fx.bcx.switch_to_block(failure);
325 AssertKind::BoundsCheck { ref len, ref index } => {
326 let len = codegen_operand(fx, len).load_scalar(fx);
327 let index = codegen_operand(fx, index).load_scalar(fx);
328 let location = fx.get_caller_location(source_info).load_scalar(fx);
332 rustc_hir::LangItem::PanicBoundsCheck,
333 &[index, len, location],
338 let msg_str = msg.description();
339 codegen_panic(fx, msg_str, source_info);
344 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
345 let discr = codegen_operand(fx, discr).load_scalar(fx);
347 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
348 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
350 assert_eq!(targets.iter().count(), 1);
351 let (then_value, then_block) = targets.iter().next().unwrap();
352 let then_block = fx.get_block(then_block);
353 let else_block = fx.get_block(targets.otherwise());
354 let test_zero = match then_value {
357 _ => unreachable!("{:?}", targets),
360 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
361 let (discr, is_inverted) =
362 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
363 let test_zero = if is_inverted { !test_zero } else { test_zero };
364 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
365 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
366 &fx.bcx, discr, test_zero,
369 fx.bcx.ins().jump(then_block, &[]);
371 fx.bcx.ins().jump(else_block, &[]);
375 fx.bcx.ins().brz(discr, then_block, &[]);
376 fx.bcx.ins().jump(else_block, &[]);
378 fx.bcx.ins().brnz(discr, then_block, &[]);
379 fx.bcx.ins().jump(else_block, &[]);
383 let mut switch = ::cranelift_frontend::Switch::new();
384 for (value, block) in targets.iter() {
385 let block = fx.get_block(block);
386 switch.set_entry(value, block);
388 let otherwise_block = fx.get_block(targets.otherwise());
389 switch.emit(&mut fx.bcx, discr, otherwise_block);
392 TerminatorKind::Call {
401 fx.tcx.sess.time("codegen call", || {
402 crate::abi::codegen_terminator_call(
404 mir::SourceInfo { span: *fn_span, ..source_info },
412 TerminatorKind::InlineAsm {
420 if options.contains(InlineAsmOptions::MAY_UNWIND) {
421 fx.tcx.sess.span_fatal(
423 "cranelift doesn't support unwinding from inline assembly.",
427 crate::inline_asm::codegen_inline_asm(
436 Some(destination) => {
437 let destination_block = fx.get_block(destination);
438 fx.bcx.ins().jump(destination_block, &[]);
441 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
445 TerminatorKind::Resume | TerminatorKind::Abort => {
446 // FIXME implement unwinding
447 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
449 TerminatorKind::Unreachable => {
450 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
452 TerminatorKind::Yield { .. }
453 | TerminatorKind::FalseEdge { .. }
454 | TerminatorKind::FalseUnwind { .. }
455 | TerminatorKind::DropAndReplace { .. }
456 | TerminatorKind::GeneratorDrop => {
457 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
459 TerminatorKind::Drop { place, target, unwind: _ } => {
460 let drop_place = codegen_place(fx, *place);
461 crate::abi::codegen_drop(fx, source_info, drop_place);
463 let target_block = fx.get_block(*target);
464 fx.bcx.ins().jump(target_block, &[]);
469 fx.bcx.seal_all_blocks();
473 fn codegen_stmt<'tcx>(
474 fx: &mut FunctionCx<'_, '_, 'tcx>,
475 #[allow(unused_variables)] cur_block: Block,
476 stmt: &Statement<'tcx>,
478 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
480 fx.set_debug_loc(stmt.source_info);
482 #[cfg(any())] // This is never true
484 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
486 if fx.clif_comments.enabled() {
487 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
488 fx.add_comment(inst, format!("{:?}", stmt));
494 StatementKind::SetDiscriminant { place, variant_index } => {
495 let place = codegen_place(fx, **place);
496 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
498 StatementKind::Assign(to_place_and_rval) => {
499 let lval = codegen_place(fx, to_place_and_rval.0);
500 let dest_layout = lval.layout();
501 match to_place_and_rval.1 {
502 Rvalue::Use(ref operand) => {
503 let val = codegen_operand(fx, operand);
504 lval.write_cvalue(fx, val);
506 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
507 let place = codegen_place(fx, place);
508 let ref_ = place.place_ref(fx, lval.layout());
509 lval.write_cvalue(fx, ref_);
511 Rvalue::ThreadLocalRef(def_id) => {
512 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
513 lval.write_cvalue(fx, val);
515 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
516 let lhs = codegen_operand(fx, &lhs_rhs.0);
517 let rhs = codegen_operand(fx, &lhs_rhs.1);
519 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
520 lval.write_cvalue(fx, res);
522 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
523 let lhs = codegen_operand(fx, &lhs_rhs.0);
524 let rhs = codegen_operand(fx, &lhs_rhs.1);
526 let res = if !fx.tcx.sess.overflow_checks() {
528 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
529 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
530 CValue::by_val_pair(val, is_overflow, lval.layout())
532 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
535 lval.write_cvalue(fx, res);
537 Rvalue::UnaryOp(un_op, ref operand) => {
538 let operand = codegen_operand(fx, operand);
539 let layout = operand.layout();
540 let val = operand.load_scalar(fx);
541 let res = match un_op {
542 UnOp::Not => match layout.ty.kind() {
544 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
545 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
547 ty::Uint(_) | ty::Int(_) => {
548 CValue::by_val(fx.bcx.ins().bnot(val), layout)
550 _ => unreachable!("un op Not for {:?}", layout.ty),
552 UnOp::Neg => match layout.ty.kind() {
553 ty::Int(IntTy::I128) => {
554 // FIXME remove this case once ineg.i128 works
556 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
557 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
559 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
560 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
561 _ => unreachable!("un op Neg for {:?}", layout.ty),
564 lval.write_cvalue(fx, res);
567 CastKind::Pointer(PointerCast::ReifyFnPointer),
571 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
572 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
573 match *from_ty.kind() {
574 ty::FnDef(def_id, substs) => {
575 let func_ref = fx.get_function_ref(
576 Instance::resolve_for_fn_ptr(
578 ParamEnv::reveal_all(),
583 .polymorphize(fx.tcx),
585 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
586 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
588 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
592 CastKind::Pointer(PointerCast::UnsafeFnPointer),
597 CastKind::Pointer(PointerCast::MutToConstPointer),
602 CastKind::Pointer(PointerCast::ArrayToPointer),
606 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
607 let operand = codegen_operand(fx, operand);
608 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
612 | CastKind::PointerExposeAddress
613 | CastKind::PointerFromExposedAddress,
617 let operand = codegen_operand(fx, operand);
618 let from_ty = operand.layout().ty;
619 let to_ty = fx.monomorphize(to_ty);
621 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
622 ty.builtin_deref(true)
623 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
624 has_ptr_meta(fx.tcx, pointee_ty)
629 if is_fat_ptr(fx, from_ty) {
630 if is_fat_ptr(fx, to_ty) {
631 // fat-ptr -> fat-ptr
632 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
634 // fat-ptr -> thin-ptr
635 let (ptr, _extra) = operand.load_scalar_pair(fx);
636 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
638 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
639 // enum -> discriminant value
640 assert!(adt_def.is_enum());
642 ty::Uint(_) | ty::Int(_) => {}
643 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
645 let to_clif_ty = fx.clif_type(to_ty).unwrap();
647 let discriminant = crate::discriminant::codegen_get_discriminant(
650 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
654 let res = crate::cast::clif_intcast(
660 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
662 let to_clif_ty = fx.clif_type(to_ty).unwrap();
663 let from = operand.load_scalar(fx);
665 let res = clif_int_or_float_cast(
672 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
676 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
680 let operand = codegen_operand(fx, operand);
681 match *operand.layout().ty.kind() {
682 ty::Closure(def_id, substs) => {
683 let instance = Instance::resolve_closure(
687 ty::ClosureKind::FnOnce,
689 .polymorphize(fx.tcx);
690 let func_ref = fx.get_function_ref(instance);
691 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
692 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
694 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
697 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
698 let operand = codegen_operand(fx, operand);
699 operand.unsize_value(fx, lval);
701 Rvalue::Discriminant(place) => {
702 let place = codegen_place(fx, place);
703 let value = place.to_cvalue(fx);
705 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
706 lval.write_cvalue(fx, discr);
708 Rvalue::Repeat(ref operand, times) => {
709 let operand = codegen_operand(fx, operand);
712 .eval(fx.tcx, ParamEnv::reveal_all())
714 .try_to_bits(fx.tcx.data_layout.pointer_size)
716 if operand.layout().size.bytes() == 0 {
717 // Do nothing for ZST's
718 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
719 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
720 // FIXME use emit_small_memset where possible
721 let addr = lval.to_ptr().get_addr(fx);
722 let val = operand.load_scalar(fx);
723 fx.bcx.call_memset(fx.target_config, addr, val, times);
725 let loop_block = fx.bcx.create_block();
726 let loop_block2 = fx.bcx.create_block();
727 let done_block = fx.bcx.create_block();
728 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
729 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
730 fx.bcx.ins().jump(loop_block, &[zero]);
732 fx.bcx.switch_to_block(loop_block);
733 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
734 fx.bcx.ins().brnz(done, done_block, &[]);
735 fx.bcx.ins().jump(loop_block2, &[]);
737 fx.bcx.switch_to_block(loop_block2);
738 let to = lval.place_index(fx, index);
739 to.write_cvalue(fx, operand);
740 let index = fx.bcx.ins().iadd_imm(index, 1);
741 fx.bcx.ins().jump(loop_block, &[index]);
743 fx.bcx.switch_to_block(done_block);
747 Rvalue::Len(place) => {
748 let place = codegen_place(fx, place);
749 let usize_layout = fx.layout_of(fx.tcx.types.usize);
750 let len = codegen_array_len(fx, place);
751 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
753 Rvalue::ShallowInitBox(ref operand, content_ty) => {
754 let content_ty = fx.monomorphize(content_ty);
755 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
756 let operand = codegen_operand(fx, operand);
757 let operand = operand.load_scalar(fx);
758 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
760 Rvalue::NullaryOp(null_op, ty) => {
764 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
766 let layout = fx.layout_of(fx.monomorphize(ty));
767 let val = match null_op {
768 NullOp::SizeOf => layout.size.bytes(),
769 NullOp::AlignOf => layout.align.abi.bytes(),
771 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
772 lval.write_cvalue(fx, val);
774 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
775 AggregateKind::Array(_ty) => {
776 for (i, operand) in operands.iter().enumerate() {
777 let operand = codegen_operand(fx, operand);
778 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
779 let to = lval.place_index(fx, index);
780 to.write_cvalue(fx, operand);
783 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
787 StatementKind::StorageLive(_)
788 | StatementKind::StorageDead(_)
789 | StatementKind::Deinit(_)
791 | StatementKind::FakeRead(..)
792 | StatementKind::Retag { .. }
793 | StatementKind::AscribeUserType(..) => {}
795 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
796 StatementKind::CopyNonOverlapping(inner) => {
797 let dst = codegen_operand(fx, &inner.dst);
800 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
801 .expect("Expected pointer");
802 let dst = dst.load_scalar(fx);
803 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
804 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
805 let elem_size: u64 = pointee.size.bytes();
807 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
808 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
813 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
814 match *place.layout().ty.kind() {
815 ty::Array(_elem_ty, len) => {
816 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
817 fx.bcx.ins().iconst(fx.pointer_type, len)
819 ty::Slice(_elem_ty) => {
820 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
822 _ => bug!("Rvalue::Len({:?})", place),
826 pub(crate) fn codegen_place<'tcx>(
827 fx: &mut FunctionCx<'_, '_, 'tcx>,
830 let mut cplace = fx.get_local_place(place.local);
832 for elem in place.projection {
834 PlaceElem::Deref => {
835 cplace = cplace.place_deref(fx);
837 PlaceElem::Field(field, _ty) => {
838 cplace = cplace.place_field(fx, field);
840 PlaceElem::Index(local) => {
841 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
842 cplace = cplace.place_index(fx, index);
844 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
845 let offset: u64 = offset;
846 let index = if !from_end {
847 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
849 let len = codegen_array_len(fx, cplace);
850 fx.bcx.ins().iadd_imm(len, -(offset as i64))
852 cplace = cplace.place_index(fx, index);
854 PlaceElem::Subslice { from, to, from_end } => {
855 // These indices are generated by slice patterns.
856 // slice[from:-to] in Python terms.
858 let from: u64 = from;
861 match cplace.layout().ty.kind() {
862 ty::Array(elem_ty, _len) => {
863 assert!(!from_end, "array subslices are never `from_end`");
864 let elem_layout = fx.layout_of(*elem_ty);
865 let ptr = cplace.to_ptr();
866 cplace = CPlace::for_ptr(
867 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
868 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
871 ty::Slice(elem_ty) => {
872 assert!(from_end, "slice subslices should be `from_end`");
873 let elem_layout = fx.layout_of(*elem_ty);
874 let (ptr, len) = cplace.to_ptr_maybe_unsized();
875 let len = len.unwrap();
876 cplace = CPlace::for_ptr_with_extra(
877 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
878 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
885 PlaceElem::Downcast(_adt_def, variant) => {
886 cplace = cplace.downcast_variant(fx, variant);
894 pub(crate) fn codegen_operand<'tcx>(
895 fx: &mut FunctionCx<'_, '_, 'tcx>,
896 operand: &Operand<'tcx>,
899 Operand::Move(place) | Operand::Copy(place) => {
900 let cplace = codegen_place(fx, *place);
903 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
907 pub(crate) fn codegen_panic<'tcx>(
908 fx: &mut FunctionCx<'_, '_, 'tcx>,
910 source_info: mir::SourceInfo,
912 let location = fx.get_caller_location(source_info).load_scalar(fx);
914 let msg_ptr = fx.anonymous_str(msg_str);
915 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
916 let args = [msg_ptr, msg_len, location];
918 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
921 pub(crate) fn codegen_panic_inner<'tcx>(
922 fx: &mut FunctionCx<'_, '_, 'tcx>,
923 lang_item: rustc_hir::LangItem,
928 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
930 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
931 let symbol_name = fx.tcx.symbol_name(instance).name;
936 AbiParam::new(fx.pointer_type),
937 AbiParam::new(fx.pointer_type),
938 AbiParam::new(fx.pointer_type),
944 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);