1 use rustc::ty::adjustment::PointerCast;
5 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
6 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7 instance: Instance<'tcx>,
12 let mir = tcx.instance_mir(instance.def);
15 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17 let mut debug_context = cx
20 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
22 // FIXME reuse Function and FunctionBuilder between multiple trans_fn calls
23 let mut bcx = FunctionBuilder::new(Function::with_name_signature(ExternalName::user(0, 0), sig));
26 let start_ebb = bcx.create_ebb();
27 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
28 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
29 ebb_map.insert(bb, bcx.create_ebb());
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 {
46 local_map: HashMap::new(),
49 constants_cx: &mut cx.constants_cx,
50 caches: &mut cx.caches,
51 source_info_set: indexmap::IndexSet::new(),
54 with_unimpl_span(fx.mir.span, || {
55 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
56 codegen_fn_content(&mut fx);
59 fx.bcx.seal_all_blocks();
60 let func = fx.bcx.finalize();
62 // Recover all necessary data from fx, before accessing func will prevent future access to it.
63 let instance = fx.instance;
64 let clif_comments = fx.clif_comments;
65 let source_info_set = fx.source_info_set;
67 #[cfg(debug_assertions)]
68 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
71 verify_func(tcx, &clif_comments, &func);
74 let context = &mut cx.caches.context;
76 cx.module.define_function(func_id, context).unwrap();
78 let value_ranges = context
79 .build_value_labels_ranges(cx.module.isa())
80 .expect("value location ranges");
82 // Write optimized function to file for debugging
83 #[cfg(debug_assertions)]
84 crate::pretty_clif::write_clif_file(
93 // Define debuginfo for function
94 let isa = cx.module.isa();
97 .map(|x| x.define(tcx, context, isa, &source_info_set));
99 // Clear context to make it usable for the next function
103 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
104 let flags = settings::Flags::new(settings::builder());
105 match ::cranelift::codegen::verify_function(&func, &flags) {
108 tcx.sess.err(&format!("{:?}", err));
109 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
112 Some(Box::new(writer)),
116 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
121 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
122 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
123 if bb_data.is_cleanup {
124 // Unwinding after panicking is not supported
128 let ebb = fx.get_ebb(bb);
129 fx.bcx.switch_to_block(ebb);
132 for stmt in &bb_data.statements {
133 fx.set_debug_loc(stmt.source_info);
134 trans_stmt(fx, ebb, stmt);
137 #[cfg(debug_assertions)]
139 let mut terminator_head = "\n".to_string();
143 .fmt_head(&mut terminator_head)
145 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
146 fx.add_comment(inst, terminator_head);
149 fx.set_debug_loc(bb_data.terminator().source_info);
151 match &bb_data.terminator().kind {
152 TerminatorKind::Goto { target } => {
153 let ebb = fx.get_ebb(*target);
154 fx.bcx.ins().jump(ebb, &[]);
156 TerminatorKind::Return => {
157 crate::abi::codegen_return(fx);
159 TerminatorKind::Assert {
166 if !fx.tcx.sess.overflow_checks() {
167 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
168 let target = fx.get_ebb(*target);
169 fx.bcx.ins().jump(target, &[]);
173 let cond = trans_operand(fx, cond).load_scalar(fx);
174 // TODO HACK brz/brnz for i8/i16 is not yet implemented
175 let cond = fx.bcx.ins().uextend(types::I32, cond);
176 let target = fx.get_ebb(*target);
178 fx.bcx.ins().brnz(cond, target, &[]);
180 fx.bcx.ins().brz(cond, target, &[]);
185 "[panic] Assert {:?} at {:?} failed.",
187 bb_data.terminator().source_info.span
192 TerminatorKind::SwitchInt {
198 let discr = trans_operand(fx, discr).load_scalar(fx);
199 let mut switch = ::cranelift::frontend::Switch::new();
200 for (i, value) in values.iter().enumerate() {
201 let ebb = fx.get_ebb(targets[i]);
202 switch.set_entry(*value as u64, ebb);
204 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
205 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
207 TerminatorKind::Call {
214 crate::abi::codegen_terminator_call(fx, func, args, destination);
216 TerminatorKind::Resume | TerminatorKind::Abort => {
217 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
219 TerminatorKind::Unreachable => {
220 trap_unreachable(fx, "[corruption] Hit unreachable code.");
222 TerminatorKind::Yield { .. }
223 | TerminatorKind::FalseEdges { .. }
224 | TerminatorKind::FalseUnwind { .. }
225 | TerminatorKind::DropAndReplace { .. }
226 | TerminatorKind::GeneratorDrop => {
227 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
229 TerminatorKind::Drop {
234 let drop_place = trans_place(fx, location);
235 crate::abi::codegen_drop(fx, drop_place);
237 let target_ebb = fx.get_ebb(*target);
238 fx.bcx.ins().jump(target_ebb, &[]);
245 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
247 stmt: &Statement<'tcx>,
249 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
251 fx.set_debug_loc(stmt.source_info);
253 #[cfg(debug_assertions)]
255 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
257 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
258 fx.add_comment(inst, format!("{:?}", stmt));
263 StatementKind::SetDiscriminant {
267 let place = trans_place(fx, place);
268 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
270 StatementKind::Assign(to_place, rval) => {
271 let lval = trans_place(fx, to_place);
272 let dest_layout = lval.layout();
274 Rvalue::Use(operand) => {
275 let val = trans_operand(fx, operand);
276 lval.write_cvalue(fx, val);
278 Rvalue::Ref(_, _, place) => {
279 let place = trans_place(fx, place);
280 place.write_place_ref(fx, lval);
282 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
283 let lhs = trans_operand(fx, lhs);
284 let rhs = trans_operand(fx, rhs);
286 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
287 lval.write_cvalue(fx, res);
289 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
290 let lhs = trans_operand(fx, lhs);
291 let rhs = trans_operand(fx, rhs);
293 let res = if !fx.tcx.sess.overflow_checks() {
295 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
296 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
297 CValue::by_val_pair(val, is_overflow, lval.layout())
299 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
302 lval.write_cvalue(fx, res);
304 Rvalue::UnaryOp(un_op, operand) => {
305 let operand = trans_operand(fx, operand);
306 let layout = operand.layout();
307 let val = operand.load_scalar(fx);
308 let res = match un_op {
310 match layout.ty.sty {
312 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
313 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
314 fx.bcx.ins().bint(types::I8, res)
316 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
317 _ => unimplemented!("un op Not for {:?}", layout.ty),
320 UnOp::Neg => match layout.ty.sty {
322 let clif_ty = fx.clif_type(layout.ty).unwrap();
323 if clif_ty == types::I128 {
324 // FIXME implement it
325 crate::trap::trap_unreachable_ret_value(
328 "i128 neg is not yet supported",
332 let zero = fx.bcx.ins().iconst(clif_ty, 0);
333 fx.bcx.ins().isub(zero, val)
336 ty::Float(_) => fx.bcx.ins().fneg(val),
337 _ => unimplemented!("un op Neg for {:?}", layout.ty),
340 lval.write_cvalue(fx, CValue::by_val(res, layout));
342 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
343 let layout = fx.layout_of(ty);
345 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
348 ty::FnDef(def_id, substs) => {
349 let func_ref = fx.get_function_ref(
350 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
353 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
354 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
356 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
359 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
360 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
361 let operand = trans_operand(fx, operand);
362 let layout = fx.layout_of(ty);
363 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
365 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
366 let operand = trans_operand(fx, operand);
367 let from_ty = operand.layout().ty;
370 fx: &FunctionCx<'_, 'tcx, impl Backend>,
373 ty.builtin_deref(true)
379 fx.layout_of(pointee_ty).is_unsized()
385 if is_fat_ptr(fx, from_ty) {
386 if is_fat_ptr(fx, to_ty) {
387 // fat-ptr -> fat-ptr
388 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
390 // fat-ptr -> thin-ptr
391 let (ptr, _extra) = operand.load_scalar_pair(fx);
392 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
394 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
395 // enum -> discriminant value
396 assert!(adt_def.is_enum());
398 ty::Uint(_) | ty::Int(_) => {}
399 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
402 let discr = crate::discriminant::codegen_get_discriminant(
407 lval.write_cvalue(fx, discr);
409 let to_clif_ty = fx.clif_type(to_ty).unwrap();
410 let from = operand.load_scalar(fx);
412 let res = clif_int_or_float_cast(
419 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
422 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
423 let operand = trans_operand(fx, operand);
424 match operand.layout().ty.sty {
425 ty::Closure(def_id, substs) => {
426 let instance = Instance::resolve_closure(
430 ty::ClosureKind::FnOnce,
432 let func_ref = fx.get_function_ref(instance);
433 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
434 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
436 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
439 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
440 let operand = trans_operand(fx, operand);
441 operand.unsize_value(fx, lval);
443 Rvalue::Discriminant(place) => {
444 let place = trans_place(fx, place);
445 let value = place.to_cvalue(fx);
447 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
448 lval.write_cvalue(fx, discr);
450 Rvalue::Repeat(operand, times) => {
451 let operand = trans_operand(fx, operand);
453 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
454 let to = lval.place_index(fx, index);
455 to.write_cvalue(fx, operand);
458 Rvalue::Len(place) => {
459 let place = trans_place(fx, place);
460 let usize_layout = fx.layout_of(fx.tcx.types.usize);
461 let len = codegen_array_len(fx, place);
462 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
464 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
465 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
467 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
468 let layout = fx.layout_of(content_ty);
469 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
473 .iconst(usize_type, layout.align.abi.bytes() as i64);
474 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
477 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
482 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
485 let instance = ty::Instance::mono(fx.tcx, def_id);
486 let func_ref = fx.get_function_ref(instance);
487 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
488 let ptr = fx.bcx.inst_results(call)[0];
489 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
491 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
495 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
496 let ty_size = fx.layout_of(ty).size.bytes();
497 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
498 lval.write_cvalue(fx, val);
500 Rvalue::Aggregate(kind, operands) => match **kind {
501 AggregateKind::Array(_ty) => {
502 for (i, operand) in operands.into_iter().enumerate() {
503 let operand = trans_operand(fx, operand);
504 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
505 let to = lval.place_index(fx, index);
506 to.write_cvalue(fx, operand);
509 _ => unimpl!("shouldn't exist at trans {:?}", rval),
513 StatementKind::StorageLive(_)
514 | StatementKind::StorageDead(_)
516 | StatementKind::FakeRead(..)
517 | StatementKind::Retag { .. }
518 | StatementKind::AscribeUserType(..) => {}
520 StatementKind::InlineAsm(asm) => {
521 use syntax::ast::Name;
527 let rustc::hir::InlineAsm {
528 asm: asm_code, // Name
529 outputs, // Vec<Name>
531 clobbers, // Vec<Name>
534 dialect: _, // syntax::ast::AsmDialect
537 match &*asm_code.as_str() {
538 "cpuid" | "cpuid\n" => {
539 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
541 assert_eq!(outputs.len(), 4);
542 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
546 assert_eq!(&outputs[i].constraint.as_str(), c);
547 assert!(!outputs[i].is_rw);
548 assert!(!outputs[i].is_indirect);
551 assert_eq!(clobbers, &[Name::intern("rbx")]);
554 assert!(!alignstack);
556 crate::trap::trap_unimplemented(
558 "__cpuid_count arch intrinsic is not supported",
562 assert_eq!(inputs, &[Name::intern("{ecx}")]);
564 assert_eq!(outputs.len(), 2);
565 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
566 assert_eq!(&outputs[i].constraint.as_str(), c);
567 assert!(!outputs[i].is_rw);
568 assert!(!outputs[i].is_indirect);
571 assert_eq!(clobbers, &[]);
574 assert!(!alignstack);
576 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
578 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
579 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
581 _ => unimpl!("Inline assembly is not supported"),
587 fn codegen_array_len<'tcx>(
588 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
591 match place.layout().ty.sty {
592 ty::Array(_elem_ty, len) => {
593 let len = crate::constant::force_eval_const(fx, len)
594 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
595 fx.bcx.ins().iconst(fx.pointer_type, len)
597 ty::Slice(_elem_ty) => place
598 .to_addr_maybe_unsized(fx)
600 .expect("Length metadata for slice place"),
601 _ => bug!("Rvalue::Len({:?})", place),
605 pub fn trans_place<'tcx>(
606 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
609 let base = match &place.base {
610 PlaceBase::Local(local) => fx.get_local_place(*local),
611 PlaceBase::Static(static_) => match static_.kind {
612 StaticKind::Static => {
613 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
615 StaticKind::Promoted(promoted, substs) => {
616 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
617 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
622 trans_place_projection(fx, base, &place.projection)
625 pub fn trans_place_projection<'tcx>(
626 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
628 projection: &Option<Box<Projection<'tcx>>>,
630 let projection = if let Some(projection) = projection {
636 let base = trans_place_projection(fx, base, &projection.base);
638 match projection.elem {
639 ProjectionElem::Deref => base.place_deref(fx),
640 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
641 ProjectionElem::Index(local) => {
642 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
643 base.place_index(fx, index)
645 ProjectionElem::ConstantIndex {
650 let index = if !from_end {
651 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
653 let len = codegen_array_len(fx, base);
654 fx.bcx.ins().iadd_imm(len, -(offset as i64))
656 base.place_index(fx, index)
658 ProjectionElem::Subslice { from, to } => {
659 // These indices are generated by slice patterns.
660 // slice[from:-to] in Python terms.
662 match base.layout().ty.sty {
663 ty::Array(elem_ty, len) => {
664 let elem_layout = fx.layout_of(elem_ty);
665 let ptr = base.to_addr(fx);
666 let len = crate::constant::force_eval_const(fx, len)
667 .eval_usize(fx.tcx, ParamEnv::reveal_all());
671 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
672 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
675 ty::Slice(elem_ty) => {
676 let elem_layout = fx.layout_of(elem_ty);
677 let (ptr, len) = base.to_addr_maybe_unsized(fx);
678 let len = len.unwrap();
679 CPlace::for_addr_with_extra(
682 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
683 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
690 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
694 pub fn trans_operand<'tcx>(
695 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
696 operand: &Operand<'tcx>,
699 Operand::Move(place) | Operand::Copy(place) => {
700 let cplace = trans_place(fx, place);
703 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),