1 //! Codegen of a single function
3 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
4 use rustc_ast::InlineAsmOptions;
5 use rustc_index::vec::IndexVec;
6 use rustc_middle::ty::adjustment::PointerCast;
7 use rustc_middle::ty::layout::FnAbiOf;
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);
24 let _mir_guard = crate::PrintOnPanic(|| {
25 let mut buf = Vec::new();
26 rustc_middle::mir::write_mir_pretty(tcx, Some(instance.def_id()), &mut buf).unwrap();
27 String::from_utf8_lossy(&buf).into_owned()
31 let symbol_name = tcx.symbol_name(instance);
32 let sig = get_function_sig(tcx, module.isa().triple(), instance);
33 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
35 cx.cached_context.clear();
37 // Make the FunctionBuilder
38 let mut func_ctx = FunctionBuilderContext::new();
39 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
40 func.name = ExternalName::user(0, func_id.as_u32());
42 func.collect_debug_info();
44 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
47 let start_block = bcx.create_block();
48 let block_map: IndexVec<BasicBlock, Block> =
49 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
52 let target_config = module.target_config();
53 let pointer_type = target_config.pointer_type();
54 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
56 let mut fx = FunctionCx {
62 constants_cx: ConstantCx::new(),
67 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
71 local_map: IndexVec::with_capacity(mir.local_decls.len()),
72 caller_location: None, // set by `codegen_fn_prelude`
75 source_info_set: indexmap::IndexSet::new(),
79 let arg_uninhabited = fx
82 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
84 if !crate::constant::check_constants(&mut fx) {
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, "compilation should have been aborted");
88 } else if arg_uninhabited {
89 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
90 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
91 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
93 tcx.sess.time("codegen clif ir", || {
95 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
96 codegen_fn_content(&mut fx);
100 // Recover all necessary data from fx, before accessing func will prevent future access to it.
101 let instance = fx.instance;
102 let mut clif_comments = fx.clif_comments;
103 let source_info_set = fx.source_info_set;
104 let local_map = fx.local_map;
106 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
108 // Store function in context
109 let context = &mut cx.cached_context;
112 crate::pretty_clif::write_clif_file(
122 verify_func(tcx, &clif_comments, &context.func);
124 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
125 // instruction, which doesn't have an encoding.
126 context.compute_cfg();
127 context.compute_domtree();
128 context.eliminate_unreachable_code(module.isa()).unwrap();
129 context.dce(module.isa()).unwrap();
130 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
131 // invalidate it when it would change.
132 context.domtree.clear();
134 // Perform rust specific optimizations
135 tcx.sess.time("optimize clif ir", || {
136 crate::optimize::optimize_function(
146 tcx.sess.time("define function", || {
147 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
149 .define_function(func_id, context, &mut NullTrapSink {}, &mut NullStackMapSink {})
153 // Write optimized function to file for debugging
154 crate::pretty_clif::write_clif_file(
163 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
164 crate::pretty_clif::write_ir_file(
166 || format!("{}.vcode", tcx.symbol_name(instance).name),
167 |file| file.write_all(disasm.as_bytes()),
171 // Define debuginfo for function
172 let isa = module.isa();
173 let debug_context = &mut cx.debug_context;
174 let unwind_context = &mut cx.unwind_context;
175 tcx.sess.time("generate debug info", || {
176 if let Some(debug_context) = debug_context {
177 debug_context.define_function(
187 unwind_context.add_function(func_id, &context, isa);
190 // Clear context to make it usable for the next function
194 pub(crate) fn verify_func(
196 writer: &crate::pretty_clif::CommentWriter,
199 tcx.sess.time("verify clif ir", || {
200 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
201 match cranelift_codegen::verify_function(&func, &flags) {
204 tcx.sess.err(&format!("{:?}", err));
205 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
207 Some(Box::new(writer)),
210 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
216 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
217 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
218 let block = fx.get_block(bb);
219 fx.bcx.switch_to_block(block);
221 if bb_data.is_cleanup {
222 // Unwinding after panicking is not supported
225 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
226 // so for cleanup blocks.
230 for stmt in &bb_data.statements {
231 fx.set_debug_loc(stmt.source_info);
232 codegen_stmt(fx, block, stmt);
235 if fx.clif_comments.enabled() {
236 let mut terminator_head = "\n".to_string();
237 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
238 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
239 fx.add_comment(inst, terminator_head);
242 let source_info = bb_data.terminator().source_info;
243 fx.set_debug_loc(source_info);
245 match &bb_data.terminator().kind {
246 TerminatorKind::Goto { target } => {
247 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
248 let mut can_immediately_return = true;
249 for stmt in &fx.mir[*target].statements {
250 if let StatementKind::StorageDead(_) = stmt.kind {
252 // FIXME Can sometimes happen, see rust-lang/rust#70531
253 can_immediately_return = false;
258 if can_immediately_return {
259 crate::abi::codegen_return(fx);
264 let block = fx.get_block(*target);
265 fx.bcx.ins().jump(block, &[]);
267 TerminatorKind::Return => {
268 crate::abi::codegen_return(fx);
270 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
271 if !fx.tcx.sess.overflow_checks() {
272 if let mir::AssertKind::OverflowNeg(_) = *msg {
273 let target = fx.get_block(*target);
274 fx.bcx.ins().jump(target, &[]);
278 let cond = codegen_operand(fx, cond).load_scalar(fx);
280 let target = fx.get_block(*target);
281 let failure = fx.bcx.create_block();
282 // FIXME Mark failure block as cold once Cranelift supports it
285 fx.bcx.ins().brz(cond, failure, &[]);
287 fx.bcx.ins().brnz(cond, failure, &[]);
289 fx.bcx.ins().jump(target, &[]);
291 fx.bcx.switch_to_block(failure);
295 AssertKind::BoundsCheck { ref len, ref index } => {
296 let len = codegen_operand(fx, len).load_scalar(fx);
297 let index = codegen_operand(fx, index).load_scalar(fx);
298 let location = fx.get_caller_location(source_info.span).load_scalar(fx);
302 rustc_hir::LangItem::PanicBoundsCheck,
303 &[index, len, location],
308 let msg_str = msg.description();
309 codegen_panic(fx, msg_str, source_info.span);
314 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
315 let discr = codegen_operand(fx, discr).load_scalar(fx);
317 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
318 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
320 assert_eq!(targets.iter().count(), 1);
321 let (then_value, then_block) = targets.iter().next().unwrap();
322 let then_block = fx.get_block(then_block);
323 let else_block = fx.get_block(targets.otherwise());
324 let test_zero = match then_value {
327 _ => unreachable!("{:?}", targets),
330 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
331 let (discr, is_inverted) =
332 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
333 let test_zero = if is_inverted { !test_zero } else { test_zero };
334 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
335 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
336 &fx.bcx, discr, test_zero,
339 fx.bcx.ins().jump(then_block, &[]);
341 fx.bcx.ins().jump(else_block, &[]);
345 fx.bcx.ins().brz(discr, then_block, &[]);
346 fx.bcx.ins().jump(else_block, &[]);
348 fx.bcx.ins().brnz(discr, then_block, &[]);
349 fx.bcx.ins().jump(else_block, &[]);
353 let mut switch = ::cranelift_frontend::Switch::new();
354 for (value, block) in targets.iter() {
355 let block = fx.get_block(block);
356 switch.set_entry(value, block);
358 let otherwise_block = fx.get_block(targets.otherwise());
359 switch.emit(&mut fx.bcx, discr, otherwise_block);
362 TerminatorKind::Call {
370 fx.tcx.sess.time("codegen call", || {
371 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
374 TerminatorKind::InlineAsm {
382 if options.contains(InlineAsmOptions::MAY_UNWIND) {
383 fx.tcx.sess.span_fatal(
385 "cranelift doesn't support unwinding from inline assembly.",
389 crate::inline_asm::codegen_inline_asm(
398 Some(destination) => {
399 let destination_block = fx.get_block(destination);
400 fx.bcx.ins().jump(destination_block, &[]);
403 crate::trap::trap_unreachable(
405 "[corruption] Returned from noreturn inline asm",
410 TerminatorKind::Resume | TerminatorKind::Abort => {
411 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
413 TerminatorKind::Unreachable => {
414 trap_unreachable(fx, "[corruption] Hit unreachable code.");
416 TerminatorKind::Yield { .. }
417 | TerminatorKind::FalseEdge { .. }
418 | TerminatorKind::FalseUnwind { .. }
419 | TerminatorKind::DropAndReplace { .. }
420 | TerminatorKind::GeneratorDrop => {
421 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
423 TerminatorKind::Drop { place, target, unwind: _ } => {
424 let drop_place = codegen_place(fx, *place);
425 crate::abi::codegen_drop(fx, source_info.span, drop_place);
427 let target_block = fx.get_block(*target);
428 fx.bcx.ins().jump(target_block, &[]);
433 fx.bcx.seal_all_blocks();
437 fn codegen_stmt<'tcx>(
438 fx: &mut FunctionCx<'_, '_, 'tcx>,
439 #[allow(unused_variables)] cur_block: Block,
440 stmt: &Statement<'tcx>,
442 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
444 fx.set_debug_loc(stmt.source_info);
448 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
450 if fx.clif_comments.enabled() {
451 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
452 fx.add_comment(inst, format!("{:?}", stmt));
458 StatementKind::SetDiscriminant { place, variant_index } => {
459 let place = codegen_place(fx, **place);
460 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
462 StatementKind::Assign(to_place_and_rval) => {
463 let lval = codegen_place(fx, to_place_and_rval.0);
464 let dest_layout = lval.layout();
465 match to_place_and_rval.1 {
466 Rvalue::Use(ref operand) => {
467 let val = codegen_operand(fx, operand);
468 lval.write_cvalue(fx, val);
470 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
471 let place = codegen_place(fx, place);
472 let ref_ = place.place_ref(fx, lval.layout());
473 lval.write_cvalue(fx, ref_);
475 Rvalue::ThreadLocalRef(def_id) => {
476 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
477 lval.write_cvalue(fx, val);
479 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
480 let lhs = codegen_operand(fx, &lhs_rhs.0);
481 let rhs = codegen_operand(fx, &lhs_rhs.1);
483 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
484 lval.write_cvalue(fx, res);
486 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
487 let lhs = codegen_operand(fx, &lhs_rhs.0);
488 let rhs = codegen_operand(fx, &lhs_rhs.1);
490 let res = if !fx.tcx.sess.overflow_checks() {
492 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
493 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
494 CValue::by_val_pair(val, is_overflow, lval.layout())
496 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
499 lval.write_cvalue(fx, res);
501 Rvalue::UnaryOp(un_op, ref operand) => {
502 let operand = codegen_operand(fx, operand);
503 let layout = operand.layout();
504 let val = operand.load_scalar(fx);
505 let res = match un_op {
506 UnOp::Not => match layout.ty.kind() {
508 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
509 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
511 ty::Uint(_) | ty::Int(_) => {
512 CValue::by_val(fx.bcx.ins().bnot(val), layout)
514 _ => unreachable!("un op Not for {:?}", layout.ty),
516 UnOp::Neg => match layout.ty.kind() {
517 ty::Int(IntTy::I128) => {
518 // FIXME remove this case once ineg.i128 works
520 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
521 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
523 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
524 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
525 _ => unreachable!("un op Neg for {:?}", layout.ty),
528 lval.write_cvalue(fx, res);
531 CastKind::Pointer(PointerCast::ReifyFnPointer),
535 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
536 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
537 match *from_ty.kind() {
538 ty::FnDef(def_id, substs) => {
539 let func_ref = fx.get_function_ref(
540 Instance::resolve_for_fn_ptr(
542 ParamEnv::reveal_all(),
547 .polymorphize(fx.tcx),
549 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
550 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
552 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
556 CastKind::Pointer(PointerCast::UnsafeFnPointer),
561 CastKind::Pointer(PointerCast::MutToConstPointer),
566 CastKind::Pointer(PointerCast::ArrayToPointer),
570 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
571 let operand = codegen_operand(fx, operand);
572 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
574 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
575 let operand = codegen_operand(fx, operand);
576 let from_ty = operand.layout().ty;
577 let to_ty = fx.monomorphize(to_ty);
579 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
580 ty.builtin_deref(true)
581 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
582 has_ptr_meta(fx.tcx, pointee_ty)
587 if is_fat_ptr(fx, from_ty) {
588 if is_fat_ptr(fx, to_ty) {
589 // fat-ptr -> fat-ptr
590 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
592 // fat-ptr -> thin-ptr
593 let (ptr, _extra) = operand.load_scalar_pair(fx);
594 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
596 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
597 // enum -> discriminant value
598 assert!(adt_def.is_enum());
600 ty::Uint(_) | ty::Int(_) => {}
601 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
603 let to_clif_ty = fx.clif_type(to_ty).unwrap();
605 let discriminant = crate::discriminant::codegen_get_discriminant(
608 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
612 let res = crate::cast::clif_intcast(
618 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
620 let to_clif_ty = fx.clif_type(to_ty).unwrap();
621 let from = operand.load_scalar(fx);
623 let res = clif_int_or_float_cast(
630 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
634 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
638 let operand = codegen_operand(fx, operand);
639 match *operand.layout().ty.kind() {
640 ty::Closure(def_id, substs) => {
641 let instance = Instance::resolve_closure(
645 ty::ClosureKind::FnOnce,
647 .polymorphize(fx.tcx);
648 let func_ref = fx.get_function_ref(instance);
649 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
650 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
652 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
655 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
656 let operand = codegen_operand(fx, operand);
657 operand.unsize_value(fx, lval);
659 Rvalue::Discriminant(place) => {
660 let place = codegen_place(fx, place);
661 let value = place.to_cvalue(fx);
663 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
664 lval.write_cvalue(fx, discr);
666 Rvalue::Repeat(ref operand, times) => {
667 let operand = codegen_operand(fx, operand);
670 .eval(fx.tcx, ParamEnv::reveal_all())
672 .try_to_bits(fx.tcx.data_layout.pointer_size)
674 if operand.layout().size.bytes() == 0 {
675 // Do nothing for ZST's
676 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
677 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
678 // FIXME use emit_small_memset where possible
679 let addr = lval.to_ptr().get_addr(fx);
680 let val = operand.load_scalar(fx);
681 fx.bcx.call_memset(fx.target_config, addr, val, times);
683 let loop_block = fx.bcx.create_block();
684 let loop_block2 = fx.bcx.create_block();
685 let done_block = fx.bcx.create_block();
686 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
687 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
688 fx.bcx.ins().jump(loop_block, &[zero]);
690 fx.bcx.switch_to_block(loop_block);
691 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
692 fx.bcx.ins().brnz(done, done_block, &[]);
693 fx.bcx.ins().jump(loop_block2, &[]);
695 fx.bcx.switch_to_block(loop_block2);
696 let to = lval.place_index(fx, index);
697 to.write_cvalue(fx, operand);
698 let index = fx.bcx.ins().iadd_imm(index, 1);
699 fx.bcx.ins().jump(loop_block, &[index]);
701 fx.bcx.switch_to_block(done_block);
705 Rvalue::Len(place) => {
706 let place = codegen_place(fx, place);
707 let usize_layout = fx.layout_of(fx.tcx.types.usize);
708 let len = codegen_array_len(fx, place);
709 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
711 Rvalue::ShallowInitBox(ref operand, content_ty) => {
712 let content_ty = fx.monomorphize(content_ty);
713 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
714 let operand = codegen_operand(fx, operand);
715 let operand = operand.load_scalar(fx);
716 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
718 Rvalue::NullaryOp(null_op, ty) => {
722 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
724 let layout = fx.layout_of(fx.monomorphize(ty));
725 let val = match null_op {
726 NullOp::SizeOf => layout.size.bytes(),
727 NullOp::AlignOf => layout.align.abi.bytes(),
729 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
730 lval.write_cvalue(fx, val);
732 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
733 AggregateKind::Array(_ty) => {
734 for (i, operand) in operands.iter().enumerate() {
735 let operand = codegen_operand(fx, operand);
736 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
737 let to = lval.place_index(fx, index);
738 to.write_cvalue(fx, operand);
741 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
745 StatementKind::StorageLive(_)
746 | StatementKind::StorageDead(_)
748 | StatementKind::FakeRead(..)
749 | StatementKind::Retag { .. }
750 | StatementKind::AscribeUserType(..) => {}
752 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
753 StatementKind::CopyNonOverlapping(inner) => {
754 let dst = codegen_operand(fx, &inner.dst);
757 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
758 .expect("Expected pointer");
759 let dst = dst.load_scalar(fx);
760 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
761 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
762 let elem_size: u64 = pointee.size.bytes();
764 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
765 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
770 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
771 match *place.layout().ty.kind() {
772 ty::Array(_elem_ty, len) => {
773 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
774 fx.bcx.ins().iconst(fx.pointer_type, len)
776 ty::Slice(_elem_ty) => {
777 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
779 _ => bug!("Rvalue::Len({:?})", place),
783 pub(crate) fn codegen_place<'tcx>(
784 fx: &mut FunctionCx<'_, '_, 'tcx>,
787 let mut cplace = fx.get_local_place(place.local);
789 for elem in place.projection {
791 PlaceElem::Deref => {
792 cplace = cplace.place_deref(fx);
794 PlaceElem::Field(field, _ty) => {
795 cplace = cplace.place_field(fx, field);
797 PlaceElem::Index(local) => {
798 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
799 cplace = cplace.place_index(fx, index);
801 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
802 let offset: u64 = offset;
803 let index = if !from_end {
804 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
806 let len = codegen_array_len(fx, cplace);
807 fx.bcx.ins().iadd_imm(len, -(offset as i64))
809 cplace = cplace.place_index(fx, index);
811 PlaceElem::Subslice { from, to, from_end } => {
812 // These indices are generated by slice patterns.
813 // slice[from:-to] in Python terms.
815 let from: u64 = from;
818 match cplace.layout().ty.kind() {
819 ty::Array(elem_ty, _len) => {
820 assert!(!from_end, "array subslices are never `from_end`");
821 let elem_layout = fx.layout_of(*elem_ty);
822 let ptr = cplace.to_ptr();
823 cplace = CPlace::for_ptr(
824 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
825 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
828 ty::Slice(elem_ty) => {
829 assert!(from_end, "slice subslices should be `from_end`");
830 let elem_layout = fx.layout_of(*elem_ty);
831 let (ptr, len) = cplace.to_ptr_maybe_unsized();
832 let len = len.unwrap();
833 cplace = CPlace::for_ptr_with_extra(
834 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
835 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
842 PlaceElem::Downcast(_adt_def, variant) => {
843 cplace = cplace.downcast_variant(fx, variant);
851 pub(crate) fn codegen_operand<'tcx>(
852 fx: &mut FunctionCx<'_, '_, 'tcx>,
853 operand: &Operand<'tcx>,
856 Operand::Move(place) | Operand::Copy(place) => {
857 let cplace = codegen_place(fx, *place);
860 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
864 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
865 let location = fx.get_caller_location(span).load_scalar(fx);
867 let msg_ptr = fx.anonymous_str(msg_str);
868 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
869 let args = [msg_ptr, msg_len, location];
871 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
874 pub(crate) fn codegen_panic_inner<'tcx>(
875 fx: &mut FunctionCx<'_, '_, 'tcx>,
876 lang_item: rustc_hir::LangItem,
881 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
883 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
884 let symbol_name = fx.tcx.symbol_name(instance).name;
889 AbiParam::new(fx.pointer_type),
890 AbiParam::new(fx.pointer_type),
891 AbiParam::new(fx.pointer_type),
897 crate::trap::trap_unreachable(fx, "panic lang item returned");