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 cranelift_codegen::ir::UserFuncName;
11 use crate::constant::ConstantCx;
12 use crate::debuginfo::FunctionDebugContext;
13 use crate::prelude::*;
14 use crate::pretty_clif::CommentWriter;
16 pub(crate) struct CodegenedFunction {
20 clif_comments: CommentWriter,
21 func_debug_cx: Option<FunctionDebugContext>,
24 #[cfg_attr(not(feature = "jit"), allow(dead_code))]
25 pub(crate) fn codegen_and_compile_fn<'tcx>(
27 cx: &mut crate::CodegenCx,
28 cached_context: &mut Context,
29 module: &mut dyn Module,
30 instance: Instance<'tcx>,
33 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
35 let cached_func = std::mem::replace(&mut cached_context.func, Function::new());
36 let codegened_func = codegen_fn(tcx, cx, cached_func, module, instance);
38 compile_fn(cx, cached_context, module, codegened_func);
41 pub(crate) fn codegen_fn<'tcx>(
43 cx: &mut crate::CodegenCx,
44 cached_func: Function,
45 module: &mut dyn Module,
46 instance: Instance<'tcx>,
47 ) -> CodegenedFunction {
48 debug_assert!(!instance.substs.needs_infer());
50 let mir = tcx.instance_mir(instance.def);
51 let _mir_guard = crate::PrintOnPanic(|| {
52 let mut buf = Vec::new();
53 with_no_trimmed_paths!({
54 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
57 String::from_utf8_lossy(&buf).into_owned()
61 let symbol_name = tcx.symbol_name(instance).name.to_string();
62 let sig = get_function_sig(tcx, module.target_config().default_call_conv, instance);
63 let func_id = module.declare_function(&symbol_name, Linkage::Local, &sig).unwrap();
65 // Make the FunctionBuilder
66 let mut func_ctx = FunctionBuilderContext::new();
67 let mut func = cached_func;
69 func.name = UserFuncName::user(0, func_id.as_u32());
71 func.collect_debug_info();
73 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
76 let start_block = bcx.create_block();
77 let block_map: IndexVec<BasicBlock, Block> =
78 (0..mir.basic_blocks.len()).map(|_| bcx.create_block()).collect();
81 let target_config = module.target_config();
82 let pointer_type = target_config.pointer_type();
83 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
85 let func_debug_cx = if let Some(debug_context) = &mut cx.debug_context {
86 Some(debug_context.define_function(tcx, &symbol_name, mir.span))
91 let mut fx = FunctionCx {
97 constants_cx: ConstantCx::new(),
103 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
107 local_map: IndexVec::with_capacity(mir.local_decls.len()),
108 caller_location: None, // set by `codegen_fn_prelude`
111 last_source_file: None,
115 tcx.sess.time("codegen clif ir", || codegen_fn_body(&mut fx, start_block));
117 // Recover all necessary data from fx, before accessing func will prevent future access to it.
118 let symbol_name = fx.symbol_name;
119 let clif_comments = fx.clif_comments;
120 let func_debug_cx = fx.func_debug_cx;
122 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
124 if cx.should_write_ir {
125 crate::pretty_clif::write_clif_file(
126 tcx.output_filenames(()),
136 verify_func(tcx, &clif_comments, &func);
138 CodegenedFunction { symbol_name, func_id, func, clif_comments, func_debug_cx }
141 pub(crate) fn compile_fn(
142 cx: &mut crate::CodegenCx,
143 cached_context: &mut Context,
144 module: &mut dyn Module,
145 codegened_func: CodegenedFunction,
147 let clif_comments = codegened_func.clif_comments;
149 // Store function in context
150 let context = cached_context;
152 context.func = codegened_func.func;
154 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
155 // instruction, which doesn't have an encoding.
156 context.compute_cfg();
157 context.compute_domtree();
158 context.eliminate_unreachable_code(module.isa()).unwrap();
159 context.dce(module.isa()).unwrap();
160 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
161 // invalidate it when it would change.
162 context.domtree.clear();
164 #[cfg(any())] // This is never true
168 let func_clone = context.func.clone();
169 let clif_comments_clone = clif_comments.clone();
170 let mut clif = String::new();
171 for flag in module.isa().flags().iter() {
172 writeln!(clif, "set {}", flag).unwrap();
174 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
175 for isa_flag in module.isa().isa_flags().iter() {
176 write!(clif, " {}", isa_flag).unwrap();
178 writeln!(clif, "\n").unwrap();
179 crate::PrintOnPanic(move || {
180 let mut clif = clif.clone();
181 ::cranelift_codegen::write::decorate_function(
182 &mut &clif_comments_clone,
192 cx.profiler.verbose_generic_activity("define function").run(|| {
193 context.want_disasm = cx.should_write_ir;
194 module.define_function(codegened_func.func_id, context).unwrap();
197 if cx.should_write_ir {
198 // Write optimized function to file for debugging
199 crate::pretty_clif::write_clif_file(
200 &cx.output_filenames,
201 &codegened_func.symbol_name,
208 if let Some(disasm) = &context.compiled_code().unwrap().disasm {
209 crate::pretty_clif::write_ir_file(
210 &cx.output_filenames,
211 &format!("{}.vcode", codegened_func.symbol_name),
212 |file| file.write_all(disasm.as_bytes()),
217 // Define debuginfo for function
218 let isa = module.isa();
219 let debug_context = &mut cx.debug_context;
220 let unwind_context = &mut cx.unwind_context;
221 cx.profiler.verbose_generic_activity("generate debug info").run(|| {
222 if let Some(debug_context) = debug_context {
223 codegened_func.func_debug_cx.unwrap().finalize(
225 codegened_func.func_id,
229 unwind_context.add_function(codegened_func.func_id, &context, isa);
233 pub(crate) fn verify_func(
235 writer: &crate::pretty_clif::CommentWriter,
238 tcx.sess.time("verify clif ir", || {
239 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
240 match cranelift_codegen::verify_function(&func, &flags) {
243 tcx.sess.err(&format!("{:?}", err));
244 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
246 Some(Box::new(writer)),
249 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
255 fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
256 if !crate::constant::check_constants(fx) {
257 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
258 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
259 // compilation should have been aborted
260 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
264 let arg_uninhabited = fx
267 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
269 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
270 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
271 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
274 fx.tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(fx, start_block));
276 for (bb, bb_data) in fx.mir.basic_blocks.iter_enumerated() {
277 let block = fx.get_block(bb);
278 fx.bcx.switch_to_block(block);
280 if bb_data.is_cleanup {
281 // Unwinding after panicking is not supported
284 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
285 // so for cleanup blocks.
289 for stmt in &bb_data.statements {
290 fx.set_debug_loc(stmt.source_info);
291 codegen_stmt(fx, block, stmt);
294 if fx.clif_comments.enabled() {
295 let mut terminator_head = "\n".to_string();
296 with_no_trimmed_paths!({
297 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
299 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
300 fx.add_comment(inst, terminator_head);
303 let source_info = bb_data.terminator().source_info;
304 fx.set_debug_loc(source_info);
306 match &bb_data.terminator().kind {
307 TerminatorKind::Goto { target } => {
308 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
309 let mut can_immediately_return = true;
310 for stmt in &fx.mir[*target].statements {
311 if let StatementKind::StorageDead(_) = stmt.kind {
313 // FIXME Can sometimes happen, see rust-lang/rust#70531
314 can_immediately_return = false;
319 if can_immediately_return {
320 crate::abi::codegen_return(fx);
325 let block = fx.get_block(*target);
326 fx.bcx.ins().jump(block, &[]);
328 TerminatorKind::Return => {
329 crate::abi::codegen_return(fx);
331 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
332 if !fx.tcx.sess.overflow_checks() {
333 if let mir::AssertKind::OverflowNeg(_) = *msg {
334 let target = fx.get_block(*target);
335 fx.bcx.ins().jump(target, &[]);
339 let cond = codegen_operand(fx, cond).load_scalar(fx);
341 let target = fx.get_block(*target);
342 let failure = fx.bcx.create_block();
343 fx.bcx.set_cold_block(failure);
346 fx.bcx.ins().brz(cond, failure, &[]);
348 fx.bcx.ins().brnz(cond, failure, &[]);
350 fx.bcx.ins().jump(target, &[]);
352 fx.bcx.switch_to_block(failure);
356 AssertKind::BoundsCheck { ref len, ref index } => {
357 let len = codegen_operand(fx, len).load_scalar(fx);
358 let index = codegen_operand(fx, index).load_scalar(fx);
359 let location = fx.get_caller_location(source_info).load_scalar(fx);
363 rustc_hir::LangItem::PanicBoundsCheck,
364 &[index, len, location],
369 let msg_str = msg.description();
370 codegen_panic(fx, msg_str, source_info);
375 TerminatorKind::SwitchInt { discr, targets } => {
376 let discr = codegen_operand(fx, discr);
377 let switch_ty = discr.layout().ty;
378 let discr = discr.load_scalar(fx);
380 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
381 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
383 assert_eq!(targets.iter().count(), 1);
384 let (then_value, then_block) = targets.iter().next().unwrap();
385 let then_block = fx.get_block(then_block);
386 let else_block = fx.get_block(targets.otherwise());
387 let test_zero = match then_value {
390 _ => unreachable!("{:?}", targets),
393 let (discr, is_inverted) =
394 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
395 let test_zero = if is_inverted { !test_zero } else { test_zero };
396 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
397 &fx.bcx, discr, test_zero,
400 fx.bcx.ins().jump(then_block, &[]);
402 fx.bcx.ins().jump(else_block, &[]);
406 fx.bcx.ins().brz(discr, then_block, &[]);
407 fx.bcx.ins().jump(else_block, &[]);
409 fx.bcx.ins().brnz(discr, then_block, &[]);
410 fx.bcx.ins().jump(else_block, &[]);
414 let mut switch = ::cranelift_frontend::Switch::new();
415 for (value, block) in targets.iter() {
416 let block = fx.get_block(block);
417 switch.set_entry(value, block);
419 let otherwise_block = fx.get_block(targets.otherwise());
420 switch.emit(&mut fx.bcx, discr, otherwise_block);
423 TerminatorKind::Call {
432 fx.tcx.sess.time("codegen call", || {
433 crate::abi::codegen_terminator_call(
435 mir::SourceInfo { span: *fn_span, ..source_info },
443 TerminatorKind::InlineAsm {
451 if options.contains(InlineAsmOptions::MAY_UNWIND) {
452 fx.tcx.sess.span_fatal(
454 "cranelift doesn't support unwinding from inline assembly.",
458 crate::inline_asm::codegen_inline_asm(
467 TerminatorKind::Resume | TerminatorKind::Abort => {
468 // FIXME implement unwinding
469 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
471 TerminatorKind::Unreachable => {
472 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
474 TerminatorKind::Yield { .. }
475 | TerminatorKind::FalseEdge { .. }
476 | TerminatorKind::FalseUnwind { .. }
477 | TerminatorKind::DropAndReplace { .. }
478 | TerminatorKind::GeneratorDrop => {
479 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
481 TerminatorKind::Drop { place, target, unwind: _ } => {
482 let drop_place = codegen_place(fx, *place);
483 crate::abi::codegen_drop(fx, source_info, drop_place);
485 let target_block = fx.get_block(*target);
486 fx.bcx.ins().jump(target_block, &[]);
491 fx.bcx.seal_all_blocks();
495 fn codegen_stmt<'tcx>(
496 fx: &mut FunctionCx<'_, '_, 'tcx>,
497 #[allow(unused_variables)] cur_block: Block,
498 stmt: &Statement<'tcx>,
500 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
502 fx.set_debug_loc(stmt.source_info);
504 #[cfg(any())] // This is never true
506 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
508 if fx.clif_comments.enabled() {
509 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
510 fx.add_comment(inst, format!("{:?}", stmt));
516 StatementKind::SetDiscriminant { place, variant_index } => {
517 let place = codegen_place(fx, **place);
518 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
520 StatementKind::Assign(to_place_and_rval) => {
521 let lval = codegen_place(fx, to_place_and_rval.0);
522 let dest_layout = lval.layout();
523 match to_place_and_rval.1 {
524 Rvalue::Use(ref operand) => {
525 let val = codegen_operand(fx, operand);
526 lval.write_cvalue(fx, val);
528 Rvalue::CopyForDeref(place) => {
529 let cplace = codegen_place(fx, place);
530 let val = cplace.to_cvalue(fx);
531 lval.write_cvalue(fx, val)
533 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
534 let place = codegen_place(fx, place);
535 let ref_ = place.place_ref(fx, lval.layout());
536 lval.write_cvalue(fx, ref_);
538 Rvalue::ThreadLocalRef(def_id) => {
539 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
540 lval.write_cvalue(fx, val);
542 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
543 let lhs = codegen_operand(fx, &lhs_rhs.0);
544 let rhs = codegen_operand(fx, &lhs_rhs.1);
546 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
547 lval.write_cvalue(fx, res);
549 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
550 let lhs = codegen_operand(fx, &lhs_rhs.0);
551 let rhs = codegen_operand(fx, &lhs_rhs.1);
553 let res = if !fx.tcx.sess.overflow_checks() {
555 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
556 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
557 CValue::by_val_pair(val, is_overflow, lval.layout())
559 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
562 lval.write_cvalue(fx, res);
564 Rvalue::UnaryOp(un_op, ref operand) => {
565 let operand = codegen_operand(fx, operand);
566 let layout = operand.layout();
567 let val = operand.load_scalar(fx);
568 let res = match un_op {
569 UnOp::Not => match layout.ty.kind() {
571 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
572 CValue::by_val(res, layout)
574 ty::Uint(_) | ty::Int(_) => {
575 CValue::by_val(fx.bcx.ins().bnot(val), layout)
577 _ => unreachable!("un op Not for {:?}", layout.ty),
579 UnOp::Neg => match layout.ty.kind() {
580 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
581 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
582 _ => unreachable!("un op Neg for {:?}", layout.ty),
585 lval.write_cvalue(fx, res);
588 CastKind::Pointer(PointerCast::ReifyFnPointer),
592 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
593 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
594 match *from_ty.kind() {
595 ty::FnDef(def_id, substs) => {
596 let func_ref = fx.get_function_ref(
597 Instance::resolve_for_fn_ptr(
599 ParamEnv::reveal_all(),
604 .polymorphize(fx.tcx),
606 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
607 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
609 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
613 CastKind::Pointer(PointerCast::UnsafeFnPointer),
618 CastKind::Pointer(PointerCast::MutToConstPointer),
623 CastKind::Pointer(PointerCast::ArrayToPointer),
627 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
628 let operand = codegen_operand(fx, operand);
629 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
633 | CastKind::FloatToFloat
634 | CastKind::FloatToInt
635 | CastKind::IntToFloat
636 | CastKind::FnPtrToPtr
638 | CastKind::PointerExposeAddress
639 | CastKind::PointerFromExposedAddress,
643 let operand = codegen_operand(fx, operand);
644 let from_ty = operand.layout().ty;
645 let to_ty = fx.monomorphize(to_ty);
647 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
648 ty.builtin_deref(true)
649 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
650 has_ptr_meta(fx.tcx, pointee_ty)
655 if is_fat_ptr(fx, from_ty) {
656 if is_fat_ptr(fx, to_ty) {
657 // fat-ptr -> fat-ptr
658 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
660 // fat-ptr -> thin-ptr
661 let (ptr, _extra) = operand.load_scalar_pair(fx);
662 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
665 let to_clif_ty = fx.clif_type(to_ty).unwrap();
666 let from = operand.load_scalar(fx);
668 let res = clif_int_or_float_cast(
675 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
679 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
683 let operand = codegen_operand(fx, operand);
684 match *operand.layout().ty.kind() {
685 ty::Closure(def_id, substs) => {
686 let instance = Instance::resolve_closure(
690 ty::ClosureKind::FnOnce,
692 .expect("failed to normalize and resolve closure during codegen")
693 .polymorphize(fx.tcx);
694 let func_ref = fx.get_function_ref(instance);
695 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
696 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
698 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
701 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
702 let operand = codegen_operand(fx, operand);
703 operand.unsize_value(fx, lval);
705 Rvalue::Cast(CastKind::DynStar, ref operand, _) => {
706 let operand = codegen_operand(fx, operand);
707 operand.coerce_dyn_star(fx, lval);
709 Rvalue::Discriminant(place) => {
710 let place = codegen_place(fx, place);
711 let value = place.to_cvalue(fx);
712 crate::discriminant::codegen_get_discriminant(fx, lval, value, dest_layout);
714 Rvalue::Repeat(ref operand, times) => {
715 let operand = codegen_operand(fx, operand);
718 .eval(fx.tcx, ParamEnv::reveal_all())
720 .try_to_bits(fx.tcx.data_layout.pointer_size)
722 if operand.layout().size.bytes() == 0 {
723 // Do nothing for ZST's
724 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
725 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
726 // FIXME use emit_small_memset where possible
727 let addr = lval.to_ptr().get_addr(fx);
728 let val = operand.load_scalar(fx);
729 fx.bcx.call_memset(fx.target_config, addr, val, times);
731 let loop_block = fx.bcx.create_block();
732 let loop_block2 = fx.bcx.create_block();
733 let done_block = fx.bcx.create_block();
734 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
735 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
736 fx.bcx.ins().jump(loop_block, &[zero]);
738 fx.bcx.switch_to_block(loop_block);
739 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
740 fx.bcx.ins().brnz(done, done_block, &[]);
741 fx.bcx.ins().jump(loop_block2, &[]);
743 fx.bcx.switch_to_block(loop_block2);
744 let to = lval.place_index(fx, index);
745 to.write_cvalue(fx, operand);
746 let index = fx.bcx.ins().iadd_imm(index, 1);
747 fx.bcx.ins().jump(loop_block, &[index]);
749 fx.bcx.switch_to_block(done_block);
753 Rvalue::Len(place) => {
754 let place = codegen_place(fx, place);
755 let usize_layout = fx.layout_of(fx.tcx.types.usize);
756 let len = codegen_array_len(fx, place);
757 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
759 Rvalue::ShallowInitBox(ref operand, content_ty) => {
760 let content_ty = fx.monomorphize(content_ty);
761 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
762 let operand = codegen_operand(fx, operand);
763 let operand = operand.load_scalar(fx);
764 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
766 Rvalue::NullaryOp(null_op, ty) => {
767 assert!(lval.layout().ty.is_sized(fx.tcx, ParamEnv::reveal_all()));
768 let layout = fx.layout_of(fx.monomorphize(ty));
769 let val = match null_op {
770 NullOp::SizeOf => layout.size.bytes(),
771 NullOp::AlignOf => layout.align.abi.bytes(),
773 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
774 lval.write_cvalue(fx, val);
776 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
777 AggregateKind::Array(_ty) => {
778 for (i, operand) in operands.iter().enumerate() {
779 let operand = codegen_operand(fx, operand);
780 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
781 let to = lval.place_index(fx, index);
782 to.write_cvalue(fx, operand);
785 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
789 StatementKind::StorageLive(_)
790 | StatementKind::StorageDead(_)
791 | StatementKind::Deinit(_)
793 | StatementKind::FakeRead(..)
794 | StatementKind::Retag { .. }
795 | StatementKind::AscribeUserType(..) => {}
797 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
798 StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
799 // We ignore `assume` intrinsics, they are only useful for optimizations
800 NonDivergingIntrinsic::Assume(_) => {}
801 NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
806 let dst = codegen_operand(fx, dst);
809 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
810 .expect("Expected pointer");
811 let dst = dst.load_scalar(fx);
812 let src = codegen_operand(fx, src).load_scalar(fx);
813 let count = codegen_operand(fx, count).load_scalar(fx);
814 let elem_size: u64 = pointee.size.bytes();
815 let bytes = if elem_size != 1 {
816 fx.bcx.ins().imul_imm(count, elem_size as i64)
820 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
826 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
827 match *place.layout().ty.kind() {
828 ty::Array(_elem_ty, len) => {
829 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
830 fx.bcx.ins().iconst(fx.pointer_type, len)
832 ty::Slice(_elem_ty) => {
833 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
835 _ => bug!("Rvalue::Len({:?})", place),
839 pub(crate) fn codegen_place<'tcx>(
840 fx: &mut FunctionCx<'_, '_, 'tcx>,
843 let mut cplace = fx.get_local_place(place.local);
845 for elem in place.projection {
847 PlaceElem::Deref => {
848 cplace = cplace.place_deref(fx);
850 PlaceElem::OpaqueCast(ty) => cplace = cplace.place_opaque_cast(fx, ty),
851 PlaceElem::Field(field, _ty) => {
852 cplace = cplace.place_field(fx, field);
854 PlaceElem::Index(local) => {
855 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
856 cplace = cplace.place_index(fx, index);
858 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
859 let offset: u64 = offset;
860 let index = if !from_end {
861 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
863 let len = codegen_array_len(fx, cplace);
864 fx.bcx.ins().iadd_imm(len, -(offset as i64))
866 cplace = cplace.place_index(fx, index);
868 PlaceElem::Subslice { from, to, from_end } => {
869 // These indices are generated by slice patterns.
870 // slice[from:-to] in Python terms.
872 let from: u64 = from;
875 match cplace.layout().ty.kind() {
876 ty::Array(elem_ty, _len) => {
877 assert!(!from_end, "array subslices are never `from_end`");
878 let elem_layout = fx.layout_of(*elem_ty);
879 let ptr = cplace.to_ptr();
880 cplace = CPlace::for_ptr(
881 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
882 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
885 ty::Slice(elem_ty) => {
886 assert!(from_end, "slice subslices should be `from_end`");
887 let elem_layout = fx.layout_of(*elem_ty);
888 let (ptr, len) = cplace.to_ptr_maybe_unsized();
889 let len = len.unwrap();
890 cplace = CPlace::for_ptr_with_extra(
891 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
892 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
899 PlaceElem::Downcast(_adt_def, variant) => {
900 cplace = cplace.downcast_variant(fx, variant);
908 pub(crate) fn codegen_operand<'tcx>(
909 fx: &mut FunctionCx<'_, '_, 'tcx>,
910 operand: &Operand<'tcx>,
913 Operand::Move(place) | Operand::Copy(place) => {
914 let cplace = codegen_place(fx, *place);
917 Operand::Constant(const_) => crate::constant::codegen_constant_operand(fx, const_),
921 pub(crate) fn codegen_panic<'tcx>(
922 fx: &mut FunctionCx<'_, '_, 'tcx>,
924 source_info: mir::SourceInfo,
926 let location = fx.get_caller_location(source_info).load_scalar(fx);
928 let msg_ptr = fx.anonymous_str(msg_str);
929 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
930 let args = [msg_ptr, msg_len, location];
932 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
935 pub(crate) fn codegen_panic_inner<'tcx>(
936 fx: &mut FunctionCx<'_, '_, 'tcx>,
937 lang_item: rustc_hir::LangItem,
945 .unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
947 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
948 let symbol_name = fx.tcx.symbol_name(instance).name;
953 AbiParam::new(fx.pointer_type),
954 AbiParam::new(fx.pointer_type),
955 AbiParam::new(fx.pointer_type),
961 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);