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