1 //! Codegen of a single function
3 use rustc_index::vec::IndexVec;
4 use rustc_middle::ty::adjustment::PointerCast;
8 pub(crate) fn codegen_fn<'tcx>(
9 cx: &mut crate::CodegenCx<'tcx, impl Module>,
10 instance: Instance<'tcx>,
16 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
17 debug_assert!(!instance.substs.needs_infer());
19 let mir = tcx.instance_mir(instance.def);
22 let (name, sig) = get_function_name_and_sig(tcx, cx.module.isa().triple(), instance, false);
23 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
25 cx.cached_context.clear();
27 // Make the FunctionBuilder
28 let mut func_ctx = FunctionBuilderContext::new();
29 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
30 func.name = ExternalName::user(0, func_id.as_u32());
32 func.collect_debug_info();
34 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
37 let start_block = bcx.create_block();
38 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len())
39 .map(|_| bcx.create_block())
43 let pointer_type = cx.module.target_config().pointer_type();
44 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
46 let mut fx = FunctionCx {
56 local_map: IndexVec::with_capacity(mir.local_decls.len()),
57 caller_location: None, // set by `codegen_fn_prelude`
58 cold_blocks: EntitySet::new(),
61 source_info_set: indexmap::IndexSet::new(),
67 let arg_uninhabited = fx.mir.args_iter().any(|arg| {
68 fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty))
75 .append_block_params_for_function_params(fx.block_map[START_BLOCK]);
76 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
77 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
79 tcx.sess.time("codegen clif ir", || {
80 tcx.sess.time("codegen prelude", || {
81 crate::abi::codegen_fn_prelude(&mut fx, start_block)
83 codegen_fn_content(&mut fx);
87 // Recover all necessary data from fx, before accessing func will prevent future access to it.
88 let instance = fx.instance;
89 let mut clif_comments = fx.clif_comments;
90 let source_info_set = fx.source_info_set;
91 let local_map = fx.local_map;
92 let cold_blocks = fx.cold_blocks;
94 // Store function in context
95 let context = &mut cx.cached_context;
98 crate::pretty_clif::write_clif_file(tcx, "unopt", None, instance, &context, &clif_comments);
101 verify_func(tcx, &clif_comments, &context.func);
103 // Perform rust specific optimizations
104 tcx.sess.time("optimize clif ir", || {
105 crate::optimize::optimize_function(
114 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
115 // instruction, which doesn't have an encoding.
116 context.compute_cfg();
117 context.compute_domtree();
118 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
119 context.dce(cx.module.isa()).unwrap();
120 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
121 // invalidate it when it would change.
122 context.domtree.clear();
124 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
127 let module = &mut cx.module;
128 tcx.sess.time("define function", || {
133 &mut cranelift_codegen::binemit::NullTrapSink {},
138 // Write optimized function to file for debugging
139 crate::pretty_clif::write_clif_file(
142 Some(cx.module.isa()),
148 if let Some(mach_compile_result) = &context.mach_compile_result {
149 if let Some(disasm) = &mach_compile_result.disasm {
150 crate::pretty_clif::write_ir_file(
152 &format!("{}.vcode", tcx.symbol_name(instance).name),
153 |file| file.write_all(disasm.as_bytes()),
158 // Define debuginfo for function
159 let isa = cx.module.isa();
160 let debug_context = &mut cx.debug_context;
161 let unwind_context = &mut cx.unwind_context;
162 tcx.sess.time("generate debug info", || {
163 if let Some(debug_context) = debug_context {
164 debug_context.define_function(
174 unwind_context.add_function(func_id, &context, isa);
177 // Clear context to make it usable for the next function
181 pub(crate) fn verify_func(
183 writer: &crate::pretty_clif::CommentWriter,
186 tcx.sess.time("verify clif ir", || {
187 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
188 match cranelift_codegen::verify_function(&func, &flags) {
191 tcx.sess.err(&format!("{:?}", err));
192 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
195 Some(Box::new(writer)),
199 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
205 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) {
206 crate::constant::check_constants(fx);
208 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
209 let block = fx.get_block(bb);
210 fx.bcx.switch_to_block(block);
212 if bb_data.is_cleanup {
213 // Unwinding after panicking is not supported
216 // FIXME once unwinding is supported uncomment next lines
217 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
218 // fx.cold_blocks.insert(block);
222 for stmt in &bb_data.statements {
223 fx.set_debug_loc(stmt.source_info);
224 codegen_stmt(fx, block, stmt);
227 #[cfg(debug_assertions)]
229 let mut terminator_head = "\n".to_string();
233 .fmt_head(&mut terminator_head)
235 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
236 fx.add_comment(inst, terminator_head);
239 fx.set_debug_loc(bb_data.terminator().source_info);
241 match &bb_data.terminator().kind {
242 TerminatorKind::Goto { target } => {
243 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
244 let mut can_immediately_return = true;
245 for stmt in &fx.mir[*target].statements {
246 if let StatementKind::StorageDead(_) = stmt.kind {
248 // FIXME Can sometimes happen, see rust-lang/rust#70531
249 can_immediately_return = false;
254 if can_immediately_return {
255 crate::abi::codegen_return(fx);
260 let block = fx.get_block(*target);
261 fx.bcx.ins().jump(block, &[]);
263 TerminatorKind::Return => {
264 crate::abi::codegen_return(fx);
266 TerminatorKind::Assert {
273 if !fx.tcx.sess.overflow_checks() {
274 if let mir::AssertKind::OverflowNeg(_) = *msg {
275 let target = fx.get_block(*target);
276 fx.bcx.ins().jump(target, &[]);
280 let cond = codegen_operand(fx, cond).load_scalar(fx);
282 let target = fx.get_block(*target);
283 let failure = fx.bcx.create_block();
284 fx.cold_blocks.insert(failure);
287 fx.bcx.ins().brz(cond, failure, &[]);
289 fx.bcx.ins().brnz(cond, failure, &[]);
291 fx.bcx.ins().jump(target, &[]);
293 fx.bcx.switch_to_block(failure);
297 AssertKind::BoundsCheck { ref len, ref index } => {
298 let len = codegen_operand(fx, len).load_scalar(fx);
299 let index = codegen_operand(fx, index).load_scalar(fx);
301 .get_caller_location(bb_data.terminator().source_info.span)
306 rustc_hir::LangItem::PanicBoundsCheck,
307 &[index, len, location],
308 bb_data.terminator().source_info.span,
312 let msg_str = msg.description();
313 codegen_panic(fx, msg_str, bb_data.terminator().source_info.span);
318 TerminatorKind::SwitchInt {
323 let discr = codegen_operand(fx, discr).load_scalar(fx);
325 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
326 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
328 assert_eq!(targets.iter().count(), 1);
329 let (then_value, then_block) = targets.iter().next().unwrap();
330 let then_block = fx.get_block(then_block);
331 let else_block = fx.get_block(targets.otherwise());
332 let test_zero = match then_value {
335 _ => unreachable!("{:?}", targets),
338 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
339 let (discr, is_inverted) =
340 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
341 let test_zero = if is_inverted { !test_zero } else { test_zero };
342 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
344 crate::optimize::peephole::make_branchable_value(&mut fx.bcx, discr);
345 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
346 &fx.bcx, discr, test_zero,
349 fx.bcx.ins().jump(then_block, &[]);
351 fx.bcx.ins().jump(else_block, &[]);
355 fx.bcx.ins().brz(discr, then_block, &[]);
356 fx.bcx.ins().jump(else_block, &[]);
358 fx.bcx.ins().brnz(discr, then_block, &[]);
359 fx.bcx.ins().jump(else_block, &[]);
363 let mut switch = ::cranelift_frontend::Switch::new();
364 for (value, block) in targets.iter() {
365 let block = fx.get_block(block);
366 switch.set_entry(value, block);
368 let otherwise_block = fx.get_block(targets.otherwise());
369 switch.emit(&mut fx.bcx, discr, otherwise_block);
372 TerminatorKind::Call {
380 fx.tcx.sess.time("codegen call", || {
381 crate::abi::codegen_terminator_call(
391 TerminatorKind::InlineAsm {
398 crate::inline_asm::codegen_inline_asm(
400 bb_data.terminator().source_info.span,
407 Some(destination) => {
408 let destination_block = fx.get_block(destination);
409 fx.bcx.ins().jump(destination_block, &[]);
412 crate::trap::trap_unreachable(
414 "[corruption] Returned from noreturn inline asm",
419 TerminatorKind::Resume | TerminatorKind::Abort => {
420 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
422 TerminatorKind::Unreachable => {
423 trap_unreachable(fx, "[corruption] Hit unreachable code.");
425 TerminatorKind::Yield { .. }
426 | TerminatorKind::FalseEdge { .. }
427 | TerminatorKind::FalseUnwind { .. }
428 | TerminatorKind::DropAndReplace { .. }
429 | TerminatorKind::GeneratorDrop => {
430 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
432 TerminatorKind::Drop {
437 let drop_place = codegen_place(fx, *place);
438 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
440 let target_block = fx.get_block(*target);
441 fx.bcx.ins().jump(target_block, &[]);
446 fx.bcx.seal_all_blocks();
450 fn codegen_stmt<'tcx>(
451 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
452 #[allow(unused_variables)] cur_block: Block,
453 stmt: &Statement<'tcx>,
455 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
457 fx.set_debug_loc(stmt.source_info);
459 #[cfg(false_debug_assertions)]
461 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
463 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
464 fx.add_comment(inst, format!("{:?}", stmt));
469 StatementKind::SetDiscriminant {
473 let place = codegen_place(fx, **place);
474 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
476 StatementKind::Assign(to_place_and_rval) => {
477 let lval = codegen_place(fx, to_place_and_rval.0);
478 let dest_layout = lval.layout();
479 match to_place_and_rval.1 {
480 Rvalue::Use(ref operand) => {
481 let val = codegen_operand(fx, operand);
482 lval.write_cvalue(fx, val);
484 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
485 let place = codegen_place(fx, place);
486 let ref_ = place.place_ref(fx, lval.layout());
487 lval.write_cvalue(fx, ref_);
489 Rvalue::ThreadLocalRef(def_id) => {
490 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
491 lval.write_cvalue(fx, val);
493 Rvalue::BinaryOp(bin_op, ref lhs, ref rhs) => {
494 let lhs = codegen_operand(fx, lhs);
495 let rhs = codegen_operand(fx, rhs);
497 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
498 lval.write_cvalue(fx, res);
500 Rvalue::CheckedBinaryOp(bin_op, ref lhs, ref rhs) => {
501 let lhs = codegen_operand(fx, lhs);
502 let rhs = codegen_operand(fx, rhs);
504 let res = if !fx.tcx.sess.overflow_checks() {
506 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
507 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
508 CValue::by_val_pair(val, is_overflow, lval.layout())
510 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
513 lval.write_cvalue(fx, res);
515 Rvalue::UnaryOp(un_op, ref operand) => {
516 let operand = codegen_operand(fx, operand);
517 let layout = operand.layout();
518 let val = operand.load_scalar(fx);
519 let res = match un_op {
520 UnOp::Not => match layout.ty.kind() {
522 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
523 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
525 ty::Uint(_) | ty::Int(_) => {
526 CValue::by_val(fx.bcx.ins().bnot(val), layout)
528 _ => unreachable!("un op Not for {:?}", layout.ty),
530 UnOp::Neg => match layout.ty.kind() {
531 ty::Int(IntTy::I128) => {
532 // FIXME remove this case once ineg.i128 works
534 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
535 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
537 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
538 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
539 _ => unreachable!("un op Neg for {:?}", layout.ty),
542 lval.write_cvalue(fx, res);
545 CastKind::Pointer(PointerCast::ReifyFnPointer),
549 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
550 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
551 match *from_ty.kind() {
552 ty::FnDef(def_id, substs) => {
553 let func_ref = fx.get_function_ref(
554 Instance::resolve_for_fn_ptr(
556 ParamEnv::reveal_all(),
561 .polymorphize(fx.tcx),
563 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
564 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
566 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
570 CastKind::Pointer(PointerCast::UnsafeFnPointer),
575 CastKind::Pointer(PointerCast::MutToConstPointer),
580 CastKind::Pointer(PointerCast::ArrayToPointer),
584 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
585 let operand = codegen_operand(fx, operand);
586 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
588 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
589 let operand = codegen_operand(fx, operand);
590 let from_ty = operand.layout().ty;
591 let to_ty = fx.monomorphize(to_ty);
594 fx: &FunctionCx<'_, 'tcx, impl Module>,
597 ty.builtin_deref(true)
603 has_ptr_meta(fx.tcx, pointee_ty)
609 if is_fat_ptr(fx, from_ty) {
610 if is_fat_ptr(fx, to_ty) {
611 // fat-ptr -> fat-ptr
612 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
614 // fat-ptr -> thin-ptr
615 let (ptr, _extra) = operand.load_scalar_pair(fx);
616 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
618 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
619 // enum -> discriminant value
620 assert!(adt_def.is_enum());
622 ty::Uint(_) | ty::Int(_) => {}
623 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
626 use rustc_target::abi::{Int, TagEncoding, Variants};
628 match operand.layout().variants {
629 Variants::Single { index } => {
633 .discriminant_for_variant(fx.tcx, index)
635 let discr = if discr.ty.is_signed() {
636 fx.layout_of(discr.ty).size.sign_extend(discr.val)
640 let discr = discr.into();
642 let discr = CValue::const_val(fx, fx.layout_of(to_ty), discr);
643 lval.write_cvalue(fx, discr);
648 tag_encoding: TagEncoding::Direct,
651 let cast_to = fx.clif_type(dest_layout.ty).unwrap();
653 // Read the tag/niche-encoded discriminant from memory.
655 operand.value_field(fx, mir::Field::new(tag_field));
656 let encoded_discr = encoded_discr.load_scalar(fx);
658 // Decode the discriminant (specifically if it's niche-encoded).
659 let signed = match tag.value {
660 Int(_, signed) => signed,
663 let val = clif_intcast(fx, encoded_discr, cast_to, signed);
664 let val = CValue::by_val(val, dest_layout);
665 lval.write_cvalue(fx, val);
667 Variants::Multiple { .. } => unreachable!(),
670 let to_clif_ty = fx.clif_type(to_ty).unwrap();
671 let from = operand.load_scalar(fx);
673 let res = clif_int_or_float_cast(
680 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
684 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
688 let operand = codegen_operand(fx, operand);
689 match *operand.layout().ty.kind() {
690 ty::Closure(def_id, substs) => {
691 let instance = Instance::resolve_closure(
695 ty::ClosureKind::FnOnce,
697 .polymorphize(fx.tcx);
698 let func_ref = fx.get_function_ref(instance);
699 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
700 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
702 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
705 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
706 let operand = codegen_operand(fx, operand);
707 operand.unsize_value(fx, lval);
709 Rvalue::Discriminant(place) => {
710 let place = codegen_place(fx, place);
711 let value = place.to_cvalue(fx);
713 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
714 lval.write_cvalue(fx, discr);
716 Rvalue::Repeat(ref operand, times) => {
717 let operand = codegen_operand(fx, operand);
720 .eval(fx.tcx, ParamEnv::reveal_all())
722 .try_to_bits(fx.tcx.data_layout.pointer_size)
724 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);
730 .call_memset(fx.cx.module.target_config(), addr, val, times);
732 let loop_block = fx.bcx.create_block();
733 let loop_block2 = fx.bcx.create_block();
734 let done_block = fx.bcx.create_block();
735 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
736 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
737 fx.bcx.ins().jump(loop_block, &[zero]);
739 fx.bcx.switch_to_block(loop_block);
740 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
741 fx.bcx.ins().brnz(done, done_block, &[]);
742 fx.bcx.ins().jump(loop_block2, &[]);
744 fx.bcx.switch_to_block(loop_block2);
745 let to = lval.place_index(fx, index);
746 to.write_cvalue(fx, operand);
747 let index = fx.bcx.ins().iadd_imm(index, 1);
748 fx.bcx.ins().jump(loop_block, &[index]);
750 fx.bcx.switch_to_block(done_block);
754 Rvalue::Len(place) => {
755 let place = codegen_place(fx, place);
756 let usize_layout = fx.layout_of(fx.tcx.types.usize);
757 let len = codegen_array_len(fx, place);
758 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
760 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
761 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
762 let content_ty = fx.monomorphize(content_ty);
763 let layout = fx.layout_of(content_ty);
764 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
768 .iconst(usize_type, layout.align.abi.bytes() as i64);
769 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
772 let def_id = match fx
775 .require(rustc_hir::LangItem::ExchangeMalloc)
781 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
784 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
785 let func_ref = fx.get_function_ref(instance);
786 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
787 let ptr = fx.bcx.inst_results(call)[0];
788 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
790 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
794 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
795 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
797 CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
798 lval.write_cvalue(fx, val);
800 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
801 AggregateKind::Array(_ty) => {
802 for (i, operand) in operands.iter().enumerate() {
803 let operand = codegen_operand(fx, operand);
804 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
805 let to = lval.place_index(fx, index);
806 to.write_cvalue(fx, operand);
809 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
813 StatementKind::StorageLive(_)
814 | StatementKind::StorageDead(_)
816 | StatementKind::FakeRead(..)
817 | StatementKind::Retag { .. }
818 | StatementKind::AscribeUserType(..) => {}
820 StatementKind::LlvmInlineAsm(asm) => {
821 use rustc_span::symbol::Symbol;
827 let rustc_hir::LlvmInlineAsmInner {
828 asm: asm_code, // Name
829 outputs: output_names, // Vec<LlvmInlineAsmOutput>
830 inputs: input_names, // Vec<Name>
831 clobbers, // Vec<Name>
837 match asm_code.as_str().trim() {
841 "mov %rbx, %rsi\n cpuid\n xchg %rbx, %rsi" => {
844 &[Symbol::intern("{eax}"), Symbol::intern("{ecx}")]
846 assert_eq!(output_names.len(), 4);
847 for (i, c) in (&["={eax}", "={esi}", "={ecx}", "={edx}"])
851 assert_eq!(&output_names[i].constraint.as_str(), c);
852 assert!(!output_names[i].is_rw);
853 assert!(!output_names[i].is_indirect);
856 assert_eq!(clobbers, &[]);
859 assert!(!alignstack);
861 assert_eq!(inputs.len(), 2);
862 let leaf = codegen_operand(fx, &inputs[0].1).load_scalar(fx); // %eax
863 let subleaf = codegen_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx
865 let (eax, ebx, ecx, edx) =
866 crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf);
868 assert_eq!(outputs.len(), 4);
869 codegen_place(fx, outputs[0])
870 .write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
871 codegen_place(fx, outputs[1])
872 .write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
873 codegen_place(fx, outputs[2])
874 .write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
875 codegen_place(fx, outputs[3])
876 .write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
879 assert_eq!(input_names, &[Symbol::intern("{ecx}")]);
881 assert_eq!(output_names.len(), 2);
882 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
883 assert_eq!(&output_names[i].constraint.as_str(), c);
884 assert!(!output_names[i].is_rw);
885 assert!(!output_names[i].is_indirect);
888 assert_eq!(clobbers, &[]);
891 assert!(!alignstack);
893 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
895 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
898 .symbol_name(fx.instance)
900 .starts_with("___chkstk") =>
902 crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
904 _ if fx.tcx.symbol_name(fx.instance).name == "__alloca" => {
905 crate::trap::trap_unimplemented(fx, "Alloca is not supported");
907 // Used in sys::windows::abort_internal
909 crate::trap::trap_unimplemented(fx, "Windows abort");
914 .span_fatal(stmt.source_info.span, "Inline assembly is not supported"),
917 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
921 fn codegen_array_len<'tcx>(
922 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
925 match *place.layout().ty.kind() {
926 ty::Array(_elem_ty, len) => {
929 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
930 fx.bcx.ins().iconst(fx.pointer_type, len)
932 ty::Slice(_elem_ty) => place
933 .to_ptr_maybe_unsized()
935 .expect("Length metadata for slice place"),
936 _ => bug!("Rvalue::Len({:?})", place),
940 pub(crate) fn codegen_place<'tcx>(
941 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
944 let mut cplace = fx.get_local_place(place.local);
946 for elem in place.projection {
948 PlaceElem::Deref => {
949 cplace = cplace.place_deref(fx);
951 PlaceElem::Field(field, _ty) => {
952 cplace = cplace.place_field(fx, field);
954 PlaceElem::Index(local) => {
955 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
956 cplace = cplace.place_index(fx, index);
958 PlaceElem::ConstantIndex {
963 let offset: u64 = offset;
964 let index = if !from_end {
965 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
967 let len = codegen_array_len(fx, cplace);
968 fx.bcx.ins().iadd_imm(len, -(offset as i64))
970 cplace = cplace.place_index(fx, index);
972 PlaceElem::Subslice { from, to, from_end } => {
973 // These indices are generated by slice patterns.
974 // slice[from:-to] in Python terms.
976 let from: u64 = from;
979 match cplace.layout().ty.kind() {
980 ty::Array(elem_ty, _len) => {
981 assert!(!from_end, "array subslices are never `from_end`");
982 let elem_layout = fx.layout_of(elem_ty);
983 let ptr = cplace.to_ptr();
984 cplace = CPlace::for_ptr(
985 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
986 fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)),
989 ty::Slice(elem_ty) => {
990 assert!(from_end, "slice subslices should be `from_end`");
991 let elem_layout = fx.layout_of(elem_ty);
992 let (ptr, len) = cplace.to_ptr_maybe_unsized();
993 let len = len.unwrap();
994 cplace = CPlace::for_ptr_with_extra(
995 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
996 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1000 _ => unreachable!(),
1003 PlaceElem::Downcast(_adt_def, variant) => {
1004 cplace = cplace.downcast_variant(fx, variant);
1012 pub(crate) fn codegen_operand<'tcx>(
1013 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
1014 operand: &Operand<'tcx>,
1017 Operand::Move(place) | Operand::Copy(place) => {
1018 let cplace = codegen_place(fx, *place);
1019 cplace.to_cvalue(fx)
1021 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
1025 pub(crate) fn codegen_panic<'tcx>(
1026 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
1030 let location = fx.get_caller_location(span).load_scalar(fx);
1032 let msg_ptr = fx.anonymous_str("assert", msg_str);
1036 .iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
1037 let args = [msg_ptr, msg_len, location];
1039 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
1042 pub(crate) fn codegen_panic_inner<'tcx>(
1043 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
1044 lang_item: rustc_hir::LangItem,
1052 .unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
1054 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
1055 let symbol_name = fx.tcx.symbol_name(instance).name;
1059 vec![fx.pointer_type, fx.pointer_type, fx.pointer_type],
1064 crate::trap::trap_unreachable(fx, "panic lang item returned");