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, 'clif, 'tcx: 'a, B: Backend + 'static>(
13 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
14 mono_item: MonoItem<'tcx>,
19 MonoItem::Fn(inst) => {
21 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
22 debug_assert!(!inst.substs.needs_infer());
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 // FIXME fix write_mir_pretty for these instances
41 format!("{:#?}", tcx.instance_mir(inst.def))
46 trans_fn(cx, inst, linkage);
48 MonoItem::Static(def_id) => {
49 crate::constant::codegen_static(&mut cx.ccx, def_id);
51 MonoItem::GlobalAsm(node_id) => tcx
53 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
57 fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
58 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
59 instance: Instance<'tcx>,
65 let mir = tcx.instance_mir(instance.def);
67 // Step 2. Check fn sig for u128 and i128 and replace those functions with a trap.
69 // FIXME implement u128 and i128 support
71 // Step 2a. Check sig for u128 and i128
72 let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx));
74 struct UI128Visitor<'a, 'tcx: 'a>(TyCtxt<'a, 'tcx, 'tcx>, bool);
76 impl<'a, 'tcx: 'a> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'a, 'tcx> {
77 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
78 if t.sty == self.0.types.u128.sty || t.sty == self.0.types.i128.sty {
80 return false; // stop visiting
83 t.super_visit_with(self)
87 let mut visitor = UI128Visitor(tcx, false);
88 fn_sig.visit_with(&mut visitor);
90 // Step 2b. If found replace function with a trap.
92 tcx.sess.warn("u128 and i128 are not yet supported. \
93 Functions using these as args will be replaced with a trap.");
95 // Step 2b1. Declare function with fake signature
97 params: vec![AbiParam::new(types::INVALID)],
99 call_conv: CallConv::Fast,
101 let name = tcx.symbol_name(instance).as_str();
102 let func_id = cx.module.declare_function(&*name, linkage, &sig).unwrap();
104 // Step 2b2. Create trapping function
105 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
106 let mut func_ctx = FunctionBuilderContext::new();
107 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
108 let start_ebb = bcx.create_ebb();
109 bcx.append_ebb_params_for_function_params(start_ebb);
110 bcx.switch_to_block(start_ebb);
111 crate::trap::trap_unreachable(&mut bcx);
112 bcx.seal_all_blocks();
115 // Step 2b3. Define function
116 cx.caches.context.func = func;
118 .define_function(func_id, &mut cx.caches.context)
120 cx.caches.context.clear();
125 // Step 3. Declare function
126 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
127 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
128 let mut debug_context = cx
131 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
133 // Step 4. Make FunctionBuilder
134 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
135 let mut func_ctx = FunctionBuilderContext::new();
136 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
138 // Step 5. Predefine ebb's
139 let start_ebb = bcx.create_ebb();
140 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
141 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
142 ebb_map.insert(bb, bcx.create_ebb());
145 // Step 6. Make FunctionCx
146 let pointer_type = cx.module.target_config().pointer_type();
147 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
149 let mut fx = FunctionCx {
159 local_map: HashMap::new(),
162 constants: &mut cx.ccx,
163 caches: &mut cx.caches,
164 source_info_set: indexmap::IndexSet::new(),
167 // Step 7. Codegen function
168 with_unimpl_span(fx.mir.span, || {
169 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
170 codegen_fn_content(&mut fx);
172 let source_info_set = fx.source_info_set.clone();
174 // Step 8. Write function to file for debugging
175 #[cfg(debug_assertions)]
176 fx.write_clif_file();
178 // Step 9. Verify function
179 verify_func(tcx, fx.clif_comments, &func);
181 // Step 10. Define function
182 cx.caches.context.func = func;
184 .define_function(func_id, &mut cx.caches.context)
187 // Step 11. Define debuginfo for function
188 let context = &cx.caches.context;
189 let isa = cx.module.isa();
192 .map(|x| x.define(tcx, context, isa, &source_info_set));
194 // Step 12. Clear context to make it usable for the next function
195 cx.caches.context.clear();
198 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
199 let flags = settings::Flags::new(settings::builder());
200 match ::cranelift::codegen::verify_function(&func, &flags) {
203 tcx.sess.err(&format!("{:?}", err));
204 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
207 Some(Box::new(&writer)),
211 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
216 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
217 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
218 if bb_data.is_cleanup {
219 // Unwinding after panicking is not supported
223 let ebb = fx.get_ebb(bb);
224 fx.bcx.switch_to_block(ebb);
227 for stmt in &bb_data.statements {
228 fx.set_debug_loc(stmt.source_info);
229 trans_stmt(fx, ebb, stmt);
232 #[cfg(debug_assertions)]
234 let mut terminator_head = "\n".to_string();
238 .fmt_head(&mut terminator_head)
240 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
241 fx.add_comment(inst, terminator_head);
244 fx.set_debug_loc(bb_data.terminator().source_info);
246 match &bb_data.terminator().kind {
247 TerminatorKind::Goto { target } => {
248 let ebb = fx.get_ebb(*target);
249 fx.bcx.ins().jump(ebb, &[]);
251 TerminatorKind::Return => {
252 crate::abi::codegen_return(fx);
254 TerminatorKind::Assert {
261 let cond = trans_operand(fx, cond).load_scalar(fx);
262 // TODO HACK brz/brnz for i8/i16 is not yet implemented
263 let cond = fx.bcx.ins().uextend(types::I32, cond);
264 let target = fx.get_ebb(*target);
266 fx.bcx.ins().brnz(cond, target, &[]);
268 fx.bcx.ins().brz(cond, target, &[]);
270 trap_panic(&mut fx.bcx);
273 TerminatorKind::SwitchInt {
279 let discr = trans_operand(fx, discr).load_scalar(fx);
280 let mut switch = ::cranelift::frontend::Switch::new();
281 for (i, value) in values.iter().enumerate() {
282 let ebb = fx.get_ebb(targets[i]);
283 switch.set_entry(*value as u64, ebb);
285 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
286 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
288 TerminatorKind::Call {
295 crate::abi::codegen_terminator_call(fx, func, args, destination);
297 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
298 trap_unreachable(&mut fx.bcx);
300 TerminatorKind::Yield { .. }
301 | TerminatorKind::FalseEdges { .. }
302 | TerminatorKind::FalseUnwind { .. }
303 | TerminatorKind::DropAndReplace { .. }
304 | TerminatorKind::GeneratorDrop => {
305 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
307 TerminatorKind::Drop {
312 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
313 let ty = fx.monomorphize(&ty);
314 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
316 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
317 // we don't actually need to drop anything
319 let drop_place = trans_place(fx, location);
320 let drop_fn_ty = drop_fn.ty(fx.tcx);
323 crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
326 let arg_place = CPlace::new_stack_slot(
329 &ty::RegionKind::ReErased,
332 mutbl: crate::rustc::hir::Mutability::MutMutable,
336 drop_place.write_place_ref(fx, arg_place);
337 let arg_value = arg_place.to_cvalue(fx);
338 crate::abi::codegen_call_inner(
349 let target_ebb = fx.get_ebb(*target);
350 fx.bcx.ins().jump(target_ebb, &[]);
355 fx.bcx.seal_all_blocks();
359 fn trans_stmt<'a, 'tcx: 'a>(
360 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
362 stmt: &Statement<'tcx>,
364 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
366 fx.set_debug_loc(stmt.source_info);
368 #[cfg(debug_assertions)]
370 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
372 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
373 fx.add_comment(inst, format!("{:?}", stmt));
378 StatementKind::SetDiscriminant {
382 let place = trans_place(fx, place);
383 let layout = place.layout();
384 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
387 match layout.variants {
388 layout::Variants::Single { index } => {
389 assert_eq!(index, *variant_index);
391 layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, .. } => {
392 let ptr = place.place_field(fx, mir::Field::new(0));
397 .discriminant_for_variant(fx.tcx, *variant_index)
399 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
400 ptr.write_cvalue(fx, discr);
402 layout::Variants::Multiple {
403 discr_kind: layout::DiscriminantKind::Niche {
410 if *variant_index != dataful_variant {
411 let niche = place.place_field(fx, mir::Field::new(0));
412 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
414 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
415 .wrapping_add(niche_start);
416 // FIXME(eddyb) Check the actual primitive type here.
417 let niche_llval = if niche_value == 0 {
418 CValue::const_val(fx, niche.layout().ty, 0)
420 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
422 niche.write_cvalue(fx, niche_llval);
427 StatementKind::Assign(to_place, rval) => {
428 let lval = trans_place(fx, to_place);
429 let dest_layout = lval.layout();
431 Rvalue::Use(operand) => {
432 let val = trans_operand(fx, operand);
433 lval.write_cvalue(fx, val);
435 Rvalue::Ref(_, _, place) => {
436 let place = trans_place(fx, place);
437 place.write_place_ref(fx, lval);
439 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
440 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
441 let lhs = trans_operand(fx, lhs);
442 let rhs = trans_operand(fx, rhs);
444 let res = match ty.sty {
445 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
447 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
450 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
452 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
453 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
454 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
455 ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
456 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
458 lval.write_cvalue(fx, res);
460 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
461 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
462 let lhs = trans_operand(fx, lhs);
463 let rhs = trans_operand(fx, rhs);
465 let res = match ty.sty {
467 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
470 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
472 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
474 lval.write_cvalue(fx, res);
476 Rvalue::UnaryOp(un_op, operand) => {
477 let operand = trans_operand(fx, operand);
478 let layout = operand.layout();
479 let val = operand.load_scalar(fx);
480 let res = match un_op {
482 match layout.ty.sty {
484 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
485 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
486 fx.bcx.ins().bint(types::I8, res)
488 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
489 _ => unimplemented!("un op Not for {:?}", layout.ty),
492 UnOp::Neg => match layout.ty.sty {
494 let clif_ty = fx.clif_type(layout.ty).unwrap();
495 let zero = fx.bcx.ins().iconst(clif_ty, 0);
496 fx.bcx.ins().isub(zero, val)
498 ty::Float(_) => fx.bcx.ins().fneg(val),
499 _ => unimplemented!("un op Neg for {:?}", layout.ty),
502 lval.write_cvalue(fx, CValue::ByVal(res, layout));
504 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
505 let layout = fx.layout_of(ty);
507 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
510 ty::FnDef(def_id, substs) => {
511 let func_ref = fx.get_function_ref(
512 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
515 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
516 lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
518 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
521 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty)
522 | Rvalue::Cast(CastKind::MutToConstPointer, operand, ty) => {
523 let operand = trans_operand(fx, operand);
524 let layout = fx.layout_of(ty);
525 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
527 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
528 let operand = trans_operand(fx, operand);
529 let from_ty = operand.layout().ty;
531 fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
534 .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
538 if is_fat_ptr(fx, from_ty) {
539 if is_fat_ptr(fx, to_ty) {
540 // fat-ptr -> fat-ptr
541 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
543 // fat-ptr -> thin-ptr
544 let (ptr, _extra) = operand.load_scalar_pair(fx);
545 lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
547 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
548 // enum -> discriminant value
549 assert!(adt_def.is_enum());
551 ty::Uint(_) | ty::Int(_) => {},
552 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
555 // FIXME avoid forcing to stack
557 CPlace::Addr(operand.force_stack(fx), None, operand.layout());
558 let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
559 lval.write_cvalue(fx, discr);
561 let from_clif_ty = fx.clif_type(from_ty).unwrap();
562 let to_clif_ty = fx.clif_type(to_ty).unwrap();
563 let from = operand.load_scalar(fx);
565 let signed = match from_ty.sty {
566 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
568 ty::Float(..) => false, // `signed` is unused for floats
569 _ => panic!("{}", from_ty),
572 let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
573 // int-like -> int-like
574 crate::common::clif_intcast(
580 } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
582 // FIXME missing encoding for fcvt_from_sint.f32.i8
583 let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
584 fx.bcx.ins().uextend(types::I32, from)
589 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
591 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
593 } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
595 let from = operand.load_scalar(fx);
597 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
599 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
601 } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
603 match (from_clif_ty, to_clif_ty) {
604 (types::F32, types::F64) => {
605 fx.bcx.ins().fpromote(types::F64, from)
607 (types::F64, types::F32) => {
608 fx.bcx.ins().fdemote(types::F32, from)
613 unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
615 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
618 Rvalue::Cast(CastKind::ClosureFnPointer(_), operand, _ty) => {
619 let operand = trans_operand(fx, operand);
620 match operand.layout().ty.sty {
621 ty::Closure(def_id, substs) => {
622 let instance = rustc_mir::monomorphize::resolve_closure(
626 ty::ClosureKind::FnOnce,
628 let func_ref = fx.get_function_ref(instance);
629 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
630 lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
633 bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
637 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
638 let operand = trans_operand(fx, operand);
639 operand.unsize_value(fx, lval);
641 Rvalue::Discriminant(place) => {
642 let place = trans_place(fx, place);
643 let discr = trans_get_discriminant(fx, place, dest_layout);
644 lval.write_cvalue(fx, discr);
646 Rvalue::Repeat(operand, times) => {
647 let operand = trans_operand(fx, operand);
649 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
650 let to = lval.place_index(fx, index);
651 to.write_cvalue(fx, operand);
654 Rvalue::Len(place) => {
655 let place = trans_place(fx, place);
656 let usize_layout = fx.layout_of(fx.tcx.types.usize);
657 let len = codegen_array_len(fx, place);
658 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
660 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
661 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
663 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
664 let layout = fx.layout_of(content_ty);
665 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
669 .iconst(usize_type, layout.align.abi.bytes() as i64);
670 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
673 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
678 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
681 let instance = ty::Instance::mono(fx.tcx, def_id);
682 let func_ref = fx.get_function_ref(instance);
683 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
684 let ptr = fx.bcx.inst_results(call)[0];
685 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
687 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
691 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
692 let ty_size = fx.layout_of(ty).size.bytes();
693 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
694 lval.write_cvalue(fx, val);
696 Rvalue::Aggregate(kind, operands) => match **kind {
697 AggregateKind::Array(_ty) => {
698 for (i, operand) in operands.into_iter().enumerate() {
699 let operand = trans_operand(fx, operand);
700 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
701 let to = lval.place_index(fx, index);
702 to.write_cvalue(fx, operand);
705 _ => unimpl!("shouldn't exist at trans {:?}", rval),
709 StatementKind::StorageLive(_)
710 | StatementKind::StorageDead(_)
712 | StatementKind::FakeRead(..)
713 | StatementKind::Retag { .. }
714 | StatementKind::AscribeUserType(..) => {}
716 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
720 fn codegen_array_len<'a, 'tcx: 'a>(
721 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
724 match place.layout().ty.sty {
725 ty::Array(_elem_ty, len) => {
726 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
727 fx.bcx.ins().iconst(fx.pointer_type, len)
729 ty::Slice(_elem_ty) => place
730 .to_addr_maybe_unsized(fx)
732 .expect("Length metadata for slice place"),
733 _ => bug!("Rvalue::Len({:?})", place),
737 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
738 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
740 dest_layout: TyLayout<'tcx>,
742 let layout = place.layout();
744 if layout.abi == layout::Abi::Uninhabited {
745 return trap_unreachable_ret_value(fx, dest_layout);
748 let (discr_scalar, discr_kind) = match &layout.variants {
749 layout::Variants::Single { index } => {
750 let discr_val = layout
753 .map_or(index.as_u32() as u128, |def| {
754 def.discriminant_for_variant(fx.tcx, *index).val
756 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
758 layout::Variants::Multiple { discr, discr_kind, variants: _ } => (discr, discr_kind),
761 let discr = place.place_field(fx, mir::Field::new(0)).to_cvalue(fx);
762 let discr_ty = discr.layout().ty;
763 let lldiscr = discr.load_scalar(fx);
765 layout::DiscriminantKind::Tag => {
766 let signed = match discr_scalar.value {
767 layout::Int(_, signed) => signed,
770 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
771 return CValue::ByVal(val, dest_layout);
773 layout::DiscriminantKind::Niche {
778 let niche_llty = fx.clif_type(discr_ty).unwrap();
779 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
780 if niche_variants.start() == niche_variants.end() {
784 .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
788 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
792 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
793 let val = fx.bcx.ins().select(b, if_true, if_false);
794 return CValue::ByVal(val, dest_layout);
796 // Rebase from niche values to discriminant values.
797 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
798 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
799 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
800 let b = fx.bcx.ins().icmp_imm(
801 IntCC::UnsignedLessThanOrEqual,
803 niche_variants.end().as_u32() as i64,
806 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
810 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
811 let val = fx.bcx.ins().select(b, if_true, if_false);
812 return CValue::ByVal(val, dest_layout);
818 macro_rules! binop_match {
819 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
820 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
822 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
823 assert_eq!($fx.tcx.types.bool, $ret_ty);
824 let ret_layout = $fx.layout_of($ret_ty);
826 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
827 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
829 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
830 assert_eq!($fx.tcx.types.bool, $ret_ty);
831 let ret_layout = $fx.layout_of($ret_ty);
832 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
833 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
835 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
838 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
839 let ret_layout = $fx.layout_of($ret_ty);
840 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
843 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
845 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
848 let lhs = $lhs.load_scalar($fx);
849 let rhs = $rhs.load_scalar($fx);
850 match ($bin_op, $signed) {
852 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
858 fn trans_bool_binop<'a, 'tcx: 'a>(
859 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
865 let res = binop_match! {
866 fx, bin_op, false, lhs, rhs, ty, "bool";
879 Lt (_) icmp(UnsignedLessThan);
880 Le (_) icmp(UnsignedLessThanOrEqual);
881 Ne (_) icmp(NotEqual);
882 Ge (_) icmp(UnsignedGreaterThanOrEqual);
883 Gt (_) icmp(UnsignedGreaterThan);
891 pub fn trans_int_binop<'a, 'tcx: 'a>(
892 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
899 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
903 "int binop requires lhs and rhs of same type"
907 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
923 Lt (false) icmp(UnsignedLessThan);
924 Lt (true) icmp(SignedLessThan);
925 Le (false) icmp(UnsignedLessThanOrEqual);
926 Le (true) icmp(SignedLessThanOrEqual);
927 Ne (_) icmp(NotEqual);
928 Ge (false) icmp(UnsignedGreaterThanOrEqual);
929 Ge (true) icmp(SignedGreaterThanOrEqual);
930 Gt (false) icmp(UnsignedGreaterThan);
931 Gt (true) icmp(SignedGreaterThan);
937 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
938 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
940 in_lhs: CValue<'tcx>,
941 in_rhs: CValue<'tcx>,
945 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
949 "checked int binop requires lhs and rhs of same type"
953 let lhs = in_lhs.load_scalar(fx);
954 let rhs = in_rhs.load_scalar(fx);
955 let res = match bin_op {
956 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
957 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
958 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
959 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
962 fx.bcx.ins().ushr(lhs, rhs)
964 fx.bcx.ins().sshr(lhs, rhs)
968 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
975 // TODO: check for overflow
976 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
978 let out_place = CPlace::new_stack_slot(fx, out_ty);
979 let out_layout = out_place.layout();
980 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
982 out_place.to_cvalue(fx)
985 fn trans_float_binop<'a, 'tcx: 'a>(
986 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
992 let res = binop_match! {
993 fx, bin_op, false, lhs, rhs, ty, "float";
999 assert_eq!(lhs.layout().ty, ty);
1000 assert_eq!(rhs.layout().ty, ty);
1002 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1003 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1014 Lt (_) fcmp(LessThan);
1015 Le (_) fcmp(LessThanOrEqual);
1016 Ne (_) fcmp(NotEqual);
1017 Ge (_) fcmp(GreaterThanOrEqual);
1018 Gt (_) fcmp(GreaterThan);
1026 fn trans_char_binop<'a, 'tcx: 'a>(
1027 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1033 let res = binop_match! {
1034 fx, bin_op, false, lhs, rhs, ty, "char";
1047 Lt (_) icmp(UnsignedLessThan);
1048 Le (_) icmp(UnsignedLessThanOrEqual);
1049 Ne (_) icmp(NotEqual);
1050 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1051 Gt (_) icmp(UnsignedGreaterThan);
1059 fn trans_ptr_binop<'a, 'tcx: 'a>(
1060 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1066 let not_fat = match lhs.layout().ty.sty {
1067 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1068 ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1070 ty::FnPtr(..) => true,
1071 _ => bug!("trans_ptr_binop on non ptr"),
1074 if let BinOp::Offset = bin_op {
1075 let (base, offset) = (lhs, rhs.load_scalar(fx));
1076 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1077 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1078 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1079 let base_val = base.load_scalar(fx);
1080 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1081 return CValue::ByVal(res, base.layout());
1085 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1098 Lt (_) icmp(UnsignedLessThan);
1099 Le (_) icmp(UnsignedLessThanOrEqual);
1100 Ne (_) icmp(NotEqual);
1101 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1102 Gt (_) icmp(UnsignedGreaterThan);
1104 Offset (_) bug; // Handled above
1107 let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1108 let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1109 let res = match bin_op {
1111 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1112 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1113 fx.bcx.ins().band(ptr_eq, extra_eq)
1116 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1117 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1118 fx.bcx.ins().bor(ptr_ne, extra_ne)
1120 _ => unimplemented!(
1121 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1126 assert_eq!(fx.tcx.types.bool, ret_ty);
1127 let ret_layout = fx.layout_of(ret_ty);
1128 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1132 pub fn trans_place<'a, 'tcx: 'a>(
1133 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1134 place: &Place<'tcx>,
1137 Place::Base(base) => match base {
1138 PlaceBase::Local(local) => fx.get_local_place(*local),
1139 PlaceBase::Static(static_) => match static_.kind {
1140 StaticKind::Static(def_id) => {
1141 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1143 StaticKind::Promoted(promoted) => {
1144 crate::constant::trans_promoted(fx, promoted, static_.ty)
1148 Place::Projection(projection) => {
1149 let base = trans_place(fx, &projection.base);
1150 match projection.elem {
1151 ProjectionElem::Deref => base.place_deref(fx),
1152 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1153 ProjectionElem::Index(local) => {
1154 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1155 base.place_index(fx, index)
1157 ProjectionElem::ConstantIndex {
1162 let index = if !from_end {
1163 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1165 let len = codegen_array_len(fx, base);
1166 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1168 base.place_index(fx, index)
1170 ProjectionElem::Subslice { from, to } => {
1171 // These indices are generated by slice patterns.
1172 // slice[from:-to] in Python terms.
1174 match base.layout().ty.sty {
1175 ty::Array(elem_ty, len) => {
1176 let elem_layout = fx.layout_of(elem_ty);
1177 let ptr = base.to_addr(fx);
1178 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1180 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1182 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1185 ty::Slice(elem_ty) => {
1186 let elem_layout = fx.layout_of(elem_ty);
1187 let (ptr, len) = base.to_addr_maybe_unsized(fx);
1188 let len = len.unwrap();
1190 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1191 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1195 _ => unreachable!(),
1198 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1204 pub fn trans_operand<'a, 'tcx>(
1205 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1206 operand: &Operand<'tcx>,
1209 Operand::Move(place) | Operand::Copy(place) => {
1210 let cplace = trans_place(fx, place);
1211 cplace.to_cvalue(fx)
1213 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),