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