1 use rustc_middle::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'tcx, B>,
8 instance: Instance<'tcx>,
11 let tcx = cxcodegen_cx.tcx;
13 let mir = tcx.instance_mir(instance.def);
16 let (name, sig) = get_function_name_and_sig(tcx, cx.module.isa().triple(), instance, false);
17 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
19 // Make FunctionBuilder
20 let context = &mut cx.cached_context;
22 context.func.name = ExternalName::user(0, func_id.as_u32());
23 context.func.signature = sig;
24 context.func.collect_debug_info();
25 let mut func_ctx = FunctionBuilderContext::new();
26 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
29 let start_block = bcx.create_block();
30 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
33 let pointer_type = cx.module.target_config().pointer_type();
34 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
36 let mut fx = FunctionCx {
38 module: &mut cx.module,
39 global_asm: &mut cx.global_asm,
47 local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
48 caller_location: None, // set by `codegen_fn_prelude`
49 cold_blocks: EntitySet::new(),
52 constants_cx: &mut cx.constants_cx,
53 vtables: &mut cx.vtables,
54 source_info_set: indexmap::IndexSet::new(),
60 let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
63 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
64 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
65 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
67 tcx.sess.time("codegen clif ir", || {
68 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
69 codegen_fn_content(&mut fx);
73 // Recover all necessary data from fx, before accessing func will prevent future access to it.
74 let instance = fx.instance;
75 let mut clif_comments = fx.clif_comments;
76 let source_info_set = fx.source_info_set;
77 let local_map = fx.local_map;
78 let cold_blocks = fx.cold_blocks;
80 crate::pretty_clif::write_clif_file(
90 verify_func(tcx, &clif_comments, &context.func);
92 // Perform rust specific optimizations
93 tcx.sess.time("optimize clif ir", || {
94 crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
97 // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
98 // instruction, which doesn't have an encoding.
99 context.compute_cfg();
100 context.compute_domtree();
101 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
104 let module = &mut cx.module;
107 || module.define_function(
110 &mut cranelift_codegen::binemit::NullTrapSink {},
114 // Write optimized function to file for debugging
115 crate::pretty_clif::write_clif_file(
118 Some(cx.module.isa()),
124 // Define debuginfo for function
125 let isa = cx.module.isa();
126 let debug_context = &mut cx.debug_context;
127 let unwind_context = &mut cx.unwind_context;
128 tcx.sess.time("generate debug info", || {
129 if let Some(debug_context) = debug_context {
130 debug_context.define_function(instance, func_id, &name, isa, context, &source_info_set, local_map);
132 unwind_context.add_function(func_id, &context, isa);
135 // Clear context to make it usable for the next function
139 pub(crate) fn verify_func(tcx: TyCtxt<'_>, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
140 tcx.sess.time("verify clif ir", || {
141 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
142 match cranelift_codegen::verify_function(&func, &flags) {
145 tcx.sess.err(&format!("{:?}", err));
146 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
149 Some(Box::new(writer)),
153 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
159 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
160 crate::constant::check_constants(fx);
162 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
163 let block = fx.get_block(bb);
164 fx.bcx.switch_to_block(block);
166 if bb_data.is_cleanup {
167 // Unwinding after panicking is not supported
170 // FIXME once unwinding is supported uncomment next lines
171 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
172 // fx.cold_blocks.insert(block);
176 for stmt in &bb_data.statements {
177 fx.set_debug_loc(stmt.source_info);
178 trans_stmt(fx, block, stmt);
181 #[cfg(debug_assertions)]
183 let mut terminator_head = "\n".to_string();
187 .fmt_head(&mut terminator_head)
189 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
190 fx.add_comment(inst, terminator_head);
193 fx.set_debug_loc(bb_data.terminator().source_info);
195 match &bb_data.terminator().kind {
196 TerminatorKind::Goto { target } => {
197 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
198 let mut can_immediately_return = true;
199 for stmt in &fx.mir[*target].statements {
200 if let StatementKind::StorageDead(_) = stmt.kind {
202 // FIXME Can sometimes happen, see rust-lang/rust#70531
203 can_immediately_return = false;
208 if can_immediately_return {
209 crate::abi::codegen_return(fx);
214 let block = fx.get_block(*target);
215 fx.bcx.ins().jump(block, &[]);
217 TerminatorKind::Return => {
218 crate::abi::codegen_return(fx);
220 TerminatorKind::Assert {
227 if !fxcodegen_cx.tcx.sess.overflow_checks() {
228 if let mir::AssertKind::OverflowNeg(_) = *msg {
229 let target = fx.get_block(*target);
230 fx.bcx.ins().jump(target, &[]);
234 let cond = trans_operand(fx, cond).load_scalar(fx);
236 let target = fx.get_block(*target);
237 let failure = fx.bcx.create_block();
238 fx.cold_blocks.insert(failure);
241 fx.bcx.ins().brz(cond, failure, &[]);
243 fx.bcx.ins().brnz(cond, failure, &[]);
245 fx.bcx.ins().jump(target, &[]);
247 fx.bcx.switch_to_block(failure);
249 let location = fx.get_caller_location(bb_data.terminator().source_info.span).load_scalar(fx);
252 let lang_item = match msg {
253 AssertKind::BoundsCheck { ref len, ref index } => {
254 let len = trans_operand(fx, len).load_scalar(fx);
255 let index = trans_operand(fx, index).load_scalar(fx);
256 args = [index, len, location];
257 rustc_hir::lang_items::PanicBoundsCheckFnLangItem
260 let msg_str = msg.description();
261 let msg_ptr = fx.anonymous_str("assert", msg_str);
262 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
263 args = [msg_ptr, msg_len, location];
264 rustc_hir::lang_items::PanicFnLangItem
268 let def_id = fxcodegen_cx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| {
269 fxcodegen_cx.tcx.sess.span_fatal(bb_data.terminator().source_info.span, &s)
272 let instance = Instance::mono(fxcodegen_cx.tcx, def_id).polymorphize(fxcodegen_cx.tcx);
273 let symbol_name = fxcodegen_cx.tcx.symbol_name(instance).name;
275 fx.lib_call(&*symbol_name, vec![fx.pointer_type, fx.pointer_type, fx.pointer_type], vec![], &args);
277 crate::trap::trap_unreachable(fx, "panic lang item returned");
280 TerminatorKind::SwitchInt {
286 let discr = trans_operand(fx, discr).load_scalar(fx);
287 let mut switch = ::cranelift_frontend::Switch::new();
288 for (i, value) in values.iter().enumerate() {
289 let block = fx.get_block(targets[i]);
290 switch.set_entry(*value, block);
292 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
293 switch.emit(&mut fx.bcx, discr, otherwise_block);
295 TerminatorKind::Call {
303 fxcodegen_cx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
312 TerminatorKind::InlineAsm {
319 crate::inline_asm::codegen_inline_asm(
321 bb_data.terminator().source_info.span,
328 Some(destination) => {
329 let destination_block = fx.get_block(destination);
330 fx.bcx.ins().jump(destination_block, &[]);
333 crate::trap::trap_unreachable(fx, "[corruption] Returned from noreturn inline asm");
337 TerminatorKind::Resume | TerminatorKind::Abort => {
338 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
340 TerminatorKind::Unreachable => {
341 trap_unreachable(fx, "[corruption] Hit unreachable code.");
343 TerminatorKind::Yield { .. }
344 | TerminatorKind::FalseEdge { .. }
345 | TerminatorKind::FalseUnwind { .. }
346 | TerminatorKind::DropAndReplace { .. }
347 | TerminatorKind::GeneratorDrop => {
348 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
350 TerminatorKind::Drop {
355 let drop_place = trans_place(fx, *place);
356 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
358 let target_block = fx.get_block(*target);
359 fx.bcx.ins().jump(target_block, &[]);
364 fx.bcx.seal_all_blocks();
369 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
370 #[allow(unused_variables)]
372 stmt: &Statement<'tcx>,
374 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
376 fx.set_debug_loc(stmt.source_info);
378 #[cfg(false_debug_assertions)]
380 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
382 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
383 fx.add_comment(inst, format!("{:?}", stmt));
388 StatementKind::SetDiscriminant {
392 let place = trans_place(fx, **place);
393 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
395 StatementKind::Assign(to_place_and_rval) => {
396 let lval = trans_place(fx, to_place_and_rval.0);
397 let dest_layout = lval.layout();
398 match &to_place_and_rval.1 {
399 Rvalue::Use(operand) => {
400 let val = trans_operand(fx, operand);
401 lval.write_cvalue(fx, val);
403 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
404 let place = trans_place(fx, *place);
405 place.write_place_ref(fx, lval);
407 Rvalue::ThreadLocalRef(def_id) => {
408 let val = crate::constant::codegen_tls_ref(fx, *def_id, lval.layout());
409 lval.write_cvalue(fx, val);
411 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
412 let lhs = trans_operand(fx, lhs);
413 let rhs = trans_operand(fx, rhs);
415 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
416 lval.write_cvalue(fx, res);
418 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
419 let lhs = trans_operand(fx, lhs);
420 let rhs = trans_operand(fx, rhs);
422 let res = if !fxcodegen_cx.tcx.sess.overflow_checks() {
424 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
425 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
426 CValue::by_val_pair(val, is_overflow, lval.layout())
428 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
431 lval.write_cvalue(fx, res);
433 Rvalue::UnaryOp(un_op, operand) => {
434 let operand = trans_operand(fx, operand);
435 let layout = operand.layout();
436 let val = operand.load_scalar(fx);
437 let res = match un_op {
439 match layout.ty.kind {
441 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
442 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
444 ty::Uint(_) | ty::Int(_) => {
445 CValue::by_val(fx.bcx.ins().bnot(val), layout)
447 _ => unreachable!("un op Not for {:?}", layout.ty),
450 UnOp::Neg => match layout.ty.kind {
451 ty::Int(IntTy::I128) => {
452 // FIXME remove this case once ineg.i128 works
453 let zero = CValue::const_val(fx, layout, 0);
454 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
457 CValue::by_val(fx.bcx.ins().ineg(val), layout)
460 CValue::by_val(fx.bcx.ins().fneg(val), layout)
462 _ => unreachable!("un op Neg for {:?}", layout.ty),
465 lval.write_cvalue(fx, res);
467 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
468 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fxcodegen_cx.tcx));
469 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
471 ty::FnDef(def_id, substs) => {
472 let func_ref = fx.get_function_ref(
473 Instance::resolve_for_fn_ptr(fxcodegen_cx.tcx, ParamEnv::reveal_all(), def_id, substs)
475 .polymorphize(fxcodegen_cx.tcx),
477 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
478 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
480 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
483 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
484 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
485 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
486 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
487 let operand = trans_operand(fx, operand);
488 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
490 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
491 let operand = trans_operand(fx, operand);
492 let from_ty = operand.layout().ty;
493 let to_ty = fx.monomorphize(to_ty);
496 fx: &FunctionCx<'_, 'tcx, impl Backend>,
499 ty.builtin_deref(true)
504 }| has_ptr_meta(fxcodegen_cx.tcx, pointee_ty),
509 if is_fat_ptr(fx, from_ty) {
510 if is_fat_ptr(fx, to_ty) {
511 // fat-ptr -> fat-ptr
512 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
514 // fat-ptr -> thin-ptr
515 let (ptr, _extra) = operand.load_scalar_pair(fx);
516 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
518 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
519 // enum -> discriminant value
520 assert!(adt_def.is_enum());
522 ty::Uint(_) | ty::Int(_) => {}
523 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
526 use rustc_target::abi::{TagEncoding, Int, Variants};
528 match &operand.layout().variants {
529 Variants::Single { index } => {
530 let discr = operand.layout().ty.discriminant_for_variant(fxcodegen_cx.tcx, *index).unwrap();
531 let discr = if discr.ty.is_signed() {
532 rustc_middle::mir::interpret::sign_extend(discr.val, fx.layout_of(discr.ty).size)
537 let discr = CValue::const_val(fx, fx.layout_of(to_ty), discr);
538 lval.write_cvalue(fx, discr);
543 tag_encoding: TagEncoding::Direct,
546 let cast_to = fx.clif_type(dest_layout.ty).unwrap();
548 // Read the tag/niche-encoded discriminant from memory.
549 let encoded_discr = operand.value_field(fx, mir::Field::new(*tag_field));
550 let encoded_discr = encoded_discr.load_scalar(fx);
552 // Decode the discriminant (specifically if it's niche-encoded).
553 let signed = match tag.value {
554 Int(_, signed) => signed,
557 let val = clif_intcast(fx, encoded_discr, cast_to, signed);
558 let val = CValue::by_val(val, dest_layout);
559 lval.write_cvalue(fx, val);
561 Variants::Multiple { ..} => unreachable!(),
564 let to_clif_ty = fx.clif_type(to_ty).unwrap();
565 let from = operand.load_scalar(fx);
567 let res = clif_int_or_float_cast(
574 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
577 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
578 let operand = trans_operand(fx, operand);
579 match operand.layout().ty.kind {
580 ty::Closure(def_id, substs) => {
581 let instance = Instance::resolve_closure(
585 ty::ClosureKind::FnOnce,
586 ).polymorphize(fxcodegen_cx.tcx);
587 let func_ref = fx.get_function_ref(instance);
588 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
589 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
591 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
594 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
595 let operand = trans_operand(fx, operand);
596 operand.unsize_value(fx, lval);
598 Rvalue::Discriminant(place) => {
599 let place = trans_place(fx, *place);
600 let value = place.to_cvalue(fx);
602 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
603 lval.write_cvalue(fx, discr);
605 Rvalue::Repeat(operand, times) => {
606 let operand = trans_operand(fx, operand);
609 .eval(fxcodegen_cx.tcx, ParamEnv::reveal_all())
611 .try_to_bits(fxcodegen_cx.tcx.data_layout.pointer_size)
614 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
615 let to = lval.place_index(fx, index);
616 to.write_cvalue(fx, operand);
619 Rvalue::Len(place) => {
620 let place = trans_place(fx, *place);
621 let usize_layout = fx.layout_of(fxcodegen_cx.tcx.types.usize);
622 let len = codegen_array_len(fx, place);
623 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
625 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
626 use rustc_hir::lang_items::ExchangeMallocFnLangItem;
628 let usize_type = fx.clif_type(fxcodegen_cx.tcx.types.usize).unwrap();
629 let content_ty = fx.monomorphize(content_ty);
630 let layout = fx.layout_of(content_ty);
631 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
635 .iconst(usize_type, layout.align.abi.bytes() as i64);
636 let box_layout = fx.layout_of(fxcodegen_cx.tcx.mk_box(content_ty));
639 let def_id = match fxcodegen_cx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
644 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
647 let instance = ty::Instance::mono(fxcodegen_cx.tcx, def_id).polymorphize(fxcodegen_cx.tcx);
648 let func_ref = fx.get_function_ref(instance);
649 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
650 let ptr = fx.bcx.inst_results(call)[0];
651 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
653 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
657 .is_sized(fxcodegen_cx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
658 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
659 let val = CValue::const_val(fx, fx.layout_of(fxcodegen_cx.tcx.types.usize), ty_size.into());
660 lval.write_cvalue(fx, val);
662 Rvalue::Aggregate(kind, operands) => match **kind {
663 AggregateKind::Array(_ty) => {
664 for (i, operand) in operands.into_iter().enumerate() {
665 let operand = trans_operand(fx, operand);
666 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
667 let to = lval.place_index(fx, index);
668 to.write_cvalue(fx, operand);
671 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
675 StatementKind::StorageLive(_)
676 | StatementKind::StorageDead(_)
678 | StatementKind::FakeRead(..)
679 | StatementKind::Retag { .. }
680 | StatementKind::AscribeUserType(..) => {}
682 StatementKind::LlvmInlineAsm(asm) => {
683 use rustc_span::symbol::Symbol;
689 let rustc_hir::LlvmInlineAsmInner {
690 asm: asm_code, // Name
691 outputs: output_names, // Vec<LlvmInlineAsmOutput>
692 inputs: input_names, // Vec<Name>
693 clobbers, // Vec<Name>
699 match asm_code.as_str().trim() {
703 "mov %rbx, %rsi\n cpuid\n xchg %rbx, %rsi" => {
704 assert_eq!(input_names, &[Symbol::intern("{eax}"), Symbol::intern("{ecx}")]);
705 assert_eq!(output_names.len(), 4);
706 for (i, c) in (&["={eax}", "={esi}", "={ecx}", "={edx}"]).iter().enumerate() {
707 assert_eq!(&output_names[i].constraint.as_str(), c);
708 assert!(!output_names[i].is_rw);
709 assert!(!output_names[i].is_indirect);
712 assert_eq!(clobbers, &[]);
715 assert!(!alignstack);
717 assert_eq!(inputs.len(), 2);
718 let leaf = trans_operand(fx, &inputs[0].1).load_scalar(fx); // %eax
719 let subleaf = trans_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx
721 let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf);
723 assert_eq!(outputs.len(), 4);
724 trans_place(fx, outputs[0]).write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fxcodegen_cx.tcx.types.u32)));
725 trans_place(fx, outputs[1]).write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fxcodegen_cx.tcx.types.u32)));
726 trans_place(fx, outputs[2]).write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fxcodegen_cx.tcx.types.u32)));
727 trans_place(fx, outputs[3]).write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fxcodegen_cx.tcx.types.u32)));
730 assert_eq!(input_names, &[Symbol::intern("{ecx}")]);
732 assert_eq!(output_names.len(), 2);
733 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
734 assert_eq!(&output_names[i].constraint.as_str(), c);
735 assert!(!output_names[i].is_rw);
736 assert!(!output_names[i].is_indirect);
739 assert_eq!(clobbers, &[]);
742 assert!(!alignstack);
744 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
746 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
747 _ if fxcodegen_cx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") => {
748 crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
750 _ if fxcodegen_cx.tcx.symbol_name(fx.instance).name == "__alloca" => {
751 crate::trap::trap_unimplemented(fx, "Alloca is not supported");
753 // Used in sys::windows::abort_internal
755 crate::trap::trap_unimplemented(fx, "Windows abort");
757 _ => fxcodegen_cx.tcx.sess.span_fatal(stmt.source_info.span, "Inline assembly is not supported"),
763 fn codegen_array_len<'tcx>(
764 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
767 match place.layout().ty.kind {
768 ty::Array(_elem_ty, len) => {
769 let len = fx.monomorphize(&len)
770 .eval(fxcodegen_cx.tcx, ParamEnv::reveal_all())
771 .eval_usize(fxcodegen_cx.tcx, ParamEnv::reveal_all()) as i64;
772 fx.bcx.ins().iconst(fx.pointer_type, len)
774 ty::Slice(_elem_ty) => place
775 .to_ptr_maybe_unsized()
777 .expect("Length metadata for slice place"),
778 _ => bug!("Rvalue::Len({:?})", place),
782 pub(crate) fn trans_place<'tcx>(
783 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
786 let mut cplace = fx.get_local_place(place.local);
788 for elem in place.projection {
790 PlaceElem::Deref => {
791 cplace = cplace.place_deref(fx);
793 PlaceElem::Field(field, _ty) => {
794 cplace = cplace.place_field(fx, field);
796 PlaceElem::Index(local) => {
797 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
798 cplace = cplace.place_index(fx, index);
800 PlaceElem::ConstantIndex {
805 let index = if !from_end {
806 fx.bcx.ins().iconst(fx.pointer_type, i64::from(offset))
808 let len = codegen_array_len(fx, cplace);
809 fx.bcx.ins().iadd_imm(len, -i64::from(offset))
811 cplace = cplace.place_index(fx, index);
813 PlaceElem::Subslice { from, to, from_end } => {
814 // These indices are generated by slice patterns.
815 // slice[from:-to] in Python terms.
817 match cplace.layout().ty.kind {
818 ty::Array(elem_ty, _len) => {
819 assert!(!from_end, "array subslices are never `from_end`");
820 let elem_layout = fx.layout_of(elem_ty);
821 let ptr = cplace.to_ptr();
822 cplace = CPlace::for_ptr(
823 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
824 fx.layout_of(fxcodegen_cx.tcx.mk_array(elem_ty, u64::from(to) - u64::from(from))),
827 ty::Slice(elem_ty) => {
828 assert!(from_end, "slice subslices should be `from_end`");
829 let elem_layout = fx.layout_of(elem_ty);
830 let (ptr, len) = cplace.to_ptr_maybe_unsized();
831 let len = len.unwrap();
832 cplace = CPlace::for_ptr_with_extra(
833 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
834 fx.bcx.ins().iadd_imm(len, -(i64::from(from) + i64::from(to))),
841 PlaceElem::Downcast(_adt_def, variant) => {
842 cplace = cplace.downcast_variant(fx, variant);
850 pub(crate) fn trans_operand<'tcx>(
851 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
852 operand: &Operand<'tcx>,
855 Operand::Move(place) | Operand::Copy(place) => {
856 let cplace = trans_place(fx, *place);
859 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),