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