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