3 struct PrintOnPanic<F: Fn() -> String>(F);
4 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
6 if ::std::thread::panicking() {
7 println!("{}", (self.0)());
12 pub fn trans_mono_item<'a, 'tcx: 'a>(
13 tcx: TyCtxt<'a, 'tcx, 'tcx>,
15 module: &mut Module<impl Backend>,
16 caches: &mut Caches<'tcx>,
17 ccx: &mut crate::constant::ConstantCx,
18 mono_item: MonoItem<'tcx>,
21 MonoItem::Fn(inst) => {
22 let _inst_guard = PrintOnPanic(|| format!("{:?}", inst));
23 let _mir_guard = PrintOnPanic(|| {
26 | InstanceDef::DropGlue(_, _)
27 | InstanceDef::Virtual(_, _)
28 if inst.def_id().krate == LOCAL_CRATE =>
30 let mut mir = ::std::io::Cursor::new(Vec::new());
31 crate::rustc_mir::util::write_mir_pretty(
37 String::from_utf8(mir.into_inner()).unwrap()
40 | InstanceDef::DropGlue(_, _)
41 | InstanceDef::Virtual(_, _)
42 | InstanceDef::FnPtrShim(_, _)
43 | InstanceDef::ClosureOnceShim { .. }
44 | InstanceDef::CloneShim(_, _) => {
45 // FIXME fix write_mir_pretty for these instances
46 format!("{:#?}", tcx.instance_mir(inst.def))
48 InstanceDef::Intrinsic(_) => bug!("tried to codegen intrinsic"),
52 trans_fn(tcx, isa, module, ccx, caches, inst);
54 MonoItem::Static(def_id) => {
55 crate::constant::codegen_static(ccx, def_id);
57 MonoItem::GlobalAsm(node_id) => tcx
59 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
63 fn trans_fn<'a, 'tcx: 'a>(
64 tcx: TyCtxt<'a, 'tcx, 'tcx>,
66 module: &mut Module<impl Backend>,
67 constants: &mut crate::constant::ConstantCx,
68 caches: &mut Caches<'tcx>,
69 instance: Instance<'tcx>,
72 let mir = tcx.instance_mir(instance.def);
74 // Step 2. Declare function
75 let (name, sig) = get_function_name_and_sig(tcx, instance);
77 .declare_function(&name, Linkage::Export, &sig)
80 // Step 3. Make FunctionBuilder
81 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
82 let mut func_ctx = FunctionBuilderContext::new();
83 let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut func, &mut func_ctx);
85 // Step 4. Predefine ebb's
86 let start_ebb = bcx.create_ebb();
87 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
88 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
89 ebb_map.insert(bb, bcx.create_ebb());
92 // Step 5. Make FunctionCx
93 let mut fx = FunctionCx {
101 assert!(!instance.substs.needs_infer());
105 local_map: HashMap::new(),
106 comments: HashMap::new(),
113 // Step 6. Codegen function
114 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
115 codegen_fn_content(&mut fx);
117 // Step 7. Write function to file for debugging
118 let mut writer = crate::pretty_clif::CommentWriter(fx.comments);
120 let mut cton = String::new();
121 if cfg!(debug_assertions) {
122 ::cranelift::codegen::write::decorate_function(&mut writer, &mut cton, &func, None)
124 let clif_file_name = format!(
126 concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
127 tcx.crate_name(LOCAL_CRATE),
128 tcx.symbol_name(instance).as_str(),
130 if let Err(e) = ::std::fs::write(clif_file_name, cton.as_bytes()) {
131 tcx.sess.warn(&format!("err writing clif file: {:?}", e));
135 // Step 8. Verify function
136 verify_func(tcx, writer, &func);
138 // Step 9. Define function
139 // TODO: cranelift doesn't yet support some of the things needed
140 if should_codegen(tcx.sess) {
141 caches.context.func = func;
143 .define_function(func_id, &mut caches.context)
145 caches.context.clear();
149 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
150 let flags = settings::Flags::new(settings::builder());
151 match ::cranelift::codegen::verify_function(&func, &flags) {
154 tcx.sess.err(&format!("{:?}", err));
155 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
158 Some(Box::new(writer)),
162 .fatal(&format!("cretonne verify error:\n{}", pretty_error));
167 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
168 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
169 if bb_data.is_cleanup {
170 // Unwinding after panicking is not supported
174 let ebb = fx.get_ebb(bb);
175 fx.bcx.switch_to_block(ebb);
178 for stmt in &bb_data.statements {
179 trans_stmt(fx, ebb, stmt);
182 let mut terminator_head = "\n".to_string();
186 .fmt_head(&mut terminator_head)
188 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
189 fx.add_comment(inst, terminator_head);
191 match &bb_data.terminator().kind {
192 TerminatorKind::Goto { target } => {
193 let ebb = fx.get_ebb(*target);
194 fx.bcx.ins().jump(ebb, &[]);
196 TerminatorKind::Return => {
197 crate::abi::codegen_return(fx);
199 TerminatorKind::Assert {
206 let cond = trans_operand(fx, cond).load_value(fx);
207 // TODO HACK brz/brnz for i8/i16 is not yet implemented
208 let cond = fx.bcx.ins().uextend(types::I32, cond);
209 let target = fx.get_ebb(*target);
211 fx.bcx.ins().brnz(cond, target, &[]);
213 fx.bcx.ins().brz(cond, target, &[]);
215 fx.bcx.ins().trap(TrapCode::User(!0));
218 TerminatorKind::SwitchInt {
224 let discr = trans_operand(fx, discr).load_value(fx);
225 let mut switch = ::cranelift::frontend::Switch::new();
226 for (i, value) in values.iter().enumerate() {
227 let ebb = fx.get_ebb(targets[i]);
228 switch.set_entry(*value as u64, ebb);
230 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
231 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
233 TerminatorKind::Call {
240 crate::abi::codegen_terminator_call(fx, func, args, destination);
242 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
243 fx.bcx.ins().trap(TrapCode::User(!0));
245 TerminatorKind::Yield { .. }
246 | TerminatorKind::FalseEdges { .. }
247 | TerminatorKind::FalseUnwind { .. }
248 | TerminatorKind::DropAndReplace { .. } => {
249 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
251 TerminatorKind::Drop {
256 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
257 let ty = fx.monomorphize(&ty);
258 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
260 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
261 // we don't actually need to drop anything
263 let drop_place = trans_place(fx, location);
264 let arg_place = CPlace::temp(
267 &ty::RegionKind::ReErased,
270 mutbl: crate::rustc::hir::Mutability::MutMutable,
274 drop_place.write_place_ref(fx, arg_place);
277 unimplemented!("Drop for trait object");
280 let drop_fn_ty = drop_fn.ty(fx.tcx);
281 let arg_value = arg_place.to_cvalue(fx);
282 crate::abi::codegen_call_inner(
293 /*let mut args = if let Some(llextra) = place.llextra {
294 args2 = [place.llval, llextra];
297 args1 = [place.llval];
300 let (drop_fn, fn_ty) = match ty.sty {
302 let fn_ty = drop_fn.ty(bx.cx.tcx);
303 let sig = common::ty_fn_sig(bx.cx, fn_ty);
304 let sig = bx.tcx().normalize_erasing_late_bound_regions(
305 ty::ParamEnv::reveal_all(),
308 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
309 let vtable = args[1];
311 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
314 let value = place.to_cvalue(fx);
315 (callee::get_fn(bx.cx, drop_fn),
316 FnType::of_instance(bx.cx, &drop_fn))
319 do_call(self, bx, fn_ty, drop_fn, args,
320 Some((ReturnDest::Nothing, target)),
324 let target_ebb = fx.get_ebb(*target);
325 fx.bcx.ins().jump(target_ebb, &[]);
327 TerminatorKind::GeneratorDrop => {
328 unimplemented!("terminator GeneratorDrop");
333 fx.bcx.seal_all_blocks();
337 fn trans_stmt<'a, 'tcx: 'a>(
338 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
340 stmt: &Statement<'tcx>,
342 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
345 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
347 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
348 fx.add_comment(inst, format!("{:?}", stmt));
353 StatementKind::SetDiscriminant {
357 let place = trans_place(fx, place);
358 let layout = place.layout();
359 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
362 match layout.variants {
363 layout::Variants::Single { index } => {
364 assert_eq!(index, *variant_index);
366 layout::Variants::Tagged { .. } => {
367 let ptr = place.place_field(fx, mir::Field::new(0));
372 .discriminant_for_variant(fx.tcx, *variant_index)
374 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
375 ptr.write_cvalue(fx, discr);
377 layout::Variants::NicheFilling {
383 if *variant_index != dataful_variant {
384 let niche = place.place_field(fx, mir::Field::new(0));
385 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
386 let niche_value = ((variant_index - *niche_variants.start()) as u128)
387 .wrapping_add(niche_start);
388 // FIXME(eddyb) Check the actual primitive type here.
389 let niche_llval = if niche_value == 0 {
390 CValue::const_val(fx, niche.layout().ty, 0)
392 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
394 niche.write_cvalue(fx, niche_llval);
399 StatementKind::Assign(to_place, rval) => {
400 let lval = trans_place(fx, to_place);
401 let dest_layout = lval.layout();
403 Rvalue::Use(operand) => {
404 let val = trans_operand(fx, operand);
405 lval.write_cvalue(fx, val);
407 Rvalue::Ref(_, _, place) => {
408 let place = trans_place(fx, place);
409 place.write_place_ref(fx, lval);
411 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
412 let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
413 let lhs = trans_operand(fx, lhs);
414 let rhs = trans_operand(fx, rhs);
416 let res = match ty.sty {
417 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
419 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
422 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
424 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
425 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
426 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
427 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
429 lval.write_cvalue(fx, res);
431 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
432 let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
433 let lhs = trans_operand(fx, lhs);
434 let rhs = trans_operand(fx, rhs);
436 let res = match ty.sty {
438 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
441 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
443 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
445 lval.write_cvalue(fx, res);
447 Rvalue::UnaryOp(un_op, operand) => {
448 let operand = trans_operand(fx, operand);
449 let layout = operand.layout();
450 let val = operand.load_value(fx);
451 let res = match un_op {
453 match layout.ty.sty {
455 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
456 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
457 fx.bcx.ins().bint(types::I8, res)
459 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
460 _ => unimplemented!("un op Not for {:?}", layout.ty),
463 UnOp::Neg => match layout.ty.sty {
465 let clif_ty = fx.cton_type(layout.ty).unwrap();
466 let zero = fx.bcx.ins().iconst(clif_ty, 0);
467 fx.bcx.ins().isub(zero, val)
469 ty::Float(_) => fx.bcx.ins().fneg(val),
470 _ => unimplemented!("un op Neg for {:?}", layout.ty),
473 lval.write_cvalue(fx, CValue::ByVal(res, layout));
475 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
476 let operand = trans_operand(fx, operand);
477 let layout = fx.layout_of(ty);
478 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
480 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
481 let operand = trans_operand(fx, operand);
482 let layout = fx.layout_of(ty);
483 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
485 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
486 let operand = trans_operand(fx, operand);
487 let from_ty = operand.layout().ty;
488 match (&from_ty.sty, &to_ty.sty) {
489 (ty::Ref(..), ty::Ref(..))
490 | (ty::Ref(..), ty::RawPtr(..))
491 | (ty::RawPtr(..), ty::Ref(..))
492 | (ty::RawPtr(..), ty::RawPtr(..)) => {
493 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
495 (ty::RawPtr(..), ty::Uint(_)) | (ty::FnPtr(..), ty::Uint(_))
496 if to_ty.sty == fx.tcx.types.usize.sty =>
498 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
500 (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
501 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
503 (ty::Char, ty::Uint(_))
504 | (ty::Uint(_), ty::Char)
505 | (ty::Uint(_), ty::Int(_))
506 | (ty::Uint(_), ty::Uint(_)) => {
507 let from = operand.load_value(fx);
508 let res = crate::common::cton_intcast(
511 fx.cton_type(to_ty).unwrap(),
514 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
516 (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
517 let from = operand.load_value(fx);
518 let res = crate::common::cton_intcast(
521 fx.cton_type(to_ty).unwrap(),
524 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
526 (ty::Float(from_flt), ty::Float(to_flt)) => {
527 let from = operand.load_value(fx);
528 let res = match (from_flt, to_flt) {
529 (FloatTy::F32, FloatTy::F64) => {
530 fx.bcx.ins().fpromote(types::F64, from)
532 (FloatTy::F64, FloatTy::F32) => {
533 fx.bcx.ins().fdemote(types::F32, from)
537 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
539 (ty::Int(_), ty::Float(_)) => {
540 let from_ty = fx.cton_type(from_ty).unwrap();
541 let from = operand.load_value(fx);
542 // FIXME missing encoding for fcvt_from_sint.f32.i8
543 let from = if from_ty == types::I8 || from_ty == types::I16 {
544 fx.bcx.ins().sextend(types::I32, from)
548 let f_type = fx.cton_type(to_ty).unwrap();
549 let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
550 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
552 (ty::Uint(_), ty::Float(_)) => {
553 let from_ty = fx.cton_type(from_ty).unwrap();
554 let from = operand.load_value(fx);
555 // FIXME missing encoding for fcvt_from_uint.f32.i8
556 let from = if from_ty == types::I8 || from_ty == types::I16 {
557 fx.bcx.ins().uextend(types::I32, from)
561 let f_type = fx.cton_type(to_ty).unwrap();
562 let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
563 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
565 (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
566 let to_ty = fx.cton_type(to_ty).unwrap();
567 let from = operand.load_value(fx);
568 let res = if to_ty != types::I8 {
569 fx.bcx.ins().uextend(to_ty, from)
573 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
575 _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
578 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
579 unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
581 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
582 let operand = trans_operand(fx, operand);
583 operand.unsize_value(fx, lval);
585 Rvalue::Discriminant(place) => {
586 let place = trans_place(fx, place).to_cvalue(fx);
587 let discr = trans_get_discriminant(fx, place, dest_layout);
588 lval.write_cvalue(fx, discr);
590 Rvalue::Repeat(operand, times) => {
591 let operand = trans_operand(fx, operand);
593 let index = fx.bcx.ins().iconst(fx.module.pointer_type(), i as i64);
594 let to = lval.place_index(fx, index);
595 to.write_cvalue(fx, operand);
598 Rvalue::Len(place) => {
599 let place = trans_place(fx, place);
600 let usize_layout = fx.layout_of(fx.tcx.types.usize);
601 let len = match place.layout().ty.sty {
602 ty::Array(_elem_ty, len) => {
603 let len = crate::constant::force_eval_const(fx, len)
604 .unwrap_usize(fx.tcx) as i64;
605 fx.bcx.ins().iconst(fx.module.pointer_type(), len)
607 ty::Slice(_elem_ty) => match place {
608 CPlace::Addr(_, size, _) => size.unwrap(),
609 CPlace::Var(_, _) => unreachable!(),
611 _ => bug!("Rvalue::Len({:?})", place),
613 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
615 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
616 use crate::rustc::middle::lang_items::ExchangeMallocFnLangItem;
618 let usize_type = fx.cton_type(fx.tcx.types.usize).unwrap();
619 let (size, align) = fx.layout_of(content_ty).size_and_align();
620 let llsize = fx.bcx.ins().iconst(usize_type, size.bytes() as i64);
621 let llalign = fx.bcx.ins().iconst(usize_type, align.abi() as i64);
622 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
625 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
630 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
633 let instance = ty::Instance::mono(fx.tcx, def_id);
634 let func_ref = fx.get_function_ref(instance);
635 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
636 let ptr = fx.bcx.inst_results(call)[0];
637 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
639 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
643 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
645 let ty_size = fx.layout_of(ty).size.bytes();
646 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
647 lval.write_cvalue(fx, val);
649 Rvalue::Aggregate(kind, operands) => match **kind {
650 AggregateKind::Array(_ty) => {
651 for (i, operand) in operands.into_iter().enumerate() {
652 let operand = trans_operand(fx, operand);
653 let index = fx.bcx.ins().iconst(fx.module.pointer_type(), i as i64);
654 let to = lval.place_index(fx, index);
655 to.write_cvalue(fx, operand);
658 _ => unimpl!("shouldn't exist at trans {:?}", rval),
662 StatementKind::StorageLive(_)
663 | StatementKind::StorageDead(_)
665 | StatementKind::FakeRead(..)
666 | StatementKind::Validate(_, _)
667 | StatementKind::EndRegion(_)
668 | StatementKind::AscribeUserType(..) => {}
670 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
674 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
675 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
677 dest_layout: TyLayout<'tcx>,
679 let layout = value.layout();
681 if layout.abi == layout::Abi::Uninhabited {
682 fx.bcx.ins().trap(TrapCode::User(!0));
684 match layout.variants {
685 layout::Variants::Single { index } => {
686 let discr_val = layout.ty.ty_adt_def().map_or(index as u128, |def| {
687 def.discriminant_for_variant(fx.tcx, index).val
689 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
691 layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
694 let discr = value.value_field(fx, mir::Field::new(0));
695 let discr_ty = discr.layout().ty;
696 let lldiscr = discr.load_value(fx);
697 match layout.variants {
698 layout::Variants::Single { .. } => bug!(),
699 layout::Variants::Tagged { ref tag, .. } => {
700 let signed = match tag.value {
701 layout::Int(_, signed) => signed,
704 let val = cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), signed);
705 return CValue::ByVal(val, dest_layout);
707 layout::Variants::NicheFilling {
713 let niche_llty = fx.cton_type(discr_ty).unwrap();
714 let dest_cton_ty = fx.cton_type(dest_layout.ty).unwrap();
715 if niche_variants.start() == niche_variants.end() {
719 .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
723 .iconst(dest_cton_ty, *niche_variants.start() as u64 as i64);
727 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
728 let val = fx.bcx.ins().select(b, if_true, if_false);
729 return CValue::ByVal(val, dest_layout);
731 // Rebase from niche values to discriminant values.
732 let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
733 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
734 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
735 let b = fx.bcx.ins().icmp_imm(
736 IntCC::UnsignedLessThanOrEqual,
738 *niche_variants.end() as u64 as i64,
741 cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), false);
745 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
746 let val = fx.bcx.ins().select(b, if_true, if_false);
747 return CValue::ByVal(val, dest_layout);
753 macro_rules! binop_match {
754 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
755 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
757 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
758 assert_eq!($fx.tcx.types.bool, $ret_ty);
759 let ret_layout = $fx.layout_of($ret_ty);
761 // TODO HACK no encoding for icmp.i8
762 use crate::common::cton_intcast;
764 cton_intcast($fx, $lhs, types::I64, $signed),
765 cton_intcast($fx, $rhs, types::I64, $signed),
767 let b = $fx.bcx.ins().icmp(IntCC::$cc, lhs, rhs);
769 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
771 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
772 assert_eq!($fx.tcx.types.bool, $ret_ty);
773 let ret_layout = $fx.layout_of($ret_ty);
774 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
775 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
777 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
780 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
781 let ret_layout = $fx.layout_of($ret_ty);
782 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
785 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
787 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
790 let lhs = $lhs.load_value($fx);
791 let rhs = $rhs.load_value($fx);
792 match ($bin_op, $signed) {
794 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
800 fn trans_bool_binop<'a, 'tcx: 'a>(
801 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
807 let res = binop_match! {
808 fx, bin_op, false, lhs, rhs, ty, "bool";
821 Lt (_) icmp(UnsignedLessThan);
822 Le (_) icmp(UnsignedLessThanOrEqual);
823 Ne (_) icmp(NotEqual);
824 Ge (_) icmp(UnsignedGreaterThanOrEqual);
825 Gt (_) icmp(UnsignedGreaterThan);
833 pub fn trans_int_binop<'a, 'tcx: 'a>(
834 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
841 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
845 "int binop requires lhs and rhs of same type"
849 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
865 Lt (false) icmp(UnsignedLessThan);
866 Lt (true) icmp(SignedLessThan);
867 Le (false) icmp(UnsignedLessThanOrEqual);
868 Le (true) icmp(SignedLessThanOrEqual);
869 Ne (_) icmp(NotEqual);
870 Ge (false) icmp(UnsignedGreaterThanOrEqual);
871 Ge (true) icmp(SignedGreaterThanOrEqual);
872 Gt (false) icmp(UnsignedGreaterThan);
873 Gt (true) icmp(SignedGreaterThan);
879 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
880 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
882 in_lhs: CValue<'tcx>,
883 in_rhs: CValue<'tcx>,
887 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
891 "checked int binop requires lhs and rhs of same type"
895 let lhs = in_lhs.load_value(fx);
896 let rhs = in_rhs.load_value(fx);
897 let res = match bin_op {
898 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
899 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
900 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
901 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
904 fx.bcx.ins().ushr(lhs, rhs)
906 fx.bcx.ins().sshr(lhs, rhs)
910 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
917 // TODO: check for overflow
918 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
920 let out_place = CPlace::temp(fx, out_ty);
921 let out_layout = out_place.layout();
922 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
924 out_place.to_cvalue(fx)
927 fn trans_float_binop<'a, 'tcx: 'a>(
928 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
934 let res = binop_match! {
935 fx, bin_op, false, lhs, rhs, ty, "float";
941 assert_eq!(lhs.layout().ty, ty);
942 assert_eq!(rhs.layout().ty, ty);
944 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
945 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
956 Lt (_) fcmp(LessThan);
957 Le (_) fcmp(LessThanOrEqual);
958 Ne (_) fcmp(NotEqual);
959 Ge (_) fcmp(GreaterThanOrEqual);
960 Gt (_) fcmp(GreaterThan);
968 fn trans_char_binop<'a, 'tcx: 'a>(
969 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
975 let res = binop_match! {
976 fx, bin_op, false, lhs, rhs, ty, "char";
989 Lt (_) icmp(UnsignedLessThan);
990 Le (_) icmp(UnsignedLessThanOrEqual);
991 Ne (_) icmp(NotEqual);
992 Ge (_) icmp(UnsignedGreaterThanOrEqual);
993 Gt (_) icmp(UnsignedGreaterThan);
1001 fn trans_ptr_binop<'a, 'tcx: 'a>(
1002 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1008 match lhs.layout().ty.sty {
1009 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1010 if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
1012 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1025 Lt (_) icmp(UnsignedLessThan);
1026 Le (_) icmp(UnsignedLessThanOrEqual);
1027 Ne (_) icmp(NotEqual);
1028 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1029 Gt (_) icmp(UnsignedGreaterThan);
1034 let lhs = lhs.load_value_pair(fx).0;
1035 let rhs = rhs.load_value_pair(fx).0;
1036 let res = match bin_op {
1037 BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1038 BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1039 _ => unimplemented!(
1040 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1045 assert_eq!(fx.tcx.types.bool, ret_ty);
1046 let ret_layout = fx.layout_of(ret_ty);
1047 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1050 _ => bug!("trans_ptr_binop on non ptr"),
1054 pub fn trans_place<'a, 'tcx: 'a>(
1055 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1056 place: &Place<'tcx>,
1059 Place::Local(local) => fx.get_local_place(*local),
1060 Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1061 Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1062 Place::Projection(projection) => {
1063 let base = trans_place(fx, &projection.base);
1064 match projection.elem {
1065 ProjectionElem::Deref => base.place_deref(fx),
1066 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1067 ProjectionElem::Index(local) => {
1068 let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
1069 base.place_index(fx, index)
1071 ProjectionElem::ConstantIndex {
1075 } => unimplemented!(
1076 "projection const index {:?} offset {:?} not from end",
1080 ProjectionElem::ConstantIndex {
1084 } => unimplemented!(
1085 "projection const index {:?} offset {:?} from end",
1089 ProjectionElem::Subslice { from, to } => unimplemented!(
1090 "projection subslice {:?} from {} to {}",
1095 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1101 pub fn trans_operand<'a, 'tcx>(
1102 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1103 operand: &Operand<'tcx>,
1106 Operand::Move(place) | Operand::Copy(place) => {
1107 let cplace = trans_place(fx, place);
1108 cplace.to_cvalue(fx)
1110 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),