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();
35 let mut cold_ebbs = EntitySet::new();
36 for (bb, &ebb) in ebb_map.iter_enumerated() {
37 if mir.basic_blocks()[bb].is_cleanup {
38 cold_ebbs.insert(ebb);
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: HashMap::new(),
57 caller_location: None, // set by `codegen_fn_prelude`
61 constants_cx: &mut cx.constants_cx,
62 vtables: &mut cx.vtables,
63 source_info_set: indexmap::IndexSet::new(),
66 if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
67 let entry_block = fx.bcx.create_ebb();
68 fx.bcx.append_ebb_params_for_function_params(entry_block);
69 fx.bcx.switch_to_block(entry_block);
70 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
72 tcx.sess.time("codegen clif ir", || {
73 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_ebb));
74 codegen_fn_content(&mut fx);
78 // Recover all necessary data from fx, before accessing func will prevent future access to it.
79 let instance = fx.instance;
80 let mut clif_comments = fx.clif_comments;
81 let source_info_set = fx.source_info_set;
82 let local_map = fx.local_map;
83 let cold_ebbs = fx.cold_ebbs;
85 #[cfg(debug_assertions)]
86 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
89 verify_func(tcx, &clif_comments, &context.func);
91 // Perform rust specific optimizations
92 tcx.sess.time("optimize clif ir", || {
93 crate::optimize::optimize_function(tcx, instance, context, &cold_ebbs, &mut clif_comments);
97 let module = &mut cx.module;
98 tcx.sess.time("define function", || module.define_function(func_id, context).unwrap());
100 // Write optimized function to file for debugging
101 #[cfg(debug_assertions)]
103 let value_ranges = context
104 .build_value_labels_ranges(cx.module.isa())
105 .expect("value location ranges");
107 crate::pretty_clif::write_clif_file(
117 // Define debuginfo for function
118 let isa = cx.module.isa();
119 tcx.sess.time("generate debug info", || {
122 .map(|x| x.define(context, isa, &source_info_set, local_map));
125 // Clear context to make it usable for the next function
129 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
130 tcx.sess.time("verify clif ir", || {
131 let flags = settings::Flags::new(settings::builder());
132 match ::cranelift_codegen::verify_function(&func, &flags) {
135 tcx.sess.err(&format!("{:?}", err));
136 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
139 Some(Box::new(writer)),
143 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
149 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
150 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
151 if bb_data.is_cleanup {
152 // Unwinding after panicking is not supported
156 let ebb = fx.get_ebb(bb);
157 fx.bcx.switch_to_block(ebb);
160 for stmt in &bb_data.statements {
161 fx.set_debug_loc(stmt.source_info);
162 trans_stmt(fx, ebb, stmt);
165 #[cfg(debug_assertions)]
167 let mut terminator_head = "\n".to_string();
171 .fmt_head(&mut terminator_head)
173 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
174 fx.add_comment(inst, terminator_head);
177 fx.set_debug_loc(bb_data.terminator().source_info);
179 match &bb_data.terminator().kind {
180 TerminatorKind::Goto { target } => {
181 let ebb = fx.get_ebb(*target);
182 fx.bcx.ins().jump(ebb, &[]);
184 TerminatorKind::Return => {
185 crate::abi::codegen_return(fx);
187 TerminatorKind::Assert {
194 if !fx.tcx.sess.overflow_checks() {
195 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
196 let target = fx.get_ebb(*target);
197 fx.bcx.ins().jump(target, &[]);
201 let cond = trans_operand(fx, cond).load_scalar(fx);
203 let target = fx.get_ebb(*target);
204 let failure = fx.bcx.create_ebb();
205 fx.cold_ebbs.insert(failure);
208 fx.bcx.ins().brz(cond, failure, &[]);
210 fx.bcx.ins().brnz(cond, failure, &[]);
212 fx.bcx.ins().jump(target, &[]);
214 fx.bcx.switch_to_block(failure);
218 "[panic] Assert {:?} at {:?} failed.",
220 bb_data.terminator().source_info.span
225 TerminatorKind::SwitchInt {
231 let discr = trans_operand(fx, discr).load_scalar(fx);
232 let mut switch = ::cranelift_frontend::Switch::new();
233 for (i, value) in values.iter().enumerate() {
234 let ebb = fx.get_ebb(targets[i]);
235 switch.set_entry(*value as u64, ebb);
237 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
238 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
240 TerminatorKind::Call {
247 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
249 bb_data.terminator().source_info.span,
255 TerminatorKind::Resume | TerminatorKind::Abort => {
256 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
258 TerminatorKind::Unreachable => {
259 trap_unreachable(fx, "[corruption] Hit unreachable code.");
261 TerminatorKind::Yield { .. }
262 | TerminatorKind::FalseEdges { .. }
263 | TerminatorKind::FalseUnwind { .. }
264 | TerminatorKind::DropAndReplace { .. }
265 | TerminatorKind::GeneratorDrop => {
266 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
268 TerminatorKind::Drop {
273 let drop_place = trans_place(fx, location);
274 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
276 let target_ebb = fx.get_ebb(*target);
277 fx.bcx.ins().jump(target_ebb, &[]);
282 fx.bcx.seal_all_blocks();
287 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
289 stmt: &Statement<'tcx>,
291 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
293 fx.set_debug_loc(stmt.source_info);
295 #[cfg(false_debug_assertions)]
297 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
299 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
300 fx.add_comment(inst, format!("{:?}", stmt));
305 StatementKind::SetDiscriminant {
309 let place = trans_place(fx, place);
310 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
312 StatementKind::Assign(to_place_and_rval) => {
313 let lval = trans_place(fx, &to_place_and_rval.0);
314 let dest_layout = lval.layout();
315 match &to_place_and_rval.1 {
316 Rvalue::Use(operand) => {
317 let val = trans_operand(fx, operand);
318 lval.write_cvalue(fx, val);
320 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
321 let place = trans_place(fx, place);
322 place.write_place_ref(fx, lval);
324 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
325 let lhs = trans_operand(fx, lhs);
326 let rhs = trans_operand(fx, rhs);
328 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
329 lval.write_cvalue(fx, res);
331 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
332 let lhs = trans_operand(fx, lhs);
333 let rhs = trans_operand(fx, rhs);
335 let res = if !fx.tcx.sess.overflow_checks() {
337 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
338 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
339 CValue::by_val_pair(val, is_overflow, lval.layout())
341 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
344 lval.write_cvalue(fx, res);
346 Rvalue::UnaryOp(un_op, operand) => {
347 let operand = trans_operand(fx, operand);
348 let layout = operand.layout();
349 let val = operand.load_scalar(fx);
350 let res = match un_op {
352 match layout.ty.kind {
354 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
355 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
356 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
358 ty::Uint(_) | ty::Int(_) => {
359 CValue::by_val(fx.bcx.ins().bnot(val), layout)
361 _ => unimplemented!("un op Not for {:?}", layout.ty),
364 UnOp::Neg => match layout.ty.kind {
366 let zero = CValue::const_val(fx, layout, 0);
367 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
370 CValue::by_val(fx.bcx.ins().fneg(val), layout)
372 _ => unimplemented!("un op Neg for {:?}", layout.ty),
375 lval.write_cvalue(fx, res);
377 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
378 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
379 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
381 ty::FnDef(def_id, substs) => {
382 let func_ref = fx.get_function_ref(
383 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
386 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
387 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
389 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
392 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
393 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
394 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
395 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
396 let operand = trans_operand(fx, operand);
397 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
399 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
400 let operand = trans_operand(fx, operand);
401 let from_ty = operand.layout().ty;
402 let to_ty = fx.monomorphize(to_ty);
405 fx: &FunctionCx<'_, 'tcx, impl Backend>,
408 ty.builtin_deref(true)
413 }| has_ptr_meta(fx.tcx, pointee_ty),
418 if is_fat_ptr(fx, from_ty) {
419 if is_fat_ptr(fx, to_ty) {
420 // fat-ptr -> fat-ptr
421 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
423 // fat-ptr -> thin-ptr
424 let (ptr, _extra) = operand.load_scalar_pair(fx);
425 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
427 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
428 // enum -> discriminant value
429 assert!(adt_def.is_enum());
431 ty::Uint(_) | ty::Int(_) => {}
432 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
435 let discr = crate::discriminant::codegen_get_discriminant(
440 lval.write_cvalue(fx, discr);
442 let to_clif_ty = fx.clif_type(to_ty).unwrap();
443 let from = operand.load_scalar(fx);
445 let res = clif_int_or_float_cast(
452 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
455 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
456 let operand = trans_operand(fx, operand);
457 match operand.layout().ty.kind {
458 ty::Closure(def_id, substs) => {
459 let instance = Instance::resolve_closure(
463 ty::ClosureKind::FnOnce,
465 let func_ref = fx.get_function_ref(instance);
466 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
467 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
469 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
472 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
473 let operand = trans_operand(fx, operand);
474 operand.unsize_value(fx, lval);
476 Rvalue::Discriminant(place) => {
477 let place = trans_place(fx, place);
478 let value = place.to_cvalue(fx);
480 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
481 lval.write_cvalue(fx, discr);
483 Rvalue::Repeat(operand, times) => {
484 let operand = trans_operand(fx, operand);
486 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
487 let to = lval.place_index(fx, index);
488 to.write_cvalue(fx, operand);
491 Rvalue::Len(place) => {
492 let place = trans_place(fx, place);
493 let usize_layout = fx.layout_of(fx.tcx.types.usize);
494 let len = codegen_array_len(fx, place);
495 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
497 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
498 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
500 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
501 let content_ty = fx.monomorphize(content_ty);
502 let layout = fx.layout_of(content_ty);
503 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
507 .iconst(usize_type, layout.align.abi.bytes() as i64);
508 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
511 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
516 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
519 let instance = ty::Instance::mono(fx.tcx, def_id);
520 let func_ref = fx.get_function_ref(instance);
521 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
522 let ptr = fx.bcx.inst_results(call)[0];
523 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
525 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
529 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
530 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
531 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
532 lval.write_cvalue(fx, val);
534 Rvalue::Aggregate(kind, operands) => match **kind {
535 AggregateKind::Array(_ty) => {
536 for (i, operand) in operands.into_iter().enumerate() {
537 let operand = trans_operand(fx, operand);
538 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
539 let to = lval.place_index(fx, index);
540 to.write_cvalue(fx, operand);
543 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
547 StatementKind::StorageLive(_)
548 | StatementKind::StorageDead(_)
550 | StatementKind::FakeRead(..)
551 | StatementKind::Retag { .. }
552 | StatementKind::AscribeUserType(..) => {}
554 StatementKind::InlineAsm(asm) => {
555 use syntax::ast::Name;
561 let rustc_hir::InlineAsmInner {
562 asm: asm_code, // Name
563 outputs, // Vec<Name>
565 clobbers, // Vec<Name>
568 dialect: _, // syntax::ast::AsmDialect
571 match &*asm_code.as_str() {
573 assert_eq!(inputs, &[Name::intern("r")]);
574 assert!(outputs.is_empty(), "{:?}", outputs);
578 "cpuid" | "cpuid\n" => {
579 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
581 assert_eq!(outputs.len(), 4);
582 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
586 assert_eq!(&outputs[i].constraint.as_str(), c);
587 assert!(!outputs[i].is_rw);
588 assert!(!outputs[i].is_indirect);
591 assert_eq!(clobbers, &[Name::intern("rbx")]);
594 assert!(!alignstack);
596 crate::trap::trap_unimplemented(
598 "__cpuid_count arch intrinsic is not supported",
602 assert_eq!(inputs, &[Name::intern("{ecx}")]);
604 assert_eq!(outputs.len(), 2);
605 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
606 assert_eq!(&outputs[i].constraint.as_str(), c);
607 assert!(!outputs[i].is_rw);
608 assert!(!outputs[i].is_indirect);
611 assert_eq!(clobbers, &[]);
614 assert!(!alignstack);
616 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
618 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
619 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
621 _ => unimpl!("Inline assembly is not supported"),
627 fn codegen_array_len<'tcx>(
628 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
631 match place.layout().ty.kind {
632 ty::Array(_elem_ty, len) => {
633 let len = crate::constant::force_eval_const(fx, len)
634 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
635 fx.bcx.ins().iconst(fx.pointer_type, len)
637 ty::Slice(_elem_ty) => place
638 .to_ptr_maybe_unsized(fx)
640 .expect("Length metadata for slice place"),
641 _ => bug!("Rvalue::Len({:?})", place),
645 pub fn trans_place<'tcx>(
646 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
649 let mut cplace = fx.get_local_place(place.local);
651 for elem in &*place.projection {
653 PlaceElem::Deref => {
654 cplace = cplace.place_deref(fx);
656 PlaceElem::Field(field, _ty) => {
657 cplace = cplace.place_field(fx, field);
659 PlaceElem::Index(local) => {
660 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
661 cplace = cplace.place_index(fx, index);
663 PlaceElem::ConstantIndex {
668 let index = if !from_end {
669 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
671 let len = codegen_array_len(fx, cplace);
672 fx.bcx.ins().iadd_imm(len, -(offset as i64))
674 cplace = cplace.place_index(fx, index);
676 PlaceElem::Subslice { from, to, from_end } => {
677 // These indices are generated by slice patterns.
678 // slice[from:-to] in Python terms.
680 match cplace.layout().ty.kind {
681 ty::Array(elem_ty, len) => {
682 let elem_layout = fx.layout_of(elem_ty);
683 let ptr = cplace.to_ptr(fx);
684 let len = crate::constant::force_eval_const(fx, len)
685 .eval_usize(fx.tcx, ParamEnv::reveal_all());
686 cplace = CPlace::for_ptr(
687 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
688 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
691 ty::Slice(elem_ty) => {
692 assert!(from_end, "slice subslices should be `from_end`");
693 let elem_layout = fx.layout_of(elem_ty);
694 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
695 let len = len.unwrap();
696 cplace = CPlace::for_ptr_with_extra(
697 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
698 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
705 PlaceElem::Downcast(_adt_def, variant) => {
706 cplace = cplace.downcast_variant(fx, variant);
714 pub fn trans_operand<'tcx>(
715 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
716 operand: &Operand<'tcx>,
719 Operand::Move(place) | Operand::Copy(place) => {
720 let cplace = trans_place(fx, place);
723 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),