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 pub(crate) fn codegen_fn<'tcx>(
26 cx: &mut crate::CodegenCx,
27 cached_func: Function,
28 module: &mut dyn Module,
29 instance: Instance<'tcx>,
30 ) -> CodegenedFunction {
31 debug_assert!(!instance.substs.needs_infer());
33 let symbol_name = tcx.symbol_name(instance).name.to_string();
34 let _timer = tcx.prof.generic_activity_with_arg("codegen fn", &*symbol_name);
36 let mir = tcx.instance_mir(instance.def);
37 let _mir_guard = crate::PrintOnPanic(|| {
38 let mut buf = Vec::new();
39 with_no_trimmed_paths!({
40 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
43 String::from_utf8_lossy(&buf).into_owned()
47 let sig = get_function_sig(tcx, module.target_config().default_call_conv, instance);
48 let func_id = module.declare_function(&symbol_name, Linkage::Local, &sig).unwrap();
50 // Make the FunctionBuilder
51 let mut func_ctx = FunctionBuilderContext::new();
52 let mut func = cached_func;
54 func.name = UserFuncName::user(0, func_id.as_u32());
56 func.collect_debug_info();
58 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
61 let start_block = bcx.create_block();
62 let block_map: IndexVec<BasicBlock, Block> =
63 (0..mir.basic_blocks.len()).map(|_| bcx.create_block()).collect();
66 let target_config = module.target_config();
67 let pointer_type = target_config.pointer_type();
68 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
70 let func_debug_cx = if let Some(debug_context) = &mut cx.debug_context {
71 Some(debug_context.define_function(tcx, &symbol_name, mir.span))
76 let mut fx = FunctionCx {
82 constants_cx: ConstantCx::new(),
88 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
92 local_map: IndexVec::with_capacity(mir.local_decls.len()),
93 caller_location: None, // set by `codegen_fn_prelude`
96 last_source_file: None,
100 tcx.prof.generic_activity("codegen clif ir").run(|| codegen_fn_body(&mut fx, start_block));
101 fx.bcx.seal_all_blocks();
104 // Recover all necessary data from fx, before accessing func will prevent future access to it.
105 let symbol_name = fx.symbol_name;
106 let clif_comments = fx.clif_comments;
107 let func_debug_cx = fx.func_debug_cx;
109 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
111 if cx.should_write_ir {
112 crate::pretty_clif::write_clif_file(
113 tcx.output_filenames(()),
123 verify_func(tcx, &clif_comments, &func);
125 CodegenedFunction { symbol_name, func_id, func, clif_comments, func_debug_cx }
128 pub(crate) fn compile_fn(
129 cx: &mut crate::CodegenCx,
130 cached_context: &mut Context,
131 module: &mut dyn Module,
132 codegened_func: CodegenedFunction,
135 cx.profiler.generic_activity_with_arg("compile function", &*codegened_func.symbol_name);
137 let clif_comments = codegened_func.clif_comments;
139 // Store function in context
140 let context = cached_context;
142 context.func = codegened_func.func;
144 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
145 // instruction, which doesn't have an encoding.
146 context.compute_cfg();
147 context.compute_domtree();
148 context.eliminate_unreachable_code(module.isa()).unwrap();
149 context.dce(module.isa()).unwrap();
150 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
151 // invalidate it when it would change.
152 context.domtree.clear();
154 #[cfg(any())] // This is never true
158 let func_clone = context.func.clone();
159 let clif_comments_clone = clif_comments.clone();
160 let mut clif = String::new();
161 for flag in module.isa().flags().iter() {
162 writeln!(clif, "set {}", flag).unwrap();
164 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
165 for isa_flag in module.isa().isa_flags().iter() {
166 write!(clif, " {}", isa_flag).unwrap();
168 writeln!(clif, "\n").unwrap();
169 crate::PrintOnPanic(move || {
170 let mut clif = clif.clone();
171 ::cranelift_codegen::write::decorate_function(
172 &mut &clif_comments_clone,
182 cx.profiler.generic_activity("define function").run(|| {
183 context.want_disasm = cx.should_write_ir;
184 module.define_function(codegened_func.func_id, context).unwrap();
186 if cx.profiler.enabled() {
187 let mut recording_args = false;
189 .generic_activity_with_arg_recorder(
190 "define function (clif pass timings)",
192 let pass_times = cranelift_codegen::timing::take_current();
193 // Replace newlines with | as measureme doesn't allow control characters like
194 // newlines inside strings.
195 recorder.record_arg(format!("{}", pass_times).replace("\n", " | "));
196 recording_args = true;
201 // Wait a tiny bit to ensure chrome's profiler doesn't hide the event
202 std::thread::sleep(std::time::Duration::from_nanos(2))
208 if cx.should_write_ir {
209 // Write optimized function to file for debugging
210 crate::pretty_clif::write_clif_file(
211 &cx.output_filenames,
212 &codegened_func.symbol_name,
219 if let Some(disasm) = &context.compiled_code().unwrap().disasm {
220 crate::pretty_clif::write_ir_file(
221 &cx.output_filenames,
222 &format!("{}.vcode", codegened_func.symbol_name),
223 |file| file.write_all(disasm.as_bytes()),
228 // Define debuginfo for function
229 let isa = module.isa();
230 let debug_context = &mut cx.debug_context;
231 let unwind_context = &mut cx.unwind_context;
232 cx.profiler.generic_activity("generate debug info").run(|| {
233 if let Some(debug_context) = debug_context {
234 codegened_func.func_debug_cx.unwrap().finalize(
236 codegened_func.func_id,
240 unwind_context.add_function(codegened_func.func_id, &context, isa);
244 pub(crate) fn verify_func(
246 writer: &crate::pretty_clif::CommentWriter,
249 tcx.prof.generic_activity("verify clif ir").run(|| {
250 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
251 match cranelift_codegen::verify_function(&func, &flags) {
254 tcx.sess.err(&format!("{:?}", err));
255 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
257 Some(Box::new(writer)),
260 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
266 fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
267 if !crate::constant::check_constants(fx) {
268 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
269 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
270 // compilation should have been aborted
271 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
275 let arg_uninhabited = fx
278 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
280 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
281 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
282 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
287 .generic_activity("codegen prelude")
288 .run(|| crate::abi::codegen_fn_prelude(fx, start_block));
290 for (bb, bb_data) in fx.mir.basic_blocks.iter_enumerated() {
291 let block = fx.get_block(bb);
292 fx.bcx.switch_to_block(block);
294 if bb_data.is_cleanup {
295 // Unwinding after panicking is not supported
298 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
299 // so for cleanup blocks.
303 for stmt in &bb_data.statements {
304 fx.set_debug_loc(stmt.source_info);
305 codegen_stmt(fx, block, stmt);
308 if fx.clif_comments.enabled() {
309 let mut terminator_head = "\n".to_string();
310 with_no_trimmed_paths!({
311 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
313 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
314 fx.add_comment(inst, terminator_head);
317 let source_info = bb_data.terminator().source_info;
318 fx.set_debug_loc(source_info);
321 crate::PrintOnPanic(|| format!("terminator {:?}", bb_data.terminator().kind));
323 match &bb_data.terminator().kind {
324 TerminatorKind::Goto { target } => {
325 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
326 let mut can_immediately_return = true;
327 for stmt in &fx.mir[*target].statements {
328 if let StatementKind::StorageDead(_) = stmt.kind {
330 // FIXME Can sometimes happen, see rust-lang/rust#70531
331 can_immediately_return = false;
336 if can_immediately_return {
337 crate::abi::codegen_return(fx);
342 let block = fx.get_block(*target);
343 fx.bcx.ins().jump(block, &[]);
345 TerminatorKind::Return => {
346 crate::abi::codegen_return(fx);
348 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
349 if !fx.tcx.sess.overflow_checks() {
350 if let mir::AssertKind::OverflowNeg(_) = *msg {
351 let target = fx.get_block(*target);
352 fx.bcx.ins().jump(target, &[]);
356 let cond = codegen_operand(fx, cond).load_scalar(fx);
358 let target = fx.get_block(*target);
359 let failure = fx.bcx.create_block();
360 fx.bcx.set_cold_block(failure);
363 fx.bcx.ins().brz(cond, failure, &[]);
365 fx.bcx.ins().brnz(cond, failure, &[]);
367 fx.bcx.ins().jump(target, &[]);
369 fx.bcx.switch_to_block(failure);
373 AssertKind::BoundsCheck { ref len, ref index } => {
374 let len = codegen_operand(fx, len).load_scalar(fx);
375 let index = codegen_operand(fx, index).load_scalar(fx);
376 let location = fx.get_caller_location(source_info).load_scalar(fx);
380 rustc_hir::LangItem::PanicBoundsCheck,
381 &[index, len, location],
386 let msg_str = msg.description();
387 codegen_panic(fx, msg_str, source_info);
392 TerminatorKind::SwitchInt { discr, targets } => {
393 let discr = codegen_operand(fx, discr);
394 let switch_ty = discr.layout().ty;
395 let discr = discr.load_scalar(fx);
397 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
398 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
400 assert_eq!(targets.iter().count(), 1);
401 let (then_value, then_block) = targets.iter().next().unwrap();
402 let then_block = fx.get_block(then_block);
403 let else_block = fx.get_block(targets.otherwise());
404 let test_zero = match then_value {
407 _ => unreachable!("{:?}", targets),
410 let (discr, is_inverted) =
411 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
412 let test_zero = if is_inverted { !test_zero } else { test_zero };
413 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
414 &fx.bcx, discr, test_zero,
417 fx.bcx.ins().jump(then_block, &[]);
419 fx.bcx.ins().jump(else_block, &[]);
423 fx.bcx.ins().brz(discr, then_block, &[]);
424 fx.bcx.ins().jump(else_block, &[]);
426 fx.bcx.ins().brnz(discr, then_block, &[]);
427 fx.bcx.ins().jump(else_block, &[]);
431 let mut switch = ::cranelift_frontend::Switch::new();
432 for (value, block) in targets.iter() {
433 let block = fx.get_block(block);
434 switch.set_entry(value, block);
436 let otherwise_block = fx.get_block(targets.otherwise());
437 switch.emit(&mut fx.bcx, discr, otherwise_block);
440 TerminatorKind::Call {
449 fx.tcx.prof.generic_activity("codegen call").run(|| {
450 crate::abi::codegen_terminator_call(
452 mir::SourceInfo { span: *fn_span, ..source_info },
460 TerminatorKind::InlineAsm {
468 if options.contains(InlineAsmOptions::MAY_UNWIND) {
469 fx.tcx.sess.span_fatal(
471 "cranelift doesn't support unwinding from inline assembly.",
475 crate::inline_asm::codegen_inline_asm(
484 TerminatorKind::Abort => {
485 codegen_panic_cannot_unwind(fx, source_info);
487 TerminatorKind::Resume => {
488 // FIXME implement unwinding
489 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
491 TerminatorKind::Unreachable => {
492 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
494 TerminatorKind::Yield { .. }
495 | TerminatorKind::FalseEdge { .. }
496 | TerminatorKind::FalseUnwind { .. }
497 | TerminatorKind::DropAndReplace { .. }
498 | TerminatorKind::GeneratorDrop => {
499 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
501 TerminatorKind::Drop { place, target, unwind: _ } => {
502 let drop_place = codegen_place(fx, *place);
503 crate::abi::codegen_drop(fx, source_info, drop_place);
505 let target_block = fx.get_block(*target);
506 fx.bcx.ins().jump(target_block, &[]);
512 fn codegen_stmt<'tcx>(
513 fx: &mut FunctionCx<'_, '_, 'tcx>,
514 #[allow(unused_variables)] cur_block: Block,
515 stmt: &Statement<'tcx>,
517 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
519 fx.set_debug_loc(stmt.source_info);
521 #[cfg(any())] // This is never true
523 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
525 if fx.clif_comments.enabled() {
526 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
527 fx.add_comment(inst, format!("{:?}", stmt));
533 StatementKind::SetDiscriminant { place, variant_index } => {
534 let place = codegen_place(fx, **place);
535 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
537 StatementKind::Assign(to_place_and_rval) => {
538 let lval = codegen_place(fx, to_place_and_rval.0);
539 let dest_layout = lval.layout();
540 match to_place_and_rval.1 {
541 Rvalue::Use(ref operand) => {
542 let val = codegen_operand(fx, operand);
543 lval.write_cvalue(fx, val);
545 Rvalue::CopyForDeref(place) => {
546 let cplace = codegen_place(fx, place);
547 let val = cplace.to_cvalue(fx);
548 lval.write_cvalue(fx, val)
550 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
551 let place = codegen_place(fx, place);
552 let ref_ = place.place_ref(fx, lval.layout());
553 lval.write_cvalue(fx, ref_);
555 Rvalue::ThreadLocalRef(def_id) => {
556 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
557 lval.write_cvalue(fx, val);
559 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
560 let lhs = codegen_operand(fx, &lhs_rhs.0);
561 let rhs = codegen_operand(fx, &lhs_rhs.1);
563 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
564 lval.write_cvalue(fx, res);
566 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
567 let lhs = codegen_operand(fx, &lhs_rhs.0);
568 let rhs = codegen_operand(fx, &lhs_rhs.1);
570 let res = if !fx.tcx.sess.overflow_checks() {
572 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
573 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
574 CValue::by_val_pair(val, is_overflow, lval.layout())
576 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
579 lval.write_cvalue(fx, res);
581 Rvalue::UnaryOp(un_op, ref operand) => {
582 let operand = codegen_operand(fx, operand);
583 let layout = operand.layout();
584 let val = operand.load_scalar(fx);
585 let res = match un_op {
586 UnOp::Not => match layout.ty.kind() {
588 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
589 CValue::by_val(res, layout)
591 ty::Uint(_) | ty::Int(_) => {
592 CValue::by_val(fx.bcx.ins().bnot(val), layout)
594 _ => unreachable!("un op Not for {:?}", layout.ty),
596 UnOp::Neg => match layout.ty.kind() {
597 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
598 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
599 _ => unreachable!("un op Neg for {:?}", layout.ty),
602 lval.write_cvalue(fx, res);
605 CastKind::Pointer(PointerCast::ReifyFnPointer),
609 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
610 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
611 match *from_ty.kind() {
612 ty::FnDef(def_id, substs) => {
613 let func_ref = fx.get_function_ref(
614 Instance::resolve_for_fn_ptr(
616 ParamEnv::reveal_all(),
621 .polymorphize(fx.tcx),
623 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
624 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
626 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
630 CastKind::Pointer(PointerCast::UnsafeFnPointer),
635 CastKind::Pointer(PointerCast::MutToConstPointer),
640 CastKind::Pointer(PointerCast::ArrayToPointer),
644 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
645 let operand = codegen_operand(fx, operand);
646 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
650 | CastKind::FloatToFloat
651 | CastKind::FloatToInt
652 | CastKind::IntToFloat
653 | CastKind::FnPtrToPtr
655 | CastKind::PointerExposeAddress
656 | CastKind::PointerFromExposedAddress,
660 let operand = codegen_operand(fx, operand);
661 let from_ty = operand.layout().ty;
662 let to_ty = fx.monomorphize(to_ty);
664 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
665 ty.builtin_deref(true)
666 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
667 has_ptr_meta(fx.tcx, pointee_ty)
672 if is_fat_ptr(fx, from_ty) {
673 if is_fat_ptr(fx, to_ty) {
674 // fat-ptr -> fat-ptr
675 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
677 // fat-ptr -> thin-ptr
678 let (ptr, _extra) = operand.load_scalar_pair(fx);
679 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
682 let to_clif_ty = fx.clif_type(to_ty).unwrap();
683 let from = operand.load_scalar(fx);
685 let res = clif_int_or_float_cast(
692 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
696 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
700 let operand = codegen_operand(fx, operand);
701 match *operand.layout().ty.kind() {
702 ty::Closure(def_id, substs) => {
703 let instance = Instance::resolve_closure(
707 ty::ClosureKind::FnOnce,
709 .expect("failed to normalize and resolve closure during codegen")
710 .polymorphize(fx.tcx);
711 let func_ref = fx.get_function_ref(instance);
712 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
713 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
715 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
718 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
719 let operand = codegen_operand(fx, operand);
720 operand.unsize_value(fx, lval);
722 Rvalue::Cast(CastKind::DynStar, ref operand, _) => {
723 let operand = codegen_operand(fx, operand);
724 operand.coerce_dyn_star(fx, lval);
726 Rvalue::Discriminant(place) => {
727 let place = codegen_place(fx, place);
728 let value = place.to_cvalue(fx);
729 crate::discriminant::codegen_get_discriminant(fx, lval, value, dest_layout);
731 Rvalue::Repeat(ref operand, times) => {
732 let operand = codegen_operand(fx, operand);
735 .eval(fx.tcx, ParamEnv::reveal_all())
737 .try_to_bits(fx.tcx.data_layout.pointer_size)
739 if operand.layout().size.bytes() == 0 {
740 // Do nothing for ZST's
741 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
742 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
743 // FIXME use emit_small_memset where possible
744 let addr = lval.to_ptr().get_addr(fx);
745 let val = operand.load_scalar(fx);
746 fx.bcx.call_memset(fx.target_config, addr, val, times);
748 let loop_block = fx.bcx.create_block();
749 let loop_block2 = fx.bcx.create_block();
750 let done_block = fx.bcx.create_block();
751 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
752 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
753 fx.bcx.ins().jump(loop_block, &[zero]);
755 fx.bcx.switch_to_block(loop_block);
756 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
757 fx.bcx.ins().brnz(done, done_block, &[]);
758 fx.bcx.ins().jump(loop_block2, &[]);
760 fx.bcx.switch_to_block(loop_block2);
761 let to = lval.place_index(fx, index);
762 to.write_cvalue(fx, operand);
763 let index = fx.bcx.ins().iadd_imm(index, 1);
764 fx.bcx.ins().jump(loop_block, &[index]);
766 fx.bcx.switch_to_block(done_block);
770 Rvalue::Len(place) => {
771 let place = codegen_place(fx, place);
772 let usize_layout = fx.layout_of(fx.tcx.types.usize);
773 let len = codegen_array_len(fx, place);
774 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
776 Rvalue::ShallowInitBox(ref operand, content_ty) => {
777 let content_ty = fx.monomorphize(content_ty);
778 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
779 let operand = codegen_operand(fx, operand);
780 let operand = operand.load_scalar(fx);
781 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
783 Rvalue::NullaryOp(null_op, ty) => {
784 assert!(lval.layout().ty.is_sized(fx.tcx, ParamEnv::reveal_all()));
785 let layout = fx.layout_of(fx.monomorphize(ty));
786 let val = match null_op {
787 NullOp::SizeOf => layout.size.bytes(),
788 NullOp::AlignOf => layout.align.abi.bytes(),
790 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
791 lval.write_cvalue(fx, val);
793 Rvalue::Aggregate(ref kind, ref operands) => {
794 let (variant_index, variant_dest, active_field_index) = match **kind {
795 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
796 let variant_dest = lval.downcast_variant(fx, variant_index);
797 (variant_index, variant_dest, active_field_index)
799 _ => (VariantIdx::from_u32(0), lval, None),
801 if active_field_index.is_some() {
802 assert_eq!(operands.len(), 1);
804 for (i, operand) in operands.iter().enumerate() {
805 let operand = codegen_operand(fx, operand);
806 let field_index = active_field_index.unwrap_or(i);
807 let to = if let mir::AggregateKind::Array(_) = **kind {
808 let index = fx.bcx.ins().iconst(fx.pointer_type, field_index as i64);
809 variant_dest.place_index(fx, index)
811 variant_dest.place_field(fx, mir::Field::new(field_index))
813 to.write_cvalue(fx, operand);
815 crate::discriminant::codegen_set_discriminant(fx, lval, variant_index);
819 StatementKind::StorageLive(_)
820 | StatementKind::StorageDead(_)
821 | StatementKind::Deinit(_)
822 | StatementKind::ConstEvalCounter
824 | StatementKind::FakeRead(..)
825 | StatementKind::Retag { .. }
826 | StatementKind::AscribeUserType(..) => {}
828 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
829 StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
830 // We ignore `assume` intrinsics, they are only useful for optimizations
831 NonDivergingIntrinsic::Assume(_) => {}
832 NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
837 let dst = codegen_operand(fx, dst);
840 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
841 .expect("Expected pointer");
842 let dst = dst.load_scalar(fx);
843 let src = codegen_operand(fx, src).load_scalar(fx);
844 let count = codegen_operand(fx, count).load_scalar(fx);
845 let elem_size: u64 = pointee.size.bytes();
846 let bytes = if elem_size != 1 {
847 fx.bcx.ins().imul_imm(count, elem_size as i64)
851 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
857 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
858 match *place.layout().ty.kind() {
859 ty::Array(_elem_ty, len) => {
860 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
861 fx.bcx.ins().iconst(fx.pointer_type, len)
863 ty::Slice(_elem_ty) => {
864 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
866 _ => bug!("Rvalue::Len({:?})", place),
870 pub(crate) fn codegen_place<'tcx>(
871 fx: &mut FunctionCx<'_, '_, 'tcx>,
874 let mut cplace = fx.get_local_place(place.local);
876 for elem in place.projection {
878 PlaceElem::Deref => {
879 cplace = cplace.place_deref(fx);
881 PlaceElem::OpaqueCast(ty) => cplace = cplace.place_opaque_cast(fx, ty),
882 PlaceElem::Field(field, _ty) => {
883 cplace = cplace.place_field(fx, field);
885 PlaceElem::Index(local) => {
886 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
887 cplace = cplace.place_index(fx, index);
889 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
890 let offset: u64 = offset;
891 let index = if !from_end {
892 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
894 let len = codegen_array_len(fx, cplace);
895 fx.bcx.ins().iadd_imm(len, -(offset as i64))
897 cplace = cplace.place_index(fx, index);
899 PlaceElem::Subslice { from, to, from_end } => {
900 // These indices are generated by slice patterns.
901 // slice[from:-to] in Python terms.
903 let from: u64 = from;
906 match cplace.layout().ty.kind() {
907 ty::Array(elem_ty, _len) => {
908 assert!(!from_end, "array subslices are never `from_end`");
909 let elem_layout = fx.layout_of(*elem_ty);
910 let ptr = cplace.to_ptr();
911 cplace = CPlace::for_ptr(
912 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
913 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
916 ty::Slice(elem_ty) => {
917 assert!(from_end, "slice subslices should be `from_end`");
918 let elem_layout = fx.layout_of(*elem_ty);
919 let (ptr, len) = cplace.to_ptr_maybe_unsized();
920 let len = len.unwrap();
921 cplace = CPlace::for_ptr_with_extra(
922 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
923 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
930 PlaceElem::Downcast(_adt_def, variant) => {
931 cplace = cplace.downcast_variant(fx, variant);
939 pub(crate) fn codegen_operand<'tcx>(
940 fx: &mut FunctionCx<'_, '_, 'tcx>,
941 operand: &Operand<'tcx>,
944 Operand::Move(place) | Operand::Copy(place) => {
945 let cplace = codegen_place(fx, *place);
948 Operand::Constant(const_) => crate::constant::codegen_constant_operand(fx, const_),
952 pub(crate) fn codegen_panic<'tcx>(
953 fx: &mut FunctionCx<'_, '_, 'tcx>,
955 source_info: mir::SourceInfo,
957 let location = fx.get_caller_location(source_info).load_scalar(fx);
959 let msg_ptr = fx.anonymous_str(msg_str);
960 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
961 let args = [msg_ptr, msg_len, location];
963 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
966 pub(crate) fn codegen_panic_nounwind<'tcx>(
967 fx: &mut FunctionCx<'_, '_, 'tcx>,
969 source_info: mir::SourceInfo,
971 let msg_ptr = fx.anonymous_str(msg_str);
972 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
973 let args = [msg_ptr, msg_len];
975 codegen_panic_inner(fx, rustc_hir::LangItem::PanicNounwind, &args, source_info.span);
978 pub(crate) fn codegen_panic_cannot_unwind<'tcx>(
979 fx: &mut FunctionCx<'_, '_, 'tcx>,
980 source_info: mir::SourceInfo,
984 codegen_panic_inner(fx, rustc_hir::LangItem::PanicCannotUnwind, &args, source_info.span);
987 fn codegen_panic_inner<'tcx>(
988 fx: &mut FunctionCx<'_, '_, 'tcx>,
989 lang_item: rustc_hir::LangItem,
997 .unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
999 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
1000 let symbol_name = fx.tcx.symbol_name(instance).name;
1004 args.iter().map(|&arg| AbiParam::new(fx.bcx.func.dfg.value_type(arg))).collect(),
1009 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);