]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Reduce verbosity of output
[rust.git] / src / base.rs
1 use crate::prelude::*;
2
3 struct PrintOnPanic(String);
4 impl Drop for PrintOnPanic {
5     fn drop(&mut self) {
6         if ::std::thread::panicking() {
7             println!("{}", self.0);
8         }
9     }
10 }
11
12 pub fn trans_mono_item<'a, 'tcx: 'a>(cx: &mut CodegenCx<'a, 'tcx>, mono_item: MonoItem<'tcx>) {
13     let tcx = cx.tcx;
14     let context = &mut cx.context;
15
16     match mono_item {
17         MonoItem::Fn(inst) => match inst {
18             Instance {
19                 def: InstanceDef::Item(def_id),
20                 substs: _,
21             } => {
22                 let mut mir = ::std::io::Cursor::new(Vec::new());
23                 ::rustc_mir::util::write_mir_pretty(tcx, Some(def_id), &mut mir).unwrap();
24                 let mir_file_name = "target/out/mir/".to_string() + &format!("{:?}", def_id).replace('/', "@");
25                 ::std::fs::write(mir_file_name, mir.into_inner()).unwrap();
26                 let _print_guard = PrintOnPanic(format!("{:?}", inst));
27
28                 let res = each_module!(cx, |(ccx, m)| trans_fn(tcx, *m, ccx, context, inst));
29                 if let Some(func_id) = res.jit {
30                     cx.defined_functions.push(func_id);
31                 };
32             }
33             Instance {
34                 def: InstanceDef::DropGlue(_, _),
35                 substs: _,
36             } => unimpl!("Unimplemented drop glue instance"),
37             inst => unimpl!("Unimplemented instance {:?}", inst),
38         },
39         MonoItem::Static(def_id) => {
40             each_module!(cx, |(ccx, _m)| {
41                 crate::constant::codegen_static(ccx, def_id);
42             });
43         }
44         MonoItem::GlobalAsm(node_id) => cx
45             .tcx
46             .sess
47             .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
48     }
49 }
50
51 fn trans_fn<'a, 'tcx: 'a>(
52     tcx: TyCtxt<'a, 'tcx, 'tcx>,
53     module: &mut Module<impl Backend>,
54     constants: &mut crate::constant::ConstantCx,
55     context: &mut Context,
56     instance: Instance<'tcx>,
57 ) -> FuncId {
58     // Step 1. Get mir
59     let mir = tcx.optimized_mir(instance.def_id());
60
61     // Step 2. Declare function
62     let (name, sig) = get_function_name_and_sig(tcx, instance);
63     let func_id = module
64         .declare_function(&name, Linkage::Export, &sig)
65         .unwrap();
66
67     // Step 3. Make FunctionBuilder
68     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
69     let mut func_ctx = FunctionBuilderContext::new();
70     let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut func, &mut func_ctx);
71
72     // Step 4. Predefine ebb's
73     let start_ebb = bcx.create_ebb();
74     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
75     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
76         ebb_map.insert(bb, bcx.create_ebb());
77     }
78
79     // Step 5. Make FunctionCx
80     let mut fx = FunctionCx {
81         tcx,
82         module,
83         instance,
84         mir,
85         bcx,
86         param_substs: {
87             assert!(!instance.substs.needs_infer());
88             instance.substs
89         },
90         ebb_map,
91         local_map: HashMap::new(),
92         comments: HashMap::new(),
93         constants,
94
95         top_nop: None,
96     };
97
98     // Step 6. Codegen function
99     crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
100     codegen_fn_content(&mut fx);
101     fx.bcx.seal_all_blocks();
102     fx.bcx.finalize();
103
104     // Step 7. Print function to terminal for debugging
105     let mut writer = crate::pretty_clif::CommentWriter(fx.comments);
106     let mut cton = String::new();
107     ::cranelift::codegen::write::decorate_function(&mut writer, &mut cton, &func, None).unwrap();
108     let clif_file_name = "target/out/clif/".to_string() + &tcx.symbol_name(instance).as_str();
109     ::std::fs::write(clif_file_name, cton.as_bytes()).unwrap();
110
111     // Step 8. Verify function
112     verify_func(tcx, writer, &func);
113
114     // Step 9. Define function
115     // TODO: cranelift doesn't yet support some of the things needed
116     if should_codegen(tcx.sess) {
117         context.func = func;
118         module.define_function(func_id, context).unwrap();
119         context.clear();
120     }
121
122     func_id
123 }
124
125 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
126     let flags = settings::Flags::new(settings::builder());
127     match ::cranelift::codegen::verify_function(&func, &flags) {
128         Ok(_) => {}
129         Err(err) => {
130             tcx.sess.err(&format!("{:?}", err));
131             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
132                 &func,
133                 None,
134                 Some(Box::new(writer)),
135                 err,
136             );
137             tcx.sess
138                 .fatal(&format!("cretonne verify error:\n{}", pretty_error));
139         }
140     }
141 }
142
143 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
144     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
145         let ebb = fx.get_ebb(bb);
146         fx.bcx.switch_to_block(ebb);
147
148         fx.bcx.ins().nop();
149         for stmt in &bb_data.statements {
150             trans_stmt(fx, ebb, stmt);
151         }
152
153         let mut terminator_head = "\n".to_string();
154         bb_data
155             .terminator()
156             .kind
157             .fmt_head(&mut terminator_head)
158             .unwrap();
159         let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
160         fx.add_comment(inst, terminator_head);
161
162         match &bb_data.terminator().kind {
163             TerminatorKind::Goto { target } => {
164                 let ebb = fx.get_ebb(*target);
165                 fx.bcx.ins().jump(ebb, &[]);
166             }
167             TerminatorKind::Return => {
168                 crate::abi::codegen_return(fx);
169             }
170             TerminatorKind::Assert {
171                 cond,
172                 expected,
173                 msg: _,
174                 target,
175                 cleanup: _,
176             } => {
177                 let cond = trans_operand(fx, cond).load_value(fx);
178                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
179                 let cond = fx.bcx.ins().uextend(types::I32, cond);
180                 let target = fx.get_ebb(*target);
181                 if *expected {
182                     fx.bcx.ins().brnz(cond, target, &[]);
183                 } else {
184                     fx.bcx.ins().brz(cond, target, &[]);
185                 };
186                 fx.bcx.ins().trap(TrapCode::User(!0));
187             }
188
189             TerminatorKind::SwitchInt {
190                 discr,
191                 switch_ty: _,
192                 values,
193                 targets,
194             } => {
195                 // TODO: prevent panics on large and negative disciminants
196                 if should_codegen(fx.tcx.sess) {
197                     let discr = trans_operand(fx, discr).load_value(fx);
198                     let mut jt_data = JumpTableData::new();
199                     for (i, value) in values.iter().enumerate() {
200                         let ebb = fx.get_ebb(targets[i]);
201                         jt_data.set_entry(*value as usize, ebb);
202                     }
203                     let jump_table = fx.bcx.create_jump_table(jt_data);
204                     fx.bcx.ins().br_table(discr, jump_table);
205                     let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
206                     fx.bcx.ins().jump(otherwise_ebb, &[]);
207                 } else {
208                     fx.bcx.ins().trap(TrapCode::User(0));
209                 }
210             }
211             TerminatorKind::Call {
212                 func,
213                 args,
214                 destination,
215                 cleanup: _,
216             } => {
217                 crate::abi::codegen_call(fx, func, args, destination);
218             }
219             TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
220                 fx.bcx.ins().trap(TrapCode::User(!0));
221             }
222             TerminatorKind::Yield { .. }
223             | TerminatorKind::FalseEdges { .. }
224             | TerminatorKind::FalseUnwind { .. } => {
225                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
226             }
227             TerminatorKind::Drop { target, .. } | TerminatorKind::DropAndReplace { target, .. } => {
228                 // TODO call drop impl
229                 // unimplemented!("terminator {:?}", bb_data.terminator());
230                 let target_ebb = fx.get_ebb(*target);
231                 fx.bcx.ins().jump(target_ebb, &[]);
232             }
233             TerminatorKind::GeneratorDrop => {
234                 unimplemented!("terminator GeneratorDrop");
235             }
236         };
237     }
238
239     fx.bcx.seal_all_blocks();
240     fx.bcx.finalize();
241 }
242
243 fn trans_stmt<'a, 'tcx: 'a>(
244     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
245     cur_ebb: Ebb,
246     stmt: &Statement<'tcx>,
247 ) {
248     let _print_guard = PrintOnPanic(format!("stmt {:?}", stmt));
249
250     let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
251     fx.add_comment(inst, format!("{:?}", stmt));
252
253     match &stmt.kind {
254         StatementKind::SetDiscriminant {
255             place,
256             variant_index,
257         } => {
258             let place = trans_place(fx, place);
259             let layout = place.layout();
260             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
261                 return;
262             }
263             match layout.variants {
264                 layout::Variants::Single { index } => {
265                     assert_eq!(index, *variant_index);
266                 }
267                 layout::Variants::Tagged { .. } => {
268                     let ptr = place.place_field(fx, mir::Field::new(0));
269                     let to = layout
270                         .ty
271                         .ty_adt_def()
272                         .unwrap()
273                         .discriminant_for_variant(fx.tcx, *variant_index)
274                         .val;
275                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
276                     ptr.write_cvalue(fx, discr);
277                 }
278                 layout::Variants::NicheFilling {
279                     dataful_variant,
280                     ref niche_variants,
281                     niche_start,
282                     ..
283                 } => {
284                     if *variant_index != dataful_variant {
285                         let niche = place.place_field(fx, mir::Field::new(0));
286                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
287                         let niche_value = ((variant_index - *niche_variants.start()) as u128)
288                             .wrapping_add(niche_start);
289                         // FIXME(eddyb) Check the actual primitive type here.
290                         let niche_llval = if niche_value == 0 {
291                             CValue::const_val(fx, niche.layout().ty, 0)
292                         } else {
293                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
294                         };
295                         niche.write_cvalue(fx, niche_llval);
296                     }
297                 }
298             }
299         }
300         StatementKind::Assign(to_place, rval) => {
301             let lval = trans_place(fx, to_place);
302             let dest_layout = lval.layout();
303             match rval {
304                 Rvalue::Use(operand) => {
305                     let val = trans_operand(fx, operand);
306                     lval.write_cvalue(fx, val);
307                 }
308                 Rvalue::Ref(_, _, place) => {
309                     let place = trans_place(fx, place);
310                     let addr = place.expect_addr();
311                     lval.write_cvalue(fx, CValue::ByVal(addr, dest_layout));
312                 }
313                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
314                     let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
315                     let lhs = trans_operand(fx, lhs);
316                     let rhs = trans_operand(fx, rhs);
317
318                     let res = match ty.sty {
319                         TypeVariants::TyBool => {
320                             trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
321                         }
322                         TypeVariants::TyUint(_) => {
323                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
324                         }
325                         TypeVariants::TyInt(_) => {
326                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
327                         }
328                         TypeVariants::TyFloat(_) => {
329                             trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
330                         }
331                         TypeVariants::TyChar => {
332                             trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
333                         }
334                         TypeVariants::TyRawPtr(..) => {
335                             trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
336                         }
337                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
338                     };
339                     lval.write_cvalue(fx, res);
340                 }
341                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
342                     let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
343                     let lhs = trans_operand(fx, lhs);
344                     let rhs = trans_operand(fx, rhs);
345
346                     let res = match ty.sty {
347                         TypeVariants::TyUint(_) => {
348                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
349                         }
350                         TypeVariants::TyInt(_) => {
351                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
352                         }
353                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
354                     };
355                     lval.write_cvalue(fx, res);
356                 }
357                 Rvalue::UnaryOp(un_op, operand) => {
358                     let ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
359                     let layout = fx.layout_of(ty);
360                     let val = trans_operand(fx, operand).load_value(fx);
361                     let res = match un_op {
362                         UnOp::Not => fx.bcx.ins().bnot(val),
363                         UnOp::Neg => match ty.sty {
364                             TypeVariants::TyInt(_) => {
365                                 let clif_ty = fx.cton_type(ty).unwrap();
366                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
367                                 fx.bcx.ins().isub(zero, val)
368                             }
369                             TypeVariants::TyFloat(_) => fx.bcx.ins().fneg(val),
370                             _ => unimplemented!("un op Neg for {:?}", ty),
371                         },
372                     };
373                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
374                 }
375                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
376                     let operand = trans_operand(fx, operand);
377                     let layout = fx.layout_of(ty);
378                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
379                 }
380                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
381                     let operand = trans_operand(fx, operand);
382                     let layout = fx.layout_of(ty);
383                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
384                 }
385                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
386                     let operand = trans_operand(fx, operand);
387                     let from_ty = operand.layout().ty;
388                     match (&from_ty.sty, &to_ty.sty) {
389                         (TypeVariants::TyRef(..), TypeVariants::TyRef(..))
390                         | (TypeVariants::TyRef(..), TypeVariants::TyRawPtr(..))
391                         | (TypeVariants::TyRawPtr(..), TypeVariants::TyRef(..))
392                         | (TypeVariants::TyRawPtr(..), TypeVariants::TyRawPtr(..)) => {
393                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
394                         }
395                         (TypeVariants::TyRawPtr(..), TypeVariants::TyUint(_))
396                         | (TypeVariants::TyFnPtr(..), TypeVariants::TyUint(_))
397                             if to_ty.sty == fx.tcx.types.usize.sty =>
398                         {
399                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
400                         }
401                         (TypeVariants::TyUint(_), TypeVariants::TyRawPtr(..))
402                             if from_ty.sty == fx.tcx.types.usize.sty =>
403                         {
404                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
405                         }
406                         (TypeVariants::TyChar, TypeVariants::TyUint(_))
407                         | (TypeVariants::TyUint(_), TypeVariants::TyChar)
408                         | (TypeVariants::TyUint(_), TypeVariants::TyInt(_))
409                         | (TypeVariants::TyUint(_), TypeVariants::TyUint(_)) => {
410                             let from = operand.load_value(fx);
411                             let res = crate::common::cton_intcast(
412                                 fx,
413                                 from,
414                                 fx.cton_type(to_ty).unwrap(),
415                                 false,
416                             );
417                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
418                         }
419                         (TypeVariants::TyInt(_), TypeVariants::TyInt(_))
420                         | (TypeVariants::TyInt(_), TypeVariants::TyUint(_)) => {
421                             let from = operand.load_value(fx);
422                             let res = crate::common::cton_intcast(
423                                 fx,
424                                 from,
425                                 fx.cton_type(to_ty).unwrap(),
426                                 true,
427                             );
428                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
429                         }
430                         (TypeVariants::TyFloat(from_flt), TypeVariants::TyFloat(to_flt)) => {
431                             let from = operand.load_value(fx);
432                             let res = match (from_flt, to_flt) {
433                                 (FloatTy::F32, FloatTy::F64) => {
434                                     fx.bcx.ins().fpromote(types::F64, from)
435                                 }
436                                 (FloatTy::F64, FloatTy::F32) => {
437                                     fx.bcx.ins().fdemote(types::F32, from)
438                                 }
439                                 _ => from,
440                             };
441                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
442                         }
443                         (TypeVariants::TyInt(_), TypeVariants::TyFloat(_)) => {
444                             let from = operand.load_value(fx);
445                             let f_type = fx.cton_type(to_ty).unwrap();
446                             let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
447                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
448                         }
449                         (TypeVariants::TyUint(_), TypeVariants::TyFloat(_)) => {
450                             let from = operand.load_value(fx);
451                             let f_type = fx.cton_type(to_ty).unwrap();
452                             let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
453                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
454                         }
455                         (TypeVariants::TyBool, TypeVariants::TyUint(_))
456                         | (TypeVariants::TyBool, TypeVariants::TyInt(_)) => {
457                             let to_ty = fx.cton_type(to_ty).unwrap();
458                             let from = operand.load_value(fx);
459                             let res = if to_ty != types::I8 {
460                                 fx.bcx.ins().uextend(to_ty, from)
461                             } else {
462                                 from
463                             };
464                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
465                         }
466                         _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
467                     }
468                 }
469                 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
470                     unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
471                 }
472                 Rvalue::Cast(CastKind::Unsize, operand, ty) => {
473                     unimpl!("rval unsize {:?} {:?}", operand, ty);
474                 }
475                 Rvalue::Discriminant(place) => {
476                     let place = trans_place(fx, place).to_cvalue(fx);
477                     let discr = trans_get_discriminant(fx, place, dest_layout);
478                     lval.write_cvalue(fx, discr);
479                 }
480                 Rvalue::Repeat(operand, times) => {
481                     let operand = trans_operand(fx, operand);
482                     for i in 0..*times {
483                         let index = fx.bcx.ins().iconst(types::I64, i as i64);
484                         let to = lval.place_index(fx, index);
485                         to.write_cvalue(fx, operand);
486                     }
487                 }
488                 Rvalue::Len(lval) => unimpl!("rval len {:?}", lval),
489                 Rvalue::NullaryOp(NullOp::Box, ty) => unimplemented!("rval box {:?}", ty),
490                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
491                     assert!(
492                         lval.layout()
493                             .ty
494                             .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
495                     );
496                     let ty_size = fx.layout_of(ty).size.bytes();
497                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
498                     lval.write_cvalue(fx, val);
499                 }
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(types::I64, i as i64);
505                             let to = lval.place_index(fx, index);
506                             to.write_cvalue(fx, operand);
507                         }
508                     }
509                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
510                 },
511             }
512         }
513         StatementKind::StorageLive(_)
514         | StatementKind::StorageDead(_)
515         | StatementKind::Nop
516         | StatementKind::ReadForMatch(_)
517         | StatementKind::Validate(_, _)
518         | StatementKind::EndRegion(_)
519         | StatementKind::UserAssertTy(_, _) => {}
520
521         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
522     }
523 }
524
525 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
526     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
527     value: CValue<'tcx>,
528     dest_layout: TyLayout<'tcx>,
529 ) -> CValue<'tcx> {
530     let layout = value.layout();
531
532     if layout.abi == layout::Abi::Uninhabited {
533         fx.bcx.ins().trap(TrapCode::User(!0));
534     }
535     match layout.variants {
536         layout::Variants::Single { index } => {
537             let discr_val = layout.ty.ty_adt_def().map_or(index as u128, |def| {
538                 def.discriminant_for_variant(fx.tcx, index).val
539             });
540             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
541         }
542         layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
543     }
544
545     let discr = value.value_field(fx, mir::Field::new(0));
546     let discr_ty = discr.layout().ty;
547     let lldiscr = discr.load_value(fx);
548     match layout.variants {
549         layout::Variants::Single { .. } => bug!(),
550         layout::Variants::Tagged { ref tag, .. } => {
551             let signed = match tag.value {
552                 layout::Int(_, signed) => signed,
553                 _ => false,
554             };
555             let val = cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), signed);
556             return CValue::ByVal(val, dest_layout);
557         }
558         layout::Variants::NicheFilling {
559             dataful_variant,
560             ref niche_variants,
561             niche_start,
562             ..
563         } => {
564             let niche_llty = fx.cton_type(discr_ty).unwrap();
565             let dest_cton_ty = fx.cton_type(dest_layout.ty).unwrap();
566             if niche_variants.start() == niche_variants.end() {
567                 let b = fx
568                     .bcx
569                     .ins()
570                     .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
571                 let if_true = fx
572                     .bcx
573                     .ins()
574                     .iconst(dest_cton_ty, *niche_variants.start() as u64 as i64);
575                 let if_false = fx
576                     .bcx
577                     .ins()
578                     .iconst(dest_cton_ty, dataful_variant as u64 as i64);
579                 let val = fx.bcx.ins().select(b, if_true, if_false);
580                 return CValue::ByVal(val, dest_layout);
581             } else {
582                 // Rebase from niche values to discriminant values.
583                 let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
584                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
585                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
586                 let b = fx.bcx.ins().icmp_imm(
587                     IntCC::UnsignedLessThanOrEqual,
588                     lldiscr,
589                     *niche_variants.end() as u64 as i64,
590                 );
591                 let if_true =
592                     cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), false);
593                 let if_false = fx
594                     .bcx
595                     .ins()
596                     .iconst(dest_cton_ty, dataful_variant as u64 as i64);
597                 let val = fx.bcx.ins().select(b, if_true, if_false);
598                 return CValue::ByVal(val, dest_layout);
599             }
600         }
601     }
602 }
603
604 macro_rules! binop_match {
605     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
606         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
607     };
608     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
609         assert_eq!($fx.tcx.types.bool, $ret_ty);
610         let ret_layout = $fx.layout_of($ret_ty);
611
612         // TODO HACK no encoding for icmp.i8
613         use crate::common::cton_intcast;
614         let (lhs, rhs) = (
615             cton_intcast($fx, $lhs, types::I64, $signed),
616             cton_intcast($fx, $rhs, types::I64, $signed),
617         );
618         let b = $fx.bcx.ins().icmp(IntCC::$cc, lhs, rhs);
619
620         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
621     }};
622     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
623         assert_eq!($fx.tcx.types.bool, $ret_ty);
624         let ret_layout = $fx.layout_of($ret_ty);
625         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
626         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
627     }};
628     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
629         $body
630     }};
631     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
632         let ret_layout = $fx.layout_of($ret_ty);
633         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
634     }};
635     (
636         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
637         $(
638             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
639         )*
640     ) => {{
641         let lhs = $lhs.load_value($fx);
642         let rhs = $rhs.load_value($fx);
643         match ($bin_op, $signed) {
644             $(
645                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
646             )*
647         }
648     }}
649 }
650
651 fn trans_bool_binop<'a, 'tcx: 'a>(
652     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
653     bin_op: BinOp,
654     lhs: CValue<'tcx>,
655     rhs: CValue<'tcx>,
656     ty: Ty<'tcx>,
657 ) -> CValue<'tcx> {
658     let res = binop_match! {
659         fx, bin_op, false, lhs, rhs, ty, "bool";
660         Add (_) bug;
661         Sub (_) bug;
662         Mul (_) bug;
663         Div (_) bug;
664         Rem (_) bug;
665         BitXor (_) bxor;
666         BitAnd (_) band;
667         BitOr (_) bor;
668         Shl (_) bug;
669         Shr (_) bug;
670
671         Eq (_) icmp(Equal);
672         Lt (_) icmp(UnsignedLessThan);
673         Le (_) icmp(UnsignedLessThanOrEqual);
674         Ne (_) icmp(NotEqual);
675         Ge (_) icmp(UnsignedGreaterThanOrEqual);
676         Gt (_) icmp(UnsignedGreaterThan);
677
678         Offset (_) bug;
679     };
680
681     res
682 }
683
684 pub fn trans_int_binop<'a, 'tcx: 'a>(
685     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
686     bin_op: BinOp,
687     lhs: CValue<'tcx>,
688     rhs: CValue<'tcx>,
689     out_ty: Ty<'tcx>,
690     signed: bool,
691 ) -> CValue<'tcx> {
692     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
693         assert_eq!(
694             lhs.layout().ty,
695             rhs.layout().ty,
696             "int binop requires lhs and rhs of same type"
697         );
698     }
699     binop_match! {
700         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
701         Add (_) iadd;
702         Sub (_) isub;
703         Mul (_) imul;
704         Div (false) udiv;
705         Div (true) sdiv;
706         Rem (false) urem;
707         Rem (true) srem;
708         BitXor (_) bxor;
709         BitAnd (_) band;
710         BitOr (_) bor;
711         Shl (_) ishl;
712         Shr (false) ushr;
713         Shr (true) sshr;
714
715         Eq (_) icmp(Equal);
716         Lt (false) icmp(UnsignedLessThan);
717         Lt (true) icmp(SignedLessThan);
718         Le (false) icmp(UnsignedLessThanOrEqual);
719         Le (true) icmp(SignedLessThanOrEqual);
720         Ne (_) icmp(NotEqual);
721         Ge (false) icmp(UnsignedGreaterThanOrEqual);
722         Ge (true) icmp(SignedGreaterThanOrEqual);
723         Gt (false) icmp(UnsignedGreaterThan);
724         Gt (true) icmp(SignedGreaterThan);
725
726         Offset (_) bug;
727     }
728 }
729
730 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
731     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
732     bin_op: BinOp,
733     lhs: CValue<'tcx>,
734     rhs: CValue<'tcx>,
735     out_ty: Ty<'tcx>,
736     signed: bool,
737 ) -> CValue<'tcx> {
738     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
739         assert_eq!(
740             lhs.layout().ty,
741             rhs.layout().ty,
742             "checked int binop requires lhs and rhs of same type"
743         );
744     }
745     let res_ty = match out_ty.sty {
746         TypeVariants::TyTuple(tys) => tys[0],
747         _ => bug!(
748             "Checked int binop requires tuple as output, but got {:?}",
749             out_ty
750         ),
751     };
752
753     let res = binop_match! {
754         fx, bin_op, signed, lhs, rhs, res_ty, "checked int/uint";
755         Add (_) iadd;
756         Sub (_) isub;
757         Mul (_) imul;
758         Div (_) bug;
759         Rem (_) bug;
760         BitXor (_) bug;
761         BitAnd (_) bug;
762         BitOr (_) bug;
763         Shl (_) ishl;
764         Shr (false) ushr;
765         Shr (true) sshr;
766
767         Eq (_) bug;
768         Lt (_) bug;
769         Le (_) bug;
770         Ne (_) bug;
771         Ge (_) bug;
772         Gt (_) bug;
773
774         Offset (_) bug;
775     };
776
777     // TODO: check for overflow
778     let has_overflow = CValue::const_val(fx, fx.tcx.types.bool, 0);
779
780     let out_place = CPlace::temp(fx, out_ty);
781     out_place
782         .place_field(fx, mir::Field::new(0))
783         .write_cvalue(fx, res);
784     out_place
785         .place_field(fx, mir::Field::new(1))
786         .write_cvalue(fx, has_overflow);
787
788     out_place.to_cvalue(fx)
789 }
790
791 fn trans_float_binop<'a, 'tcx: 'a>(
792     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
793     bin_op: BinOp,
794     lhs: CValue<'tcx>,
795     rhs: CValue<'tcx>,
796     ty: Ty<'tcx>,
797 ) -> CValue<'tcx> {
798     let res = binop_match! {
799         fx, bin_op, false, lhs, rhs, ty, "float";
800         Add (_) fadd;
801         Sub (_) fsub;
802         Mul (_) fmul;
803         Div (_) fdiv;
804         Rem (_) custom(|| {
805             assert_eq!(lhs.layout().ty, ty);
806             assert_eq!(rhs.layout().ty, ty);
807             match ty.sty {
808                 TypeVariants::TyFloat(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
809                 TypeVariants::TyFloat(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
810                 _ => bug!(),
811             }
812         });
813         BitXor (_) bxor;
814         BitAnd (_) band;
815         BitOr (_) bor;
816         Shl (_) bug;
817         Shr (_) bug;
818
819         Eq (_) fcmp(Equal);
820         Lt (_) fcmp(LessThan);
821         Le (_) fcmp(LessThanOrEqual);
822         Ne (_) fcmp(NotEqual);
823         Ge (_) fcmp(GreaterThanOrEqual);
824         Gt (_) fcmp(GreaterThan);
825
826         Offset (_) bug;
827     };
828
829     res
830 }
831
832 fn trans_char_binop<'a, 'tcx: 'a>(
833     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
834     bin_op: BinOp,
835     lhs: CValue<'tcx>,
836     rhs: CValue<'tcx>,
837     ty: Ty<'tcx>,
838 ) -> CValue<'tcx> {
839     let res = binop_match! {
840         fx, bin_op, false, lhs, rhs, ty, "char";
841         Add (_) bug;
842         Sub (_) bug;
843         Mul (_) bug;
844         Div (_) bug;
845         Rem (_) bug;
846         BitXor (_) bug;
847         BitAnd (_) bug;
848         BitOr (_) bug;
849         Shl (_) bug;
850         Shr (_) bug;
851
852         Eq (_) icmp(Equal);
853         Lt (_) icmp(UnsignedLessThan);
854         Le (_) icmp(UnsignedLessThanOrEqual);
855         Ne (_) icmp(NotEqual);
856         Ge (_) icmp(UnsignedGreaterThanOrEqual);
857         Gt (_) icmp(UnsignedGreaterThan);
858
859         Offset (_) bug;
860     };
861
862     res
863 }
864
865 fn trans_ptr_binop<'a, 'tcx: 'a>(
866     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
867     bin_op: BinOp,
868     lhs: CValue<'tcx>,
869     rhs: CValue<'tcx>,
870     ty: Ty<'tcx>,
871 ) -> CValue<'tcx> {
872     match lhs.layout().ty.sty {
873         TypeVariants::TyRawPtr(TypeAndMut { ty, mutbl: _ }) => {
874             if !ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
875                 unimpl!("Unsized values are not yet implemented");
876             }
877         }
878         _ => bug!("trans_ptr_binop on non ptr"),
879     }
880     binop_match! {
881         fx, bin_op, false, lhs, rhs, ty, "ptr";
882         Add (_) bug;
883         Sub (_) bug;
884         Mul (_) bug;
885         Div (_) bug;
886         Rem (_) bug;
887         BitXor (_) bug;
888         BitAnd (_) bug;
889         BitOr (_) bug;
890         Shl (_) bug;
891         Shr (_) bug;
892
893         Eq (_) icmp(Equal);
894         Lt (_) icmp(UnsignedLessThan);
895         Le (_) icmp(UnsignedLessThanOrEqual);
896         Ne (_) icmp(NotEqual);
897         Ge (_) icmp(UnsignedGreaterThanOrEqual);
898         Gt (_) icmp(UnsignedGreaterThan);
899
900         Offset (_) iadd;
901     }
902 }
903
904 pub fn trans_place<'a, 'tcx: 'a>(
905     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
906     place: &Place<'tcx>,
907 ) -> CPlace<'tcx> {
908     match place {
909         Place::Local(local) => fx.get_local_place(*local),
910         Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
911         Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
912         Place::Projection(projection) => {
913             let base = trans_place(fx, &projection.base);
914             match projection.elem {
915                 ProjectionElem::Deref => {
916                     let layout = fx.layout_of(place.ty(&*fx.mir, fx.tcx).to_ty(fx.tcx));
917                     if layout.is_unsized() {
918                         unimpl!("Unsized places are not yet implemented");
919                     }
920                     CPlace::Addr(base.to_cvalue(fx).load_value(fx), layout)
921                 }
922                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
923                 ProjectionElem::Index(local) => {
924                     let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
925                     base.place_index(fx, index)
926                 }
927                 ProjectionElem::ConstantIndex {
928                     offset,
929                     min_length: _,
930                     from_end: false,
931                 } => unimplemented!(
932                     "projection const index {:?} offset {:?} not from end",
933                     projection.base,
934                     offset
935                 ),
936                 ProjectionElem::ConstantIndex {
937                     offset,
938                     min_length: _,
939                     from_end: true,
940                 } => unimplemented!(
941                     "projection const index {:?} offset {:?} from end",
942                     projection.base,
943                     offset
944                 ),
945                 ProjectionElem::Subslice { from, to } => unimplemented!(
946                     "projection subslice {:?} from {} to {}",
947                     projection.base,
948                     from,
949                     to
950                 ),
951                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
952             }
953         }
954     }
955 }
956
957 pub fn trans_operand<'a, 'tcx>(
958     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
959     operand: &Operand<'tcx>,
960 ) -> CValue<'tcx> {
961     match operand {
962         Operand::Move(place) | Operand::Copy(place) => {
963             let cplace = trans_place(fx, place);
964             cplace.to_cvalue(fx)
965         }
966         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
967     }
968 }