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 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
65 codegen_fn_content(&mut fx);
68 // Recover all necessary data from fx, before accessing func will prevent future access to it.
69 let instance = fx.instance;
70 let mut clif_comments = fx.clif_comments;
71 let source_info_set = fx.source_info_set;
72 let local_map = fx.local_map;
74 #[cfg(debug_assertions)]
75 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
78 verify_func(tcx, &clif_comments, &context.func);
80 // Perform rust specific optimizations
81 crate::optimize::optimize_function(cx.tcx, instance, context, &mut clif_comments);
84 cx.module.define_function(func_id, context).unwrap();
86 // Write optimized function to file for debugging
87 #[cfg(debug_assertions)]
89 let value_ranges = context
90 .build_value_labels_ranges(cx.module.isa())
91 .expect("value location ranges");
93 crate::pretty_clif::write_clif_file(
103 // Define debuginfo for function
104 let isa = cx.module.isa();
107 .map(|x| x.define(context, isa, &source_info_set, local_map));
109 // Clear context to make it usable for the next function
113 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
114 let flags = settings::Flags::new(settings::builder());
115 match ::cranelift_codegen::verify_function(&func, &flags) {
118 tcx.sess.err(&format!("{:?}", err));
119 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
122 Some(Box::new(writer)),
126 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
131 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
132 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
133 if bb_data.is_cleanup {
134 // Unwinding after panicking is not supported
138 let ebb = fx.get_ebb(bb);
139 fx.bcx.switch_to_block(ebb);
142 for stmt in &bb_data.statements {
143 fx.set_debug_loc(stmt.source_info);
144 trans_stmt(fx, ebb, stmt);
147 #[cfg(debug_assertions)]
149 let mut terminator_head = "\n".to_string();
153 .fmt_head(&mut terminator_head)
155 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
156 fx.add_comment(inst, terminator_head);
159 fx.set_debug_loc(bb_data.terminator().source_info);
161 match &bb_data.terminator().kind {
162 TerminatorKind::Goto { target } => {
163 let ebb = fx.get_ebb(*target);
164 fx.bcx.ins().jump(ebb, &[]);
166 TerminatorKind::Return => {
167 crate::abi::codegen_return(fx);
169 TerminatorKind::Assert {
176 if !fx.tcx.sess.overflow_checks() {
177 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
178 let target = fx.get_ebb(*target);
179 fx.bcx.ins().jump(target, &[]);
183 let cond = trans_operand(fx, cond).load_scalar(fx);
184 let target = fx.get_ebb(*target);
185 let failure = fx.bcx.create_ebb();
187 fx.bcx.ins().brz(cond, failure, &[]);
189 fx.bcx.ins().brnz(cond, failure, &[]);
191 fx.bcx.ins().jump(target, &[]);
193 // FIXME insert bb after all other bb's to reduce the amount of jumps in the common
194 // case and improve code locality.
195 fx.bcx.switch_to_block(failure);
199 "[panic] Assert {:?} at {:?} failed.",
201 bb_data.terminator().source_info.span
206 TerminatorKind::SwitchInt {
212 let discr = trans_operand(fx, discr).load_scalar(fx);
213 let mut switch = ::cranelift_frontend::Switch::new();
214 for (i, value) in values.iter().enumerate() {
215 let ebb = fx.get_ebb(targets[i]);
216 switch.set_entry(*value as u64, ebb);
218 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
219 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
221 TerminatorKind::Call {
228 crate::abi::codegen_terminator_call(
233 bb_data.terminator().source_info.span,
236 TerminatorKind::Resume | TerminatorKind::Abort => {
237 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
239 TerminatorKind::Unreachable => {
240 trap_unreachable(fx, "[corruption] Hit unreachable code.");
242 TerminatorKind::Yield { .. }
243 | TerminatorKind::FalseEdges { .. }
244 | TerminatorKind::FalseUnwind { .. }
245 | TerminatorKind::DropAndReplace { .. }
246 | TerminatorKind::GeneratorDrop => {
247 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
249 TerminatorKind::Drop {
254 let drop_place = trans_place(fx, location);
255 crate::abi::codegen_drop(fx, drop_place);
257 let target_ebb = fx.get_ebb(*target);
258 fx.bcx.ins().jump(target_ebb, &[]);
263 fx.bcx.seal_all_blocks();
268 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
270 stmt: &Statement<'tcx>,
272 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
274 fx.set_debug_loc(stmt.source_info);
276 #[cfg(debug_assertions)]
278 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
280 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
281 fx.add_comment(inst, format!("{:?}", stmt));
286 StatementKind::SetDiscriminant {
290 let place = trans_place(fx, place);
291 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
293 StatementKind::Assign(to_place_and_rval) => {
294 let lval = trans_place(fx, &to_place_and_rval.0);
295 let dest_layout = lval.layout();
296 match &to_place_and_rval.1 {
297 Rvalue::Use(operand) => {
298 let val = trans_operand(fx, operand);
299 lval.write_cvalue(fx, val);
301 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
302 let place = trans_place(fx, place);
303 place.write_place_ref(fx, lval);
305 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
306 let lhs = trans_operand(fx, lhs);
307 let rhs = trans_operand(fx, rhs);
309 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
310 lval.write_cvalue(fx, res);
312 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
313 let lhs = trans_operand(fx, lhs);
314 let rhs = trans_operand(fx, rhs);
316 let res = if !fx.tcx.sess.overflow_checks() {
318 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
319 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
320 CValue::by_val_pair(val, is_overflow, lval.layout())
322 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
325 lval.write_cvalue(fx, res);
327 Rvalue::UnaryOp(un_op, operand) => {
328 let operand = trans_operand(fx, operand);
329 let layout = operand.layout();
330 let val = operand.load_scalar(fx);
331 let res = match un_op {
333 match layout.ty.kind {
335 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
336 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
337 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
339 ty::Uint(_) | ty::Int(_) => {
340 CValue::by_val(fx.bcx.ins().bnot(val), layout)
342 _ => unimplemented!("un op Not for {:?}", layout.ty),
345 UnOp::Neg => match layout.ty.kind {
347 let zero = CValue::const_val(fx, layout.ty, 0);
348 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
351 CValue::by_val(fx.bcx.ins().fneg(val), layout)
353 _ => unimplemented!("un op Neg for {:?}", layout.ty),
356 lval.write_cvalue(fx, res);
358 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
359 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
360 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
362 ty::FnDef(def_id, substs) => {
363 let func_ref = fx.get_function_ref(
364 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
367 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
368 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
370 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
373 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
374 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
375 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
376 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
377 let operand = trans_operand(fx, operand);
378 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
380 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
381 let operand = trans_operand(fx, operand);
382 let from_ty = operand.layout().ty;
383 let to_ty = fx.monomorphize(to_ty);
386 fx: &FunctionCx<'_, 'tcx, impl Backend>,
389 ty.builtin_deref(true)
394 }| has_ptr_meta(fx.tcx, pointee_ty),
399 if is_fat_ptr(fx, from_ty) {
400 if is_fat_ptr(fx, to_ty) {
401 // fat-ptr -> fat-ptr
402 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
404 // fat-ptr -> thin-ptr
405 let (ptr, _extra) = operand.load_scalar_pair(fx);
406 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
408 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
409 // enum -> discriminant value
410 assert!(adt_def.is_enum());
412 ty::Uint(_) | ty::Int(_) => {}
413 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
416 let discr = crate::discriminant::codegen_get_discriminant(
421 lval.write_cvalue(fx, discr);
423 let to_clif_ty = fx.clif_type(to_ty).unwrap();
424 let from = operand.load_scalar(fx);
426 let res = clif_int_or_float_cast(
433 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
436 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
437 let operand = trans_operand(fx, operand);
438 match operand.layout().ty.kind {
439 ty::Closure(def_id, substs) => {
440 let instance = Instance::resolve_closure(
444 ty::ClosureKind::FnOnce,
446 let func_ref = fx.get_function_ref(instance);
447 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
448 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
450 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
453 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
454 let operand = trans_operand(fx, operand);
455 operand.unsize_value(fx, lval);
457 Rvalue::Discriminant(place) => {
458 let place = trans_place(fx, place);
459 let value = place.to_cvalue(fx);
461 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
462 lval.write_cvalue(fx, discr);
464 Rvalue::Repeat(operand, times) => {
465 let operand = trans_operand(fx, operand);
467 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
468 let to = lval.place_index(fx, index);
469 to.write_cvalue(fx, operand);
472 Rvalue::Len(place) => {
473 let place = trans_place(fx, place);
474 let usize_layout = fx.layout_of(fx.tcx.types.usize);
475 let len = codegen_array_len(fx, place);
476 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
478 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
479 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
481 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
482 let content_ty = fx.monomorphize(content_ty);
483 let layout = fx.layout_of(content_ty);
484 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
488 .iconst(usize_type, layout.align.abi.bytes() as i64);
489 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
492 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
497 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
500 let instance = ty::Instance::mono(fx.tcx, def_id);
501 let func_ref = fx.get_function_ref(instance);
502 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
503 let ptr = fx.bcx.inst_results(call)[0];
504 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
506 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
510 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
511 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
512 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
513 lval.write_cvalue(fx, val);
515 Rvalue::Aggregate(kind, operands) => match **kind {
516 AggregateKind::Array(_ty) => {
517 for (i, operand) in operands.into_iter().enumerate() {
518 let operand = trans_operand(fx, operand);
519 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
520 let to = lval.place_index(fx, index);
521 to.write_cvalue(fx, operand);
524 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
528 StatementKind::StorageLive(_)
529 | StatementKind::StorageDead(_)
531 | StatementKind::FakeRead(..)
532 | StatementKind::Retag { .. }
533 | StatementKind::AscribeUserType(..) => {}
535 StatementKind::InlineAsm(asm) => {
536 use syntax::ast::Name;
542 let rustc_hir::InlineAsmInner {
543 asm: asm_code, // Name
544 outputs, // Vec<Name>
546 clobbers, // Vec<Name>
549 dialect: _, // syntax::ast::AsmDialect
552 match &*asm_code.as_str() {
554 assert_eq!(inputs, &[Name::intern("r")]);
555 assert!(outputs.is_empty(), "{:?}", outputs);
559 "cpuid" | "cpuid\n" => {
560 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
562 assert_eq!(outputs.len(), 4);
563 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
567 assert_eq!(&outputs[i].constraint.as_str(), c);
568 assert!(!outputs[i].is_rw);
569 assert!(!outputs[i].is_indirect);
572 assert_eq!(clobbers, &[Name::intern("rbx")]);
575 assert!(!alignstack);
577 crate::trap::trap_unimplemented(
579 "__cpuid_count arch intrinsic is not supported",
583 assert_eq!(inputs, &[Name::intern("{ecx}")]);
585 assert_eq!(outputs.len(), 2);
586 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
587 assert_eq!(&outputs[i].constraint.as_str(), c);
588 assert!(!outputs[i].is_rw);
589 assert!(!outputs[i].is_indirect);
592 assert_eq!(clobbers, &[]);
595 assert!(!alignstack);
597 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
599 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
600 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
602 _ => unimpl!("Inline assembly is not supported"),
608 fn codegen_array_len<'tcx>(
609 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
612 match place.layout().ty.kind {
613 ty::Array(_elem_ty, len) => {
614 let len = crate::constant::force_eval_const(fx, len)
615 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
616 fx.bcx.ins().iconst(fx.pointer_type, len)
618 ty::Slice(_elem_ty) => place
619 .to_ptr_maybe_unsized(fx)
621 .expect("Length metadata for slice place"),
622 _ => bug!("Rvalue::Len({:?})", place),
626 pub fn trans_place<'tcx>(
627 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
630 let mut cplace = match &place.base {
631 PlaceBase::Local(local) => fx.get_local_place(*local),
632 PlaceBase::Static(static_) => match static_.kind {
633 StaticKind::Static => {
634 // Statics can't be generic, so `static_.ty` doesn't need to be monomorphized.
635 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
637 StaticKind::Promoted(promoted, substs) => {
638 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
639 let ty = fx.monomorphize(&static_.ty);
640 crate::constant::trans_promoted(fx, instance, promoted, ty)
645 for elem in &*place.projection {
647 PlaceElem::Deref => {
648 cplace = cplace.place_deref(fx);
650 PlaceElem::Field(field, _ty) => {
651 cplace = cplace.place_field(fx, field);
653 PlaceElem::Index(local) => {
654 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
655 cplace = cplace.place_index(fx, index);
657 PlaceElem::ConstantIndex {
662 let index = if !from_end {
663 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
665 let len = codegen_array_len(fx, cplace);
666 fx.bcx.ins().iadd_imm(len, -(offset as i64))
668 cplace = cplace.place_index(fx, index);
670 PlaceElem::Subslice { from, to, from_end } => {
671 // These indices are generated by slice patterns.
672 // slice[from:-to] in Python terms.
674 match cplace.layout().ty.kind {
675 ty::Array(elem_ty, len) => {
676 let elem_layout = fx.layout_of(elem_ty);
677 let ptr = cplace.to_ptr(fx);
678 let len = crate::constant::force_eval_const(fx, len)
679 .eval_usize(fx.tcx, ParamEnv::reveal_all());
680 cplace = CPlace::for_ptr(
681 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
682 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
685 ty::Slice(elem_ty) => {
686 assert!(from_end, "slice subslices should be `from_end`");
687 let elem_layout = fx.layout_of(elem_ty);
688 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
689 let len = len.unwrap();
690 cplace = CPlace::for_ptr_with_extra(
691 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
692 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
699 PlaceElem::Downcast(_adt_def, variant) => {
700 cplace = cplace.downcast_variant(fx, variant);
708 pub fn trans_operand<'tcx>(
709 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
710 operand: &Operand<'tcx>,
713 Operand::Move(place) | Operand::Copy(place) => {
714 let cplace = trans_place(fx, place);
717 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),