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;
8 use rustc_middle::ty::SymbolName;
10 use indexmap::IndexSet;
12 use crate::constant::ConstantCx;
13 use crate::prelude::*;
14 use crate::pretty_clif::CommentWriter;
16 struct CodegenedFunction<'tcx> {
17 instance: Instance<'tcx>,
18 symbol_name: SymbolName<'tcx>,
21 clif_comments: CommentWriter,
22 source_info_set: IndexSet<SourceInfo>,
23 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
26 pub(crate) fn codegen_and_compile_fn<'tcx>(
27 cx: &mut crate::CodegenCx<'tcx>,
28 cached_context: &mut Context,
29 module: &mut dyn Module,
30 instance: Instance<'tcx>,
34 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
36 let cached_func = std::mem::replace(&mut cached_context.func, Function::new());
37 let codegened_func = codegen_fn(cx, cached_func, module, instance);
39 compile_fn(cx, cached_context, module, codegened_func);
43 cx: &mut crate::CodegenCx<'tcx>,
44 cached_func: Function,
45 module: &mut dyn Module,
46 instance: Instance<'tcx>,
47 ) -> CodegenedFunction<'tcx> {
48 debug_assert!(!instance.substs.needs_infer());
52 let mir = tcx.instance_mir(instance.def);
53 let _mir_guard = crate::PrintOnPanic(|| {
54 let mut buf = Vec::new();
55 with_no_trimmed_paths!({
56 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
59 String::from_utf8_lossy(&buf).into_owned()
63 let symbol_name = tcx.symbol_name(instance);
64 let sig = get_function_sig(tcx, module.isa().triple(), instance);
65 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
67 // Make the FunctionBuilder
68 let mut func_ctx = FunctionBuilderContext::new();
69 let mut func = cached_func;
71 func.name = ExternalName::user(0, func_id.as_u32());
73 func.collect_debug_info();
75 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
78 let start_block = bcx.create_block();
79 let block_map: IndexVec<BasicBlock, Block> =
80 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
83 let target_config = module.target_config();
84 let pointer_type = target_config.pointer_type();
85 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
87 let mut fx = FunctionCx {
93 constants_cx: ConstantCx::new(),
98 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
102 local_map: IndexVec::with_capacity(mir.local_decls.len()),
103 caller_location: None, // set by `codegen_fn_prelude`
106 source_info_set: indexmap::IndexSet::new(),
110 tcx.sess.time("codegen clif ir", || codegen_fn_body(&mut fx, start_block));
112 // Recover all necessary data from fx, before accessing func will prevent future access to it.
113 let instance = fx.instance;
114 let clif_comments = fx.clif_comments;
115 let source_info_set = fx.source_info_set;
116 let local_map = fx.local_map;
118 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
120 crate::pretty_clif::write_clif_file(
130 verify_func(tcx, &clif_comments, &func);
144 cx: &mut crate::CodegenCx<'tcx>,
145 cached_context: &mut Context,
146 module: &mut dyn Module,
147 codegened_func: CodegenedFunction<'tcx>,
151 let mut clif_comments = codegened_func.clif_comments;
153 // Store function in context
154 let context = cached_context;
156 context.func = codegened_func.func;
158 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
159 // instruction, which doesn't have an encoding.
160 context.compute_cfg();
161 context.compute_domtree();
162 context.eliminate_unreachable_code(module.isa()).unwrap();
163 context.dce(module.isa()).unwrap();
164 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
165 // invalidate it when it would change.
166 context.domtree.clear();
168 // Perform rust specific optimizations
169 tcx.sess.time("optimize clif ir", || {
170 crate::optimize::optimize_function(
173 codegened_func.instance,
179 #[cfg(any())] // This is never true
183 let func_clone = context.func.clone();
184 let clif_comments_clone = clif_comments.clone();
185 let mut clif = String::new();
186 for flag in module.isa().flags().iter() {
187 writeln!(clif, "set {}", flag).unwrap();
189 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
190 for isa_flag in module.isa().isa_flags().iter() {
191 write!(clif, " {}", isa_flag).unwrap();
193 writeln!(clif, "\n").unwrap();
194 crate::PrintOnPanic(move || {
195 let mut clif = clif.clone();
196 ::cranelift_codegen::write::decorate_function(
197 &mut &clif_comments_clone,
207 tcx.sess.time("define function", || {
208 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
209 module.define_function(codegened_func.func_id, context).unwrap();
212 // Write optimized function to file for debugging
213 crate::pretty_clif::write_clif_file(
217 codegened_func.instance,
222 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
223 crate::pretty_clif::write_ir_file(
225 || format!("{}.vcode", tcx.symbol_name(codegened_func.instance).name),
226 |file| file.write_all(disasm.as_bytes()),
230 // Define debuginfo for function
231 let isa = module.isa();
232 let debug_context = &mut cx.debug_context;
233 let unwind_context = &mut cx.unwind_context;
234 tcx.sess.time("generate debug info", || {
235 if let Some(debug_context) = debug_context {
236 debug_context.define_function(
237 codegened_func.instance,
238 codegened_func.func_id,
239 codegened_func.symbol_name.name,
242 &codegened_func.source_info_set,
243 codegened_func.local_map,
246 unwind_context.add_function(codegened_func.func_id, &context, isa);
250 pub(crate) fn verify_func(
252 writer: &crate::pretty_clif::CommentWriter,
255 tcx.sess.time("verify clif ir", || {
256 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
257 match cranelift_codegen::verify_function(&func, &flags) {
260 tcx.sess.err(&format!("{:?}", err));
261 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
263 Some(Box::new(writer)),
266 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
272 fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
273 if !crate::constant::check_constants(fx) {
274 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
275 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
276 // compilation should have been aborted
277 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
281 let arg_uninhabited = fx
284 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
286 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
287 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
288 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
291 fx.tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(fx, start_block));
293 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
294 let block = fx.get_block(bb);
295 fx.bcx.switch_to_block(block);
297 if bb_data.is_cleanup {
298 // Unwinding after panicking is not supported
301 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
302 // so for cleanup blocks.
306 for stmt in &bb_data.statements {
307 fx.set_debug_loc(stmt.source_info);
308 codegen_stmt(fx, block, stmt);
311 if fx.clif_comments.enabled() {
312 let mut terminator_head = "\n".to_string();
313 with_no_trimmed_paths!({
314 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
316 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
317 fx.add_comment(inst, terminator_head);
320 let source_info = bb_data.terminator().source_info;
321 fx.set_debug_loc(source_info);
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, switch_ty, targets } => {
393 let discr = codegen_operand(fx, discr).load_scalar(fx);
395 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
396 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
398 assert_eq!(targets.iter().count(), 1);
399 let (then_value, then_block) = targets.iter().next().unwrap();
400 let then_block = fx.get_block(then_block);
401 let else_block = fx.get_block(targets.otherwise());
402 let test_zero = match then_value {
405 _ => unreachable!("{:?}", targets),
408 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
409 let (discr, is_inverted) =
410 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
411 let test_zero = if is_inverted { !test_zero } else { test_zero };
412 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
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.sess.time("codegen call", || {
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::Resume | TerminatorKind::Abort => {
485 // FIXME implement unwinding
486 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
488 TerminatorKind::Unreachable => {
489 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
491 TerminatorKind::Yield { .. }
492 | TerminatorKind::FalseEdge { .. }
493 | TerminatorKind::FalseUnwind { .. }
494 | TerminatorKind::DropAndReplace { .. }
495 | TerminatorKind::GeneratorDrop => {
496 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
498 TerminatorKind::Drop { place, target, unwind: _ } => {
499 let drop_place = codegen_place(fx, *place);
500 crate::abi::codegen_drop(fx, source_info, drop_place);
502 let target_block = fx.get_block(*target);
503 fx.bcx.ins().jump(target_block, &[]);
508 fx.bcx.seal_all_blocks();
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(fx.bcx.ins().bint(types::I8, 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(IntTy::I128) => {
598 // FIXME remove this case once ineg.i128 works
600 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
601 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
603 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
604 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
605 _ => unreachable!("un op Neg for {:?}", layout.ty),
608 lval.write_cvalue(fx, res);
611 CastKind::Pointer(PointerCast::ReifyFnPointer),
615 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
616 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
617 match *from_ty.kind() {
618 ty::FnDef(def_id, substs) => {
619 let func_ref = fx.get_function_ref(
620 Instance::resolve_for_fn_ptr(
622 ParamEnv::reveal_all(),
627 .polymorphize(fx.tcx),
629 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
630 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
632 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
636 CastKind::Pointer(PointerCast::UnsafeFnPointer),
641 CastKind::Pointer(PointerCast::MutToConstPointer),
646 CastKind::Pointer(PointerCast::ArrayToPointer),
650 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
651 let operand = codegen_operand(fx, operand);
652 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
656 | CastKind::PointerExposeAddress
657 | CastKind::PointerFromExposedAddress,
661 let operand = codegen_operand(fx, operand);
662 let from_ty = operand.layout().ty;
663 let to_ty = fx.monomorphize(to_ty);
665 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
666 ty.builtin_deref(true)
667 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
668 has_ptr_meta(fx.tcx, pointee_ty)
673 if is_fat_ptr(fx, from_ty) {
674 if is_fat_ptr(fx, to_ty) {
675 // fat-ptr -> fat-ptr
676 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
678 // fat-ptr -> thin-ptr
679 let (ptr, _extra) = operand.load_scalar_pair(fx);
680 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
683 let to_clif_ty = fx.clif_type(to_ty).unwrap();
684 let from = operand.load_scalar(fx);
686 let res = clif_int_or_float_cast(
693 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
697 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
701 let operand = codegen_operand(fx, operand);
702 match *operand.layout().ty.kind() {
703 ty::Closure(def_id, substs) => {
704 let instance = Instance::resolve_closure(
708 ty::ClosureKind::FnOnce,
710 .expect("failed to normalize and resolve closure during codegen")
711 .polymorphize(fx.tcx);
712 let func_ref = fx.get_function_ref(instance);
713 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
714 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
716 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
719 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
720 let operand = codegen_operand(fx, operand);
721 operand.unsize_value(fx, lval);
723 Rvalue::Discriminant(place) => {
724 let place = codegen_place(fx, place);
725 let value = place.to_cvalue(fx);
726 crate::discriminant::codegen_get_discriminant(fx, lval, value, dest_layout);
728 Rvalue::Repeat(ref operand, times) => {
729 let operand = codegen_operand(fx, operand);
732 .eval(fx.tcx, ParamEnv::reveal_all())
734 .try_to_bits(fx.tcx.data_layout.pointer_size)
736 if operand.layout().size.bytes() == 0 {
737 // Do nothing for ZST's
738 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
739 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
740 // FIXME use emit_small_memset where possible
741 let addr = lval.to_ptr().get_addr(fx);
742 let val = operand.load_scalar(fx);
743 fx.bcx.call_memset(fx.target_config, addr, val, times);
745 let loop_block = fx.bcx.create_block();
746 let loop_block2 = fx.bcx.create_block();
747 let done_block = fx.bcx.create_block();
748 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
749 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
750 fx.bcx.ins().jump(loop_block, &[zero]);
752 fx.bcx.switch_to_block(loop_block);
753 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
754 fx.bcx.ins().brnz(done, done_block, &[]);
755 fx.bcx.ins().jump(loop_block2, &[]);
757 fx.bcx.switch_to_block(loop_block2);
758 let to = lval.place_index(fx, index);
759 to.write_cvalue(fx, operand);
760 let index = fx.bcx.ins().iadd_imm(index, 1);
761 fx.bcx.ins().jump(loop_block, &[index]);
763 fx.bcx.switch_to_block(done_block);
767 Rvalue::Len(place) => {
768 let place = codegen_place(fx, place);
769 let usize_layout = fx.layout_of(fx.tcx.types.usize);
770 let len = codegen_array_len(fx, place);
771 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
773 Rvalue::ShallowInitBox(ref operand, content_ty) => {
774 let content_ty = fx.monomorphize(content_ty);
775 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
776 let operand = codegen_operand(fx, operand);
777 let operand = operand.load_scalar(fx);
778 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
780 Rvalue::NullaryOp(null_op, ty) => {
784 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
786 let layout = fx.layout_of(fx.monomorphize(ty));
787 let val = match null_op {
788 NullOp::SizeOf => layout.size.bytes(),
789 NullOp::AlignOf => layout.align.abi.bytes(),
791 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
792 lval.write_cvalue(fx, val);
794 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
795 AggregateKind::Array(_ty) => {
796 for (i, operand) in operands.iter().enumerate() {
797 let operand = codegen_operand(fx, operand);
798 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
799 let to = lval.place_index(fx, index);
800 to.write_cvalue(fx, operand);
803 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
807 StatementKind::StorageLive(_)
808 | StatementKind::StorageDead(_)
809 | StatementKind::Deinit(_)
811 | StatementKind::FakeRead(..)
812 | StatementKind::Retag { .. }
813 | StatementKind::AscribeUserType(..) => {}
815 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
816 StatementKind::CopyNonOverlapping(inner) => {
817 let dst = codegen_operand(fx, &inner.dst);
820 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
821 .expect("Expected pointer");
822 let dst = dst.load_scalar(fx);
823 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
824 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
825 let elem_size: u64 = pointee.size.bytes();
827 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
828 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
833 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
834 match *place.layout().ty.kind() {
835 ty::Array(_elem_ty, len) => {
836 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
837 fx.bcx.ins().iconst(fx.pointer_type, len)
839 ty::Slice(_elem_ty) => {
840 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
842 _ => bug!("Rvalue::Len({:?})", place),
846 pub(crate) fn codegen_place<'tcx>(
847 fx: &mut FunctionCx<'_, '_, 'tcx>,
850 let mut cplace = fx.get_local_place(place.local);
852 for elem in place.projection {
854 PlaceElem::Deref => {
855 cplace = cplace.place_deref(fx);
857 PlaceElem::Field(field, _ty) => {
858 cplace = cplace.place_field(fx, field);
860 PlaceElem::Index(local) => {
861 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
862 cplace = cplace.place_index(fx, index);
864 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
865 let offset: u64 = offset;
866 let index = if !from_end {
867 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
869 let len = codegen_array_len(fx, cplace);
870 fx.bcx.ins().iadd_imm(len, -(offset as i64))
872 cplace = cplace.place_index(fx, index);
874 PlaceElem::Subslice { from, to, from_end } => {
875 // These indices are generated by slice patterns.
876 // slice[from:-to] in Python terms.
878 let from: u64 = from;
881 match cplace.layout().ty.kind() {
882 ty::Array(elem_ty, _len) => {
883 assert!(!from_end, "array subslices are never `from_end`");
884 let elem_layout = fx.layout_of(*elem_ty);
885 let ptr = cplace.to_ptr();
886 cplace = CPlace::for_ptr(
887 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
888 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
891 ty::Slice(elem_ty) => {
892 assert!(from_end, "slice subslices should be `from_end`");
893 let elem_layout = fx.layout_of(*elem_ty);
894 let (ptr, len) = cplace.to_ptr_maybe_unsized();
895 let len = len.unwrap();
896 cplace = CPlace::for_ptr_with_extra(
897 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
898 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
905 PlaceElem::Downcast(_adt_def, variant) => {
906 cplace = cplace.downcast_variant(fx, variant);
914 pub(crate) fn codegen_operand<'tcx>(
915 fx: &mut FunctionCx<'_, '_, 'tcx>,
916 operand: &Operand<'tcx>,
919 Operand::Move(place) | Operand::Copy(place) => {
920 let cplace = codegen_place(fx, *place);
923 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
927 pub(crate) fn codegen_panic<'tcx>(
928 fx: &mut FunctionCx<'_, '_, 'tcx>,
930 source_info: mir::SourceInfo,
932 let location = fx.get_caller_location(source_info).load_scalar(fx);
934 let msg_ptr = fx.anonymous_str(msg_str);
935 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
936 let args = [msg_ptr, msg_len, location];
938 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
941 pub(crate) fn codegen_panic_inner<'tcx>(
942 fx: &mut FunctionCx<'_, '_, 'tcx>,
943 lang_item: rustc_hir::LangItem,
948 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
950 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
951 let symbol_name = fx.tcx.symbol_name(instance).name;
956 AbiParam::new(fx.pointer_type),
957 AbiParam::new(fx.pointer_type),
958 AbiParam::new(fx.pointer_type),
964 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);