1 use rustc::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
8 instance: Instance<'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();
18 let mut debug_context = cx
21 .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
23 // Make FunctionBuilder
24 let context = &mut cx.cached_context;
26 context.func.name = ExternalName::user(0, func_id.as_u32());
27 context.func.signature = sig;
28 context.func.collect_debug_info();
29 let mut func_ctx = FunctionBuilderContext::new();
30 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
33 let start_ebb = bcx.create_ebb();
34 let ebb_map: IndexVec<BasicBlock, Ebb> = (0..mir.basic_blocks().len()).map(|_| bcx.create_ebb()).collect();
37 let pointer_type = cx.module.target_config().pointer_type();
38 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
40 let mut fx = FunctionCx {
50 local_map: HashMap::new(),
53 constants_cx: &mut cx.constants_cx,
54 vtables: &mut cx.vtables,
55 source_info_set: indexmap::IndexSet::new(),
58 if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
59 let entry_block = fx.bcx.create_ebb();
60 fx.bcx.append_ebb_params_for_function_params(entry_block);
61 fx.bcx.switch_to_block(entry_block);
62 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
64 tcx.sess.time("codegen clif ir", || {
65 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_ebb));
66 codegen_fn_content(&mut fx);
70 // Recover all necessary data from fx, before accessing func will prevent future access to it.
71 let instance = fx.instance;
72 let mut clif_comments = fx.clif_comments;
73 let source_info_set = fx.source_info_set;
74 let local_map = fx.local_map;
76 #[cfg(debug_assertions)]
77 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
80 verify_func(tcx, &clif_comments, &context.func);
82 // Perform rust specific optimizations
83 tcx.sess.time("optimize clif ir", || {
84 crate::optimize::optimize_function(tcx, instance, context, &mut clif_comments);
88 let module = &mut cx.module;
89 tcx.sess.time("define function", || module.define_function(func_id, context).unwrap());
91 // Write optimized function to file for debugging
92 #[cfg(debug_assertions)]
94 let value_ranges = context
95 .build_value_labels_ranges(cx.module.isa())
96 .expect("value location ranges");
98 crate::pretty_clif::write_clif_file(
108 // Define debuginfo for function
109 let isa = cx.module.isa();
110 tcx.sess.time("generate debug info", || {
113 .map(|x| x.define(context, isa, &source_info_set, local_map));
116 // Clear context to make it usable for the next function
120 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
121 tcx.sess.time("verify clif ir", || {
122 let flags = settings::Flags::new(settings::builder());
123 match ::cranelift_codegen::verify_function(&func, &flags) {
126 tcx.sess.err(&format!("{:?}", err));
127 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
130 Some(Box::new(writer)),
134 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
140 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
141 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
142 if bb_data.is_cleanup {
143 // Unwinding after panicking is not supported
147 let ebb = fx.get_ebb(bb);
148 fx.bcx.switch_to_block(ebb);
151 for stmt in &bb_data.statements {
152 fx.set_debug_loc(stmt.source_info);
153 trans_stmt(fx, ebb, stmt);
156 #[cfg(debug_assertions)]
158 let mut terminator_head = "\n".to_string();
162 .fmt_head(&mut terminator_head)
164 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
165 fx.add_comment(inst, terminator_head);
168 fx.set_debug_loc(bb_data.terminator().source_info);
170 match &bb_data.terminator().kind {
171 TerminatorKind::Goto { target } => {
172 let ebb = fx.get_ebb(*target);
173 fx.bcx.ins().jump(ebb, &[]);
175 TerminatorKind::Return => {
176 crate::abi::codegen_return(fx);
178 TerminatorKind::Assert {
185 if !fx.tcx.sess.overflow_checks() {
186 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
187 let target = fx.get_ebb(*target);
188 fx.bcx.ins().jump(target, &[]);
192 let cond = trans_operand(fx, cond).load_scalar(fx);
193 let target = fx.get_ebb(*target);
194 let failure = fx.bcx.create_ebb();
196 fx.bcx.ins().brz(cond, failure, &[]);
198 fx.bcx.ins().brnz(cond, failure, &[]);
200 fx.bcx.ins().jump(target, &[]);
202 // FIXME insert bb after all other bb's to reduce the amount of jumps in the common
203 // case and improve code locality.
204 fx.bcx.switch_to_block(failure);
208 "[panic] Assert {:?} at {:?} failed.",
210 bb_data.terminator().source_info.span
215 TerminatorKind::SwitchInt {
221 let discr = trans_operand(fx, discr).load_scalar(fx);
222 let mut switch = ::cranelift_frontend::Switch::new();
223 for (i, value) in values.iter().enumerate() {
224 let ebb = fx.get_ebb(targets[i]);
225 switch.set_entry(*value as u64, ebb);
227 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
228 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
230 TerminatorKind::Call {
237 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
242 bb_data.terminator().source_info.span,
245 TerminatorKind::Resume | TerminatorKind::Abort => {
246 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
248 TerminatorKind::Unreachable => {
249 trap_unreachable(fx, "[corruption] Hit unreachable code.");
251 TerminatorKind::Yield { .. }
252 | TerminatorKind::FalseEdges { .. }
253 | TerminatorKind::FalseUnwind { .. }
254 | TerminatorKind::DropAndReplace { .. }
255 | TerminatorKind::GeneratorDrop => {
256 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
258 TerminatorKind::Drop {
263 let drop_place = trans_place(fx, location);
264 crate::abi::codegen_drop(fx, drop_place);
266 let target_ebb = fx.get_ebb(*target);
267 fx.bcx.ins().jump(target_ebb, &[]);
272 fx.bcx.seal_all_blocks();
277 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
279 stmt: &Statement<'tcx>,
281 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
283 fx.set_debug_loc(stmt.source_info);
285 #[cfg(debug_assertions)]
287 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
289 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
290 fx.add_comment(inst, format!("{:?}", stmt));
295 StatementKind::SetDiscriminant {
299 let place = trans_place(fx, place);
300 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
302 StatementKind::Assign(to_place_and_rval) => {
303 let lval = trans_place(fx, &to_place_and_rval.0);
304 let dest_layout = lval.layout();
305 match &to_place_and_rval.1 {
306 Rvalue::Use(operand) => {
307 let val = trans_operand(fx, operand);
308 lval.write_cvalue(fx, val);
310 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
311 let place = trans_place(fx, place);
312 place.write_place_ref(fx, lval);
314 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
315 let lhs = trans_operand(fx, lhs);
316 let rhs = trans_operand(fx, rhs);
318 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
319 lval.write_cvalue(fx, res);
321 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
322 let lhs = trans_operand(fx, lhs);
323 let rhs = trans_operand(fx, rhs);
325 let res = if !fx.tcx.sess.overflow_checks() {
327 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
328 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
329 CValue::by_val_pair(val, is_overflow, lval.layout())
331 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
334 lval.write_cvalue(fx, res);
336 Rvalue::UnaryOp(un_op, operand) => {
337 let operand = trans_operand(fx, operand);
338 let layout = operand.layout();
339 let val = operand.load_scalar(fx);
340 let res = match un_op {
342 match layout.ty.kind {
344 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
345 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
346 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
348 ty::Uint(_) | ty::Int(_) => {
349 CValue::by_val(fx.bcx.ins().bnot(val), layout)
351 _ => unimplemented!("un op Not for {:?}", layout.ty),
354 UnOp::Neg => match layout.ty.kind {
356 let zero = CValue::const_val(fx, layout.ty, 0);
357 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
360 CValue::by_val(fx.bcx.ins().fneg(val), layout)
362 _ => unimplemented!("un op Neg for {:?}", layout.ty),
365 lval.write_cvalue(fx, res);
367 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
368 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
369 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
371 ty::FnDef(def_id, substs) => {
372 let func_ref = fx.get_function_ref(
373 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
376 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
377 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
379 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
382 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
383 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
384 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
385 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
386 let operand = trans_operand(fx, operand);
387 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
389 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
390 let operand = trans_operand(fx, operand);
391 let from_ty = operand.layout().ty;
392 let to_ty = fx.monomorphize(to_ty);
395 fx: &FunctionCx<'_, 'tcx, impl Backend>,
398 ty.builtin_deref(true)
403 }| has_ptr_meta(fx.tcx, pointee_ty),
408 if is_fat_ptr(fx, from_ty) {
409 if is_fat_ptr(fx, to_ty) {
410 // fat-ptr -> fat-ptr
411 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
413 // fat-ptr -> thin-ptr
414 let (ptr, _extra) = operand.load_scalar_pair(fx);
415 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
417 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
418 // enum -> discriminant value
419 assert!(adt_def.is_enum());
421 ty::Uint(_) | ty::Int(_) => {}
422 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
425 let discr = crate::discriminant::codegen_get_discriminant(
430 lval.write_cvalue(fx, discr);
432 let to_clif_ty = fx.clif_type(to_ty).unwrap();
433 let from = operand.load_scalar(fx);
435 let res = clif_int_or_float_cast(
442 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
445 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
446 let operand = trans_operand(fx, operand);
447 match operand.layout().ty.kind {
448 ty::Closure(def_id, substs) => {
449 let instance = Instance::resolve_closure(
453 ty::ClosureKind::FnOnce,
455 let func_ref = fx.get_function_ref(instance);
456 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
457 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
459 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
462 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
463 let operand = trans_operand(fx, operand);
464 operand.unsize_value(fx, lval);
466 Rvalue::Discriminant(place) => {
467 let place = trans_place(fx, place);
468 let value = place.to_cvalue(fx);
470 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
471 lval.write_cvalue(fx, discr);
473 Rvalue::Repeat(operand, times) => {
474 let operand = trans_operand(fx, operand);
476 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
477 let to = lval.place_index(fx, index);
478 to.write_cvalue(fx, operand);
481 Rvalue::Len(place) => {
482 let place = trans_place(fx, place);
483 let usize_layout = fx.layout_of(fx.tcx.types.usize);
484 let len = codegen_array_len(fx, place);
485 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
487 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
488 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
490 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
491 let content_ty = fx.monomorphize(content_ty);
492 let layout = fx.layout_of(content_ty);
493 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
497 .iconst(usize_type, layout.align.abi.bytes() as i64);
498 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
501 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
506 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
509 let instance = ty::Instance::mono(fx.tcx, def_id);
510 let func_ref = fx.get_function_ref(instance);
511 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
512 let ptr = fx.bcx.inst_results(call)[0];
513 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
515 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
519 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
520 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
521 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
522 lval.write_cvalue(fx, val);
524 Rvalue::Aggregate(kind, operands) => match **kind {
525 AggregateKind::Array(_ty) => {
526 for (i, operand) in operands.into_iter().enumerate() {
527 let operand = trans_operand(fx, operand);
528 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
529 let to = lval.place_index(fx, index);
530 to.write_cvalue(fx, operand);
533 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
537 StatementKind::StorageLive(_)
538 | StatementKind::StorageDead(_)
540 | StatementKind::FakeRead(..)
541 | StatementKind::Retag { .. }
542 | StatementKind::AscribeUserType(..) => {}
544 StatementKind::InlineAsm(asm) => {
545 use syntax::ast::Name;
551 let rustc_hir::InlineAsmInner {
552 asm: asm_code, // Name
553 outputs, // Vec<Name>
555 clobbers, // Vec<Name>
558 dialect: _, // syntax::ast::AsmDialect
561 match &*asm_code.as_str() {
563 assert_eq!(inputs, &[Name::intern("r")]);
564 assert!(outputs.is_empty(), "{:?}", outputs);
568 "cpuid" | "cpuid\n" => {
569 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
571 assert_eq!(outputs.len(), 4);
572 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
576 assert_eq!(&outputs[i].constraint.as_str(), c);
577 assert!(!outputs[i].is_rw);
578 assert!(!outputs[i].is_indirect);
581 assert_eq!(clobbers, &[Name::intern("rbx")]);
584 assert!(!alignstack);
586 crate::trap::trap_unimplemented(
588 "__cpuid_count arch intrinsic is not supported",
592 assert_eq!(inputs, &[Name::intern("{ecx}")]);
594 assert_eq!(outputs.len(), 2);
595 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
596 assert_eq!(&outputs[i].constraint.as_str(), c);
597 assert!(!outputs[i].is_rw);
598 assert!(!outputs[i].is_indirect);
601 assert_eq!(clobbers, &[]);
604 assert!(!alignstack);
606 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
608 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
609 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
611 _ => unimpl!("Inline assembly is not supported"),
617 fn codegen_array_len<'tcx>(
618 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
621 match place.layout().ty.kind {
622 ty::Array(_elem_ty, len) => {
623 let len = crate::constant::force_eval_const(fx, len)
624 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
625 fx.bcx.ins().iconst(fx.pointer_type, len)
627 ty::Slice(_elem_ty) => place
628 .to_ptr_maybe_unsized(fx)
630 .expect("Length metadata for slice place"),
631 _ => bug!("Rvalue::Len({:?})", place),
635 pub fn trans_place<'tcx>(
636 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
639 let mut cplace = match &place.base {
640 PlaceBase::Local(local) => fx.get_local_place(*local),
641 PlaceBase::Static(static_) => match static_.kind {
642 StaticKind::Static => {
643 // Statics can't be generic, so `static_.ty` doesn't need to be monomorphized.
644 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
646 StaticKind::Promoted(promoted, substs) => {
647 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
648 let ty = fx.monomorphize(&static_.ty);
649 crate::constant::trans_promoted(fx, instance, promoted, ty)
654 for elem in &*place.projection {
656 PlaceElem::Deref => {
657 cplace = cplace.place_deref(fx);
659 PlaceElem::Field(field, _ty) => {
660 cplace = cplace.place_field(fx, field);
662 PlaceElem::Index(local) => {
663 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
664 cplace = cplace.place_index(fx, index);
666 PlaceElem::ConstantIndex {
671 let index = if !from_end {
672 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
674 let len = codegen_array_len(fx, cplace);
675 fx.bcx.ins().iadd_imm(len, -(offset as i64))
677 cplace = cplace.place_index(fx, index);
679 PlaceElem::Subslice { from, to, from_end } => {
680 // These indices are generated by slice patterns.
681 // slice[from:-to] in Python terms.
683 match cplace.layout().ty.kind {
684 ty::Array(elem_ty, len) => {
685 let elem_layout = fx.layout_of(elem_ty);
686 let ptr = cplace.to_ptr(fx);
687 let len = crate::constant::force_eval_const(fx, len)
688 .eval_usize(fx.tcx, ParamEnv::reveal_all());
689 cplace = CPlace::for_ptr(
690 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
691 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
694 ty::Slice(elem_ty) => {
695 assert!(from_end, "slice subslices should be `from_end`");
696 let elem_layout = fx.layout_of(elem_ty);
697 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
698 let len = len.unwrap();
699 cplace = CPlace::for_ptr_with_extra(
700 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
701 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
708 PlaceElem::Downcast(_adt_def, variant) => {
709 cplace = cplace.downcast_variant(fx, variant);
717 pub fn trans_operand<'tcx>(
718 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
719 operand: &Operand<'tcx>,
722 Operand::Move(place) | Operand::Copy(place) => {
723 let cplace = trans_place(fx, place);
726 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),