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>,
14 module: &mut Module<impl Backend>,
15 caches: &mut Caches<'tcx>,
16 ccx: &mut crate::constant::ConstantCx,
17 mono_item: MonoItem<'tcx>,
20 MonoItem::Fn(inst) => {
21 let _inst_guard = PrintOnPanic(|| format!("{:?}", inst));
22 let _mir_guard = PrintOnPanic(|| {
25 | InstanceDef::DropGlue(_, _)
26 | InstanceDef::Virtual(_, _)
27 if inst.def_id().krate == LOCAL_CRATE =>
29 let mut mir = ::std::io::Cursor::new(Vec::new());
30 crate::rustc_mir::util::write_mir_pretty(tcx, Some(inst.def_id()), &mut mir)
32 String::from_utf8(mir.into_inner()).unwrap()
35 | InstanceDef::DropGlue(_, _)
36 | InstanceDef::Virtual(_, _)
37 | InstanceDef::FnPtrShim(_, _)
38 | InstanceDef::ClosureOnceShim { .. }
39 | InstanceDef::CloneShim(_, _) => {
40 // FIXME fix write_mir_pretty for these instances
41 format!("{:#?}", tcx.instance_mir(inst.def))
43 InstanceDef::Intrinsic(_) => bug!("tried to codegen intrinsic"),
47 trans_fn(tcx, module, ccx, caches, inst);
49 MonoItem::Static(def_id) => {
50 crate::constant::codegen_static(ccx, def_id);
52 MonoItem::GlobalAsm(node_id) => tcx
54 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
58 fn trans_fn<'a, 'tcx: 'a>(
59 tcx: TyCtxt<'a, 'tcx, 'tcx>,
60 module: &mut Module<impl Backend>,
61 constants: &mut crate::constant::ConstantCx,
62 caches: &mut Caches<'tcx>,
63 instance: Instance<'tcx>,
66 let mir = tcx.instance_mir(instance.def);
68 // Step 2. Declare function
69 let (name, sig) = get_function_name_and_sig(tcx, instance);
71 .declare_function(&name, Linkage::Export, &sig)
74 // Step 3. Make FunctionBuilder
75 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
76 let mut func_ctx = FunctionBuilderContext::new();
77 let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut func, &mut func_ctx);
79 // Step 4. Predefine ebb's
80 let start_ebb = bcx.create_ebb();
81 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
82 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
83 ebb_map.insert(bb, bcx.create_ebb());
86 // Step 5. Make FunctionCx
87 let mut fx = FunctionCx {
94 assert!(!instance.substs.needs_infer());
98 local_map: HashMap::new(),
99 comments: HashMap::new(),
106 // Step 6. Codegen function
107 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
108 codegen_fn_content(&mut fx);
110 // Step 7. Write function to file for debugging
111 let mut writer = crate::pretty_clif::CommentWriter(fx.comments);
113 let mut cton = String::new();
114 if cfg!(debug_assertions) {
115 ::cranelift::codegen::write::decorate_function(&mut writer, &mut cton, &func, None)
117 let clif_file_name = "target/out/clif/".to_string() + &tcx.symbol_name(instance).as_str();
118 ::std::fs::write(clif_file_name, cton.as_bytes()).unwrap();
121 // Step 8. Verify function
122 verify_func(tcx, writer, &func);
124 // Step 9. Define function
125 // TODO: cranelift doesn't yet support some of the things needed
126 if should_codegen(tcx.sess) {
127 caches.context.func = func;
129 .define_function(func_id, &mut caches.context)
131 caches.context.clear();
135 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
136 let flags = settings::Flags::new(settings::builder());
137 match ::cranelift::codegen::verify_function(&func, &flags) {
140 tcx.sess.err(&format!("{:?}", err));
141 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
144 Some(Box::new(writer)),
148 .fatal(&format!("cretonne verify error:\n{}", pretty_error));
153 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
154 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
155 let ebb = fx.get_ebb(bb);
156 fx.bcx.switch_to_block(ebb);
159 for stmt in &bb_data.statements {
160 trans_stmt(fx, ebb, stmt);
163 let mut terminator_head = "\n".to_string();
167 .fmt_head(&mut terminator_head)
169 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
170 fx.add_comment(inst, terminator_head);
172 match &bb_data.terminator().kind {
173 TerminatorKind::Goto { target } => {
174 let ebb = fx.get_ebb(*target);
175 fx.bcx.ins().jump(ebb, &[]);
177 TerminatorKind::Return => {
178 crate::abi::codegen_return(fx);
180 TerminatorKind::Assert {
187 let cond = trans_operand(fx, cond).load_value(fx);
188 // TODO HACK brz/brnz for i8/i16 is not yet implemented
189 let cond = fx.bcx.ins().uextend(types::I32, cond);
190 let target = fx.get_ebb(*target);
192 fx.bcx.ins().brnz(cond, target, &[]);
194 fx.bcx.ins().brz(cond, target, &[]);
196 fx.bcx.ins().trap(TrapCode::User(!0));
199 TerminatorKind::SwitchInt {
205 let discr = trans_operand(fx, discr).load_value(fx);
206 let mut switch = ::cranelift::frontend::Switch::new();
207 for (i, value) in values.iter().enumerate() {
208 let ebb = fx.get_ebb(targets[i]);
209 switch.set_entry(*value as u64, ebb);
211 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
212 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
214 TerminatorKind::Call {
220 crate::abi::codegen_terminator_call(fx, func, args, destination);
222 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
223 fx.bcx.ins().trap(TrapCode::User(!0));
225 TerminatorKind::Yield { .. }
226 | TerminatorKind::FalseEdges { .. }
227 | TerminatorKind::FalseUnwind { .. }
228 | TerminatorKind::DropAndReplace { .. } => {
229 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
231 TerminatorKind::Drop {
236 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
237 let ty = fx.monomorphize(&ty);
238 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
240 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
241 // we don't actually need to drop anything
243 let drop_place = trans_place(fx, location);
244 let arg_place = CPlace::temp(
247 &ty::RegionKind::ReErased,
250 mutbl: crate::rustc::hir::Mutability::MutMutable,
254 drop_place.write_place_ref(fx, arg_place);
257 unimplemented!("Drop for trait object");
260 let drop_fn_ty = drop_fn.ty(fx.tcx);
261 let arg_value = arg_place.to_cvalue(fx);
262 crate::abi::codegen_call_inner(
273 /*let mut args = if let Some(llextra) = place.llextra {
274 args2 = [place.llval, llextra];
277 args1 = [place.llval];
280 let (drop_fn, fn_ty) = match ty.sty {
282 let fn_ty = drop_fn.ty(bx.cx.tcx);
283 let sig = common::ty_fn_sig(bx.cx, fn_ty);
284 let sig = bx.tcx().normalize_erasing_late_bound_regions(
285 ty::ParamEnv::reveal_all(),
288 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
289 let vtable = args[1];
291 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
294 let value = place.to_cvalue(fx);
295 (callee::get_fn(bx.cx, drop_fn),
296 FnType::of_instance(bx.cx, &drop_fn))
299 do_call(self, bx, fn_ty, drop_fn, args,
300 Some((ReturnDest::Nothing, target)),
304 let target_ebb = fx.get_ebb(*target);
305 fx.bcx.ins().jump(target_ebb, &[]);
307 TerminatorKind::GeneratorDrop => {
308 unimplemented!("terminator GeneratorDrop");
313 fx.bcx.seal_all_blocks();
317 fn trans_stmt<'a, 'tcx: 'a>(
318 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
320 stmt: &Statement<'tcx>,
322 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
325 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
327 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
328 fx.add_comment(inst, format!("{:?}", stmt));
333 StatementKind::SetDiscriminant {
337 let place = trans_place(fx, place);
338 let layout = place.layout();
339 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
342 match layout.variants {
343 layout::Variants::Single { index } => {
344 assert_eq!(index, *variant_index);
346 layout::Variants::Tagged { .. } => {
347 let ptr = place.place_field(fx, mir::Field::new(0));
352 .discriminant_for_variant(fx.tcx, *variant_index)
354 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
355 ptr.write_cvalue(fx, discr);
357 layout::Variants::NicheFilling {
363 if *variant_index != dataful_variant {
364 let niche = place.place_field(fx, mir::Field::new(0));
365 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
366 let niche_value = ((variant_index - *niche_variants.start()) as u128)
367 .wrapping_add(niche_start);
368 // FIXME(eddyb) Check the actual primitive type here.
369 let niche_llval = if niche_value == 0 {
370 CValue::const_val(fx, niche.layout().ty, 0)
372 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
374 niche.write_cvalue(fx, niche_llval);
379 StatementKind::Assign(to_place, rval) => {
380 let lval = trans_place(fx, to_place);
381 let dest_layout = lval.layout();
383 Rvalue::Use(operand) => {
384 let val = trans_operand(fx, operand);
385 lval.write_cvalue(fx, val);
387 Rvalue::Ref(_, _, place) => {
388 let place = trans_place(fx, place);
389 place.write_place_ref(fx, lval);
391 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
392 let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
393 let lhs = trans_operand(fx, lhs);
394 let rhs = trans_operand(fx, rhs);
396 let res = match ty.sty {
397 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
399 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
402 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
404 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
405 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
406 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
407 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
409 lval.write_cvalue(fx, res);
411 Rvalue::CheckedBinaryOp(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 {
418 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
421 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
423 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
425 lval.write_cvalue(fx, res);
427 Rvalue::UnaryOp(un_op, operand) => {
428 let operand = trans_operand(fx, operand);
429 let layout = operand.layout();
430 let val = operand.load_value(fx);
431 let res = match un_op {
433 match layout.ty.sty {
435 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
436 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
437 fx.bcx.ins().bint(types::I8, res)
439 ty::Uint(_) | ty::Int(_) => {
440 fx.bcx.ins().bnot(val)
442 _ => unimplemented!("un op Not for {:?}", layout.ty),
445 UnOp::Neg => match layout.ty.sty {
447 let clif_ty = fx.cton_type(layout.ty).unwrap();
448 let zero = fx.bcx.ins().iconst(clif_ty, 0);
449 fx.bcx.ins().isub(zero, val)
451 ty::Float(_) => fx.bcx.ins().fneg(val),
452 _ => unimplemented!("un op Neg for {:?}", layout.ty),
455 lval.write_cvalue(fx, CValue::ByVal(res, layout));
457 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
458 let operand = trans_operand(fx, operand);
459 let layout = fx.layout_of(ty);
460 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
462 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
463 let operand = trans_operand(fx, operand);
464 let layout = fx.layout_of(ty);
465 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
467 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
468 let operand = trans_operand(fx, operand);
469 let from_ty = operand.layout().ty;
470 match (&from_ty.sty, &to_ty.sty) {
471 (ty::Ref(..), ty::Ref(..))
472 | (ty::Ref(..), ty::RawPtr(..))
473 | (ty::RawPtr(..), ty::Ref(..))
474 | (ty::RawPtr(..), ty::RawPtr(..)) => {
475 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
477 (ty::RawPtr(..), ty::Uint(_)) | (ty::FnPtr(..), ty::Uint(_))
478 if to_ty.sty == fx.tcx.types.usize.sty =>
480 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
482 (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
483 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
485 (ty::Char, ty::Uint(_))
486 | (ty::Uint(_), ty::Char)
487 | (ty::Uint(_), ty::Int(_))
488 | (ty::Uint(_), ty::Uint(_)) => {
489 let from = operand.load_value(fx);
490 let res = crate::common::cton_intcast(
493 fx.cton_type(to_ty).unwrap(),
496 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
498 (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
499 let from = operand.load_value(fx);
500 let res = crate::common::cton_intcast(
503 fx.cton_type(to_ty).unwrap(),
506 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
508 (ty::Float(from_flt), ty::Float(to_flt)) => {
509 let from = operand.load_value(fx);
510 let res = match (from_flt, to_flt) {
511 (FloatTy::F32, FloatTy::F64) => {
512 fx.bcx.ins().fpromote(types::F64, from)
514 (FloatTy::F64, FloatTy::F32) => {
515 fx.bcx.ins().fdemote(types::F32, from)
519 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
521 (ty::Int(_), ty::Float(_)) => {
522 let from = operand.load_value(fx);
523 let f_type = fx.cton_type(to_ty).unwrap();
524 let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
525 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
527 (ty::Uint(_), ty::Float(_)) => {
528 let from = operand.load_value(fx);
529 let f_type = fx.cton_type(to_ty).unwrap();
530 let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
531 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
533 (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
534 let to_ty = fx.cton_type(to_ty).unwrap();
535 let from = operand.load_value(fx);
536 let res = if to_ty != types::I8 {
537 fx.bcx.ins().uextend(to_ty, from)
541 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
543 _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
546 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
547 unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
549 Rvalue::Cast(CastKind::Unsize, operand, ty) => {
550 let operand = trans_operand(fx, operand);
551 operand.unsize_value(fx, lval);
553 Rvalue::Discriminant(place) => {
554 let place = trans_place(fx, place).to_cvalue(fx);
555 let discr = trans_get_discriminant(fx, place, dest_layout);
556 lval.write_cvalue(fx, discr);
558 Rvalue::Repeat(operand, times) => {
559 let operand = trans_operand(fx, operand);
561 let index = fx.bcx.ins().iconst(fx.module.pointer_type(), i as i64);
562 let to = lval.place_index(fx, index);
563 to.write_cvalue(fx, operand);
566 Rvalue::Len(place) => {
567 let place = trans_place(fx, place);
568 let size = match place {
569 CPlace::Addr(_, size, _) => size.unwrap(),
570 CPlace::Var(_, _) => unreachable!(),
572 let usize_layout = fx.layout_of(fx.tcx.types.usize);
573 lval.write_cvalue(fx, CValue::ByVal(size, usize_layout));
575 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
576 use crate::rustc::middle::lang_items::ExchangeMallocFnLangItem;
578 let usize_type = fx.cton_type(fx.tcx.types.usize).unwrap();
579 let (size, align) = fx.layout_of(content_ty).size_and_align();
580 let llsize = fx.bcx.ins().iconst(usize_type, size.bytes() as i64);
581 let llalign = fx.bcx.ins().iconst(usize_type, align.abi() as i64);
582 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
585 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
590 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
593 let instance = ty::Instance::mono(fx.tcx, def_id);
594 let func_ref = fx.get_function_ref(instance);
595 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
596 let ptr = fx.bcx.inst_results(call)[0];
597 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
599 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
603 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
605 let ty_size = fx.layout_of(ty).size.bytes();
606 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
607 lval.write_cvalue(fx, val);
609 Rvalue::Aggregate(kind, operands) => match **kind {
610 AggregateKind::Array(_ty) => {
611 for (i, operand) in operands.into_iter().enumerate() {
612 let operand = trans_operand(fx, operand);
613 let index = fx.bcx.ins().iconst(fx.module.pointer_type(), i as i64);
614 let to = lval.place_index(fx, index);
615 to.write_cvalue(fx, operand);
618 _ => unimpl!("shouldn't exist at trans {:?}", rval),
622 StatementKind::StorageLive(_)
623 | StatementKind::StorageDead(_)
625 | StatementKind::FakeRead(..)
626 | StatementKind::Validate(_, _)
627 | StatementKind::EndRegion(_)
628 | StatementKind::AscribeUserType(..) => {}
630 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
634 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
635 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
637 dest_layout: TyLayout<'tcx>,
639 let layout = value.layout();
641 if layout.abi == layout::Abi::Uninhabited {
642 fx.bcx.ins().trap(TrapCode::User(!0));
644 match layout.variants {
645 layout::Variants::Single { index } => {
646 let discr_val = layout.ty.ty_adt_def().map_or(index as u128, |def| {
647 def.discriminant_for_variant(fx.tcx, index).val
649 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
651 layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
654 let discr = value.value_field(fx, mir::Field::new(0));
655 let discr_ty = discr.layout().ty;
656 let lldiscr = discr.load_value(fx);
657 match layout.variants {
658 layout::Variants::Single { .. } => bug!(),
659 layout::Variants::Tagged { ref tag, .. } => {
660 let signed = match tag.value {
661 layout::Int(_, signed) => signed,
664 let val = cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), signed);
665 return CValue::ByVal(val, dest_layout);
667 layout::Variants::NicheFilling {
673 let niche_llty = fx.cton_type(discr_ty).unwrap();
674 let dest_cton_ty = fx.cton_type(dest_layout.ty).unwrap();
675 if niche_variants.start() == niche_variants.end() {
679 .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
683 .iconst(dest_cton_ty, *niche_variants.start() as u64 as i64);
687 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
688 let val = fx.bcx.ins().select(b, if_true, if_false);
689 return CValue::ByVal(val, dest_layout);
691 // Rebase from niche values to discriminant values.
692 let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
693 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
694 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
695 let b = fx.bcx.ins().icmp_imm(
696 IntCC::UnsignedLessThanOrEqual,
698 *niche_variants.end() as u64 as i64,
701 cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), false);
705 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
706 let val = fx.bcx.ins().select(b, if_true, if_false);
707 return CValue::ByVal(val, dest_layout);
713 macro_rules! binop_match {
714 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
715 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
717 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
718 assert_eq!($fx.tcx.types.bool, $ret_ty);
719 let ret_layout = $fx.layout_of($ret_ty);
721 // TODO HACK no encoding for icmp.i8
722 use crate::common::cton_intcast;
724 cton_intcast($fx, $lhs, types::I64, $signed),
725 cton_intcast($fx, $rhs, types::I64, $signed),
727 let b = $fx.bcx.ins().icmp(IntCC::$cc, lhs, rhs);
729 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
731 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
732 assert_eq!($fx.tcx.types.bool, $ret_ty);
733 let ret_layout = $fx.layout_of($ret_ty);
734 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
735 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
737 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
740 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
741 let ret_layout = $fx.layout_of($ret_ty);
742 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
745 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
747 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
750 let lhs = $lhs.load_value($fx);
751 let rhs = $rhs.load_value($fx);
752 match ($bin_op, $signed) {
754 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
760 fn trans_bool_binop<'a, 'tcx: 'a>(
761 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
767 let res = binop_match! {
768 fx, bin_op, false, lhs, rhs, ty, "bool";
781 Lt (_) icmp(UnsignedLessThan);
782 Le (_) icmp(UnsignedLessThanOrEqual);
783 Ne (_) icmp(NotEqual);
784 Ge (_) icmp(UnsignedGreaterThanOrEqual);
785 Gt (_) icmp(UnsignedGreaterThan);
793 pub fn trans_int_binop<'a, 'tcx: 'a>(
794 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
801 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
805 "int binop requires lhs and rhs of same type"
809 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
825 Lt (false) icmp(UnsignedLessThan);
826 Lt (true) icmp(SignedLessThan);
827 Le (false) icmp(UnsignedLessThanOrEqual);
828 Le (true) icmp(SignedLessThanOrEqual);
829 Ne (_) icmp(NotEqual);
830 Ge (false) icmp(UnsignedGreaterThanOrEqual);
831 Ge (true) icmp(SignedGreaterThanOrEqual);
832 Gt (false) icmp(UnsignedGreaterThan);
833 Gt (true) icmp(SignedGreaterThan);
839 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
840 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
842 in_lhs: CValue<'tcx>,
843 in_rhs: CValue<'tcx>,
847 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
851 "checked int binop requires lhs and rhs of same type"
854 let res_ty = match out_ty.sty {
855 ty::Tuple(tys) => tys[0],
857 "Checked int binop requires tuple as output, but got {:?}",
862 let lhs = in_lhs.load_value(fx);
863 let rhs = in_rhs.load_value(fx);
864 let res = match bin_op {
865 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
866 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
867 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
868 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
869 BinOp::Shr => if !signed {
870 fx.bcx.ins().ushr(lhs, rhs)
872 fx.bcx.ins().sshr(lhs, rhs)
875 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
882 // TODO: check for overflow
883 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
885 let out_place = CPlace::temp(fx, out_ty);
886 let out_layout = out_place.layout();
887 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
889 out_place.to_cvalue(fx)
892 fn trans_float_binop<'a, 'tcx: 'a>(
893 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
899 let res = binop_match! {
900 fx, bin_op, false, lhs, rhs, ty, "float";
906 assert_eq!(lhs.layout().ty, ty);
907 assert_eq!(rhs.layout().ty, ty);
909 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
910 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
921 Lt (_) fcmp(LessThan);
922 Le (_) fcmp(LessThanOrEqual);
923 Ne (_) fcmp(NotEqual);
924 Ge (_) fcmp(GreaterThanOrEqual);
925 Gt (_) fcmp(GreaterThan);
933 fn trans_char_binop<'a, 'tcx: 'a>(
934 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
940 let res = binop_match! {
941 fx, bin_op, false, lhs, rhs, ty, "char";
954 Lt (_) icmp(UnsignedLessThan);
955 Le (_) icmp(UnsignedLessThanOrEqual);
956 Ne (_) icmp(NotEqual);
957 Ge (_) icmp(UnsignedGreaterThanOrEqual);
958 Gt (_) icmp(UnsignedGreaterThan);
966 fn trans_ptr_binop<'a, 'tcx: 'a>(
967 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
973 match lhs.layout().ty.sty {
974 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
975 if !ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
976 unimpl!("Unsized values are not yet implemented");
979 _ => bug!("trans_ptr_binop on non ptr"),
982 fx, bin_op, false, lhs, rhs, ty, "ptr";
995 Lt (_) icmp(UnsignedLessThan);
996 Le (_) icmp(UnsignedLessThanOrEqual);
997 Ne (_) icmp(NotEqual);
998 Ge (_) icmp(UnsignedGreaterThanOrEqual);
999 Gt (_) icmp(UnsignedGreaterThan);
1005 pub fn trans_place<'a, 'tcx: 'a>(
1006 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1007 place: &Place<'tcx>,
1010 Place::Local(local) => fx.get_local_place(*local),
1011 Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1012 Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1013 Place::Projection(projection) => {
1014 let base = trans_place(fx, &projection.base);
1015 match projection.elem {
1016 ProjectionElem::Deref => base.place_deref(fx),
1017 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1018 ProjectionElem::Index(local) => {
1019 let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
1020 base.place_index(fx, index)
1022 ProjectionElem::ConstantIndex {
1026 } => unimplemented!(
1027 "projection const index {:?} offset {:?} not from end",
1031 ProjectionElem::ConstantIndex {
1035 } => unimplemented!(
1036 "projection const index {:?} offset {:?} from end",
1040 ProjectionElem::Subslice { from, to } => unimplemented!(
1041 "projection subslice {:?} from {} to {}",
1046 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1052 pub fn trans_operand<'a, 'tcx>(
1053 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1054 operand: &Operand<'tcx>,
1057 Operand::Move(place) | Operand::Copy(place) => {
1058 let cplace = trans_place(fx, place);
1059 cplace.to_cvalue(fx)
1061 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),