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