]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Merge pull request #339 from bjorn3/fix_libstd
[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, false);
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         source_info_set: indexmap::IndexSet::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 source_info_set = fx.source_info_set.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, &source_info_set));
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             | TerminatorKind::GeneratorDrop => {
247                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
248             }
249             TerminatorKind::Drop {
250                 location,
251                 target,
252                 unwind: _,
253             } => {
254                 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
255                 let ty = fx.monomorphize(&ty);
256                 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
257
258                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
259                     // we don't actually need to drop anything
260                 } else {
261                     let drop_place = trans_place(fx, location);
262                     let drop_fn_ty = drop_fn.ty(fx.tcx);
263                     match ty.sty {
264                         ty::Dynamic(..) => {
265                             crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
266                         }
267                         _ => {
268                             let arg_place = CPlace::new_stack_slot(
269                                 fx,
270                                 fx.tcx.mk_ref(
271                                     &ty::RegionKind::ReErased,
272                                     TypeAndMut {
273                                         ty,
274                                         mutbl: crate::rustc::hir::Mutability::MutMutable,
275                                     },
276                                 ),
277                             );
278                             drop_place.write_place_ref(fx, arg_place);
279                             let arg_value = arg_place.to_cvalue(fx);
280                             crate::abi::codegen_call_inner(
281                                 fx,
282                                 None,
283                                 drop_fn_ty,
284                                 vec![arg_value],
285                                 None,
286                             );
287                         }
288                     }
289                 }
290
291                 let target_ebb = fx.get_ebb(*target);
292                 fx.bcx.ins().jump(target_ebb, &[]);
293             }
294         };
295     }
296
297     fx.bcx.seal_all_blocks();
298     fx.bcx.finalize();
299 }
300
301 fn trans_stmt<'a, 'tcx: 'a>(
302     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
303     cur_ebb: Ebb,
304     stmt: &Statement<'tcx>,
305 ) {
306     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
307
308     fx.set_debug_loc(stmt.source_info);
309
310     #[cfg(debug_assertions)]
311     match &stmt.kind {
312         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
313         _ => {
314             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
315             fx.add_comment(inst, format!("{:?}", stmt));
316         }
317     }
318
319     match &stmt.kind {
320         StatementKind::SetDiscriminant {
321             place,
322             variant_index,
323         } => {
324             let place = trans_place(fx, place);
325             let layout = place.layout();
326             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
327                 return;
328             }
329             match layout.variants {
330                 layout::Variants::Single { index } => {
331                     assert_eq!(index, *variant_index);
332                 }
333                 layout::Variants::Tagged { .. } => {
334                     let ptr = place.place_field(fx, mir::Field::new(0));
335                     let to = layout
336                         .ty
337                         .ty_adt_def()
338                         .unwrap()
339                         .discriminant_for_variant(fx.tcx, *variant_index)
340                         .val;
341                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
342                     ptr.write_cvalue(fx, discr);
343                 }
344                 layout::Variants::NicheFilling {
345                     dataful_variant,
346                     ref niche_variants,
347                     niche_start,
348                     ..
349                 } => {
350                     if *variant_index != dataful_variant {
351                         let niche = place.place_field(fx, mir::Field::new(0));
352                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
353                         let niche_value =
354                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
355                                 .wrapping_add(niche_start);
356                         // FIXME(eddyb) Check the actual primitive type here.
357                         let niche_llval = if niche_value == 0 {
358                             CValue::const_val(fx, niche.layout().ty, 0)
359                         } else {
360                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
361                         };
362                         niche.write_cvalue(fx, niche_llval);
363                     }
364                 }
365             }
366         }
367         StatementKind::Assign(to_place, rval) => {
368             let lval = trans_place(fx, to_place);
369             let dest_layout = lval.layout();
370             match &**rval {
371                 Rvalue::Use(operand) => {
372                     let val = trans_operand(fx, operand);
373                     lval.write_cvalue(fx, val);
374                 }
375                 Rvalue::Ref(_, _, place) => {
376                     let place = trans_place(fx, place);
377                     place.write_place_ref(fx, lval);
378                 }
379                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
380                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
381                     let lhs = trans_operand(fx, lhs);
382                     let rhs = trans_operand(fx, rhs);
383
384                     let res = match ty.sty {
385                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
386                         ty::Uint(_) => {
387                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
388                         }
389                         ty::Int(_) => {
390                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
391                         }
392                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
393                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
394                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
395                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
396                     };
397                     lval.write_cvalue(fx, res);
398                 }
399                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
400                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
401                     let lhs = trans_operand(fx, lhs);
402                     let rhs = trans_operand(fx, rhs);
403
404                     let res = match ty.sty {
405                         ty::Uint(_) => {
406                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
407                         }
408                         ty::Int(_) => {
409                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
410                         }
411                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
412                     };
413                     lval.write_cvalue(fx, res);
414                 }
415                 Rvalue::UnaryOp(un_op, operand) => {
416                     let operand = trans_operand(fx, operand);
417                     let layout = operand.layout();
418                     let val = operand.load_scalar(fx);
419                     let res = match un_op {
420                         UnOp::Not => {
421                             match layout.ty.sty {
422                                 ty::Bool => {
423                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
424                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
425                                     fx.bcx.ins().bint(types::I8, res)
426                                 }
427                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
428                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
429                             }
430                         }
431                         UnOp::Neg => match layout.ty.sty {
432                             ty::Int(_) => {
433                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
434                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
435                                 fx.bcx.ins().isub(zero, val)
436                             }
437                             ty::Float(_) => fx.bcx.ins().fneg(val),
438                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
439                         },
440                     };
441                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
442                 }
443                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
444                     let layout = fx.layout_of(ty);
445                     match fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx)).sty {
446                         ty::FnDef(def_id, substs) => {
447                             let func_ref = fx.get_function_ref(
448                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap(),
449                             );
450                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
451                             lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
452                         }
453                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
454                     }
455                 }
456                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
457                     let operand = trans_operand(fx, operand);
458                     let layout = fx.layout_of(ty);
459                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
460                 }
461                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
462                     let operand = trans_operand(fx, operand);
463                     let from_ty = operand.layout().ty;
464                     match (&from_ty.sty, &to_ty.sty) {
465                         (ty::Ref(..), ty::Ref(..))
466                         | (ty::Ref(..), ty::RawPtr(..))
467                         | (ty::RawPtr(..), ty::Ref(..))
468                         | (ty::RawPtr(..), ty::RawPtr(..))
469                         | (ty::FnPtr(..), ty::RawPtr(..)) => {
470                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
471                         }
472                         (ty::RawPtr(..), ty::Uint(_))
473                         | (ty::RawPtr(..), ty::Int(_))
474                         | (ty::FnPtr(..), ty::Uint(_))
475                             if to_ty.sty == fx.tcx.types.usize.sty
476                                 || to_ty.sty == fx.tcx.types.isize.sty
477                                 || fx.clif_type(to_ty).unwrap() == pointer_ty(fx.tcx) =>
478                         {
479                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
480                         }
481                         (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
482                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
483                         }
484                         (ty::Char, ty::Uint(_))
485                         | (ty::Uint(_), ty::Char)
486                         | (ty::Uint(_), ty::Int(_))
487                         | (ty::Uint(_), ty::Uint(_)) => {
488                             let from = operand.load_scalar(fx);
489                             let res = crate::common::clif_intcast(
490                                 fx,
491                                 from,
492                                 fx.clif_type(to_ty).unwrap(),
493                                 false,
494                             );
495                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
496                         }
497                         (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
498                             let from = operand.load_scalar(fx);
499                             let res = crate::common::clif_intcast(
500                                 fx,
501                                 from,
502                                 fx.clif_type(to_ty).unwrap(),
503                                 true,
504                             );
505                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
506                         }
507                         (ty::Float(from_flt), ty::Float(to_flt)) => {
508                             let from = operand.load_scalar(fx);
509                             let res = match (from_flt, to_flt) {
510                                 (FloatTy::F32, FloatTy::F64) => {
511                                     fx.bcx.ins().fpromote(types::F64, from)
512                                 }
513                                 (FloatTy::F64, FloatTy::F32) => {
514                                     fx.bcx.ins().fdemote(types::F32, from)
515                                 }
516                                 _ => from,
517                             };
518                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
519                         }
520                         (ty::Int(_), ty::Float(_)) => {
521                             let from_ty = fx.clif_type(from_ty).unwrap();
522                             let from = operand.load_scalar(fx);
523                             // FIXME missing encoding for fcvt_from_sint.f32.i8
524                             let from = if from_ty == types::I8 || from_ty == types::I16 {
525                                 fx.bcx.ins().sextend(types::I32, from)
526                             } else {
527                                 from
528                             };
529                             let f_type = fx.clif_type(to_ty).unwrap();
530                             let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
531                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
532                         }
533                         (ty::Uint(_), ty::Float(_)) => {
534                             let from_ty = fx.clif_type(from_ty).unwrap();
535                             let from = operand.load_scalar(fx);
536                             // FIXME missing encoding for fcvt_from_uint.f32.i8
537                             let from = if from_ty == types::I8 || from_ty == types::I16 {
538                                 fx.bcx.ins().uextend(types::I32, from)
539                             } else {
540                                 from
541                             };
542                             let f_type = fx.clif_type(to_ty).unwrap();
543                             let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
544                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
545                         }
546                         (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
547                             let to_ty = fx.clif_type(to_ty).unwrap();
548                             let from = operand.load_scalar(fx);
549                             let res = if to_ty != types::I8 {
550                                 fx.bcx.ins().uextend(to_ty, from)
551                             } else {
552                                 from
553                             };
554                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
555                         }
556                         (ty::Adt(adt_def, _substs), ty::Uint(_)) | (ty::Adt(adt_def, _substs), ty::Int(_)) if adt_def.is_enum() => {
557                             let discr = trans_get_discriminant(fx, operand, fx.layout_of(to_ty));
558                             lval.write_cvalue(fx, discr);
559                         }
560                         _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
561                     }
562                 }
563                 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
564                     unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
565                 }
566                 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
567                     let operand = trans_operand(fx, operand);
568                     operand.unsize_value(fx, lval);
569                 }
570                 Rvalue::Discriminant(place) => {
571                     let place = trans_place(fx, place).to_cvalue(fx);
572                     let discr = trans_get_discriminant(fx, place, dest_layout);
573                     lval.write_cvalue(fx, discr);
574                 }
575                 Rvalue::Repeat(operand, times) => {
576                     let operand = trans_operand(fx, operand);
577                     for i in 0..*times {
578                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
579                         let to = lval.place_index(fx, index);
580                         to.write_cvalue(fx, operand);
581                     }
582                 }
583                 Rvalue::Len(place) => {
584                     let place = trans_place(fx, place);
585                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
586                     let len = codegen_array_len(fx, place);
587                     lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
588                 }
589                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
590                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
591
592                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
593                     let layout = fx.layout_of(content_ty);
594                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
595                     let llalign = fx
596                         .bcx
597                         .ins()
598                         .iconst(usize_type, layout.align.abi.bytes() as i64);
599                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
600
601                     // Allocate space:
602                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
603                         Ok(id) => id,
604                         Err(s) => {
605                             fx.tcx
606                                 .sess
607                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
608                         }
609                     };
610                     let instance = ty::Instance::mono(fx.tcx, def_id);
611                     let func_ref = fx.get_function_ref(instance);
612                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
613                     let ptr = fx.bcx.inst_results(call)[0];
614                     lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
615                 }
616                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
617                     assert!(lval
618                         .layout()
619                         .ty
620                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
621                     let ty_size = fx.layout_of(ty).size.bytes();
622                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
623                     lval.write_cvalue(fx, val);
624                 }
625                 Rvalue::Aggregate(kind, operands) => match **kind {
626                     AggregateKind::Array(_ty) => {
627                         for (i, operand) in operands.into_iter().enumerate() {
628                             let operand = trans_operand(fx, operand);
629                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
630                             let to = lval.place_index(fx, index);
631                             to.write_cvalue(fx, operand);
632                         }
633                     }
634                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
635                 },
636             }
637         }
638         StatementKind::StorageLive(_)
639         | StatementKind::StorageDead(_)
640         | StatementKind::Nop
641         | StatementKind::FakeRead(..)
642         | StatementKind::Retag { .. }
643         | StatementKind::AscribeUserType(..) => {}
644
645         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
646     }
647 }
648
649 fn codegen_array_len<'a, 'tcx: 'a>(
650     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
651     place: CPlace<'tcx>,
652 ) -> Value {
653     match place.layout().ty.sty {
654         ty::Array(_elem_ty, len) => {
655             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
656             fx.bcx.ins().iconst(fx.pointer_type, len)
657         }
658         ty::Slice(_elem_ty) => {
659             place.to_addr_maybe_unsized(fx).1.expect("Length metadata for slice place")
660         }
661         _ => bug!("Rvalue::Len({:?})", place),
662     }
663 }
664
665 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
666     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
667     value: CValue<'tcx>,
668     dest_layout: TyLayout<'tcx>,
669 ) -> CValue<'tcx> {
670     let layout = value.layout();
671
672     if layout.abi == layout::Abi::Uninhabited {
673         trap_unreachable(&mut fx.bcx);
674     }
675     match layout.variants {
676         layout::Variants::Single { index } => {
677             let discr_val = layout
678                 .ty
679                 .ty_adt_def()
680                 .map_or(index.as_u32() as u128, |def| {
681                     def.discriminant_for_variant(fx.tcx, index).val
682                 });
683             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
684         }
685         layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
686     }
687
688     let discr = value.value_field(fx, mir::Field::new(0));
689     let discr_ty = discr.layout().ty;
690     let lldiscr = discr.load_scalar(fx);
691     match layout.variants {
692         layout::Variants::Single { .. } => bug!(),
693         layout::Variants::Tagged { ref tag, .. } => {
694             let signed = match tag.value {
695                 layout::Int(_, signed) => signed,
696                 _ => false,
697             };
698             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
699             return CValue::ByVal(val, dest_layout);
700         }
701         layout::Variants::NicheFilling {
702             dataful_variant,
703             ref niche_variants,
704             niche_start,
705             ..
706         } => {
707             let niche_llty = fx.clif_type(discr_ty).unwrap();
708             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
709             if niche_variants.start() == niche_variants.end() {
710                 let b = fx
711                     .bcx
712                     .ins()
713                     .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
714                 let if_true = fx
715                     .bcx
716                     .ins()
717                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
718                 let if_false = fx
719                     .bcx
720                     .ins()
721                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
722                 let val = fx.bcx.ins().select(b, if_true, if_false);
723                 return CValue::ByVal(val, dest_layout);
724             } else {
725                 // Rebase from niche values to discriminant values.
726                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
727                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
728                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
729                 let b = fx.bcx.ins().icmp_imm(
730                     IntCC::UnsignedLessThanOrEqual,
731                     lldiscr,
732                     niche_variants.end().as_u32() as i64,
733                 );
734                 let if_true =
735                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
736                 let if_false = fx
737                     .bcx
738                     .ins()
739                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
740                 let val = fx.bcx.ins().select(b, if_true, if_false);
741                 return CValue::ByVal(val, dest_layout);
742             }
743         }
744     }
745 }
746
747 macro_rules! binop_match {
748     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
749         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
750     };
751     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
752         assert_eq!($fx.tcx.types.bool, $ret_ty);
753         let ret_layout = $fx.layout_of($ret_ty);
754
755         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
756         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
757     }};
758     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
759         assert_eq!($fx.tcx.types.bool, $ret_ty);
760         let ret_layout = $fx.layout_of($ret_ty);
761         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
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, custom(|| $body:expr)) => {{
765         $body
766     }};
767     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
768         let ret_layout = $fx.layout_of($ret_ty);
769         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
770     }};
771     (
772         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
773         $(
774             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
775         )*
776     ) => {{
777         let lhs = $lhs.load_scalar($fx);
778         let rhs = $rhs.load_scalar($fx);
779         match ($bin_op, $signed) {
780             $(
781                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
782             )*
783         }
784     }}
785 }
786
787 fn trans_bool_binop<'a, 'tcx: 'a>(
788     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
789     bin_op: BinOp,
790     lhs: CValue<'tcx>,
791     rhs: CValue<'tcx>,
792     ty: Ty<'tcx>,
793 ) -> CValue<'tcx> {
794     let res = binop_match! {
795         fx, bin_op, false, lhs, rhs, ty, "bool";
796         Add (_) bug;
797         Sub (_) bug;
798         Mul (_) bug;
799         Div (_) bug;
800         Rem (_) bug;
801         BitXor (_) bxor;
802         BitAnd (_) band;
803         BitOr (_) bor;
804         Shl (_) bug;
805         Shr (_) bug;
806
807         Eq (_) icmp(Equal);
808         Lt (_) icmp(UnsignedLessThan);
809         Le (_) icmp(UnsignedLessThanOrEqual);
810         Ne (_) icmp(NotEqual);
811         Ge (_) icmp(UnsignedGreaterThanOrEqual);
812         Gt (_) icmp(UnsignedGreaterThan);
813
814         Offset (_) bug;
815     };
816
817     res
818 }
819
820 pub fn trans_int_binop<'a, 'tcx: 'a>(
821     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
822     bin_op: BinOp,
823     lhs: CValue<'tcx>,
824     rhs: CValue<'tcx>,
825     out_ty: Ty<'tcx>,
826     signed: bool,
827 ) -> CValue<'tcx> {
828     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
829         assert_eq!(
830             lhs.layout().ty,
831             rhs.layout().ty,
832             "int binop requires lhs and rhs of same type"
833         );
834     }
835     binop_match! {
836         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
837         Add (_) iadd;
838         Sub (_) isub;
839         Mul (_) imul;
840         Div (false) udiv;
841         Div (true) sdiv;
842         Rem (false) urem;
843         Rem (true) srem;
844         BitXor (_) bxor;
845         BitAnd (_) band;
846         BitOr (_) bor;
847         Shl (_) ishl;
848         Shr (false) ushr;
849         Shr (true) sshr;
850
851         Eq (_) icmp(Equal);
852         Lt (false) icmp(UnsignedLessThan);
853         Lt (true) icmp(SignedLessThan);
854         Le (false) icmp(UnsignedLessThanOrEqual);
855         Le (true) icmp(SignedLessThanOrEqual);
856         Ne (_) icmp(NotEqual);
857         Ge (false) icmp(UnsignedGreaterThanOrEqual);
858         Ge (true) icmp(SignedGreaterThanOrEqual);
859         Gt (false) icmp(UnsignedGreaterThan);
860         Gt (true) icmp(SignedGreaterThan);
861
862         Offset (_) bug;
863     }
864 }
865
866 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
867     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
868     bin_op: BinOp,
869     in_lhs: CValue<'tcx>,
870     in_rhs: CValue<'tcx>,
871     out_ty: Ty<'tcx>,
872     signed: bool,
873 ) -> CValue<'tcx> {
874     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
875         assert_eq!(
876             in_lhs.layout().ty,
877             in_rhs.layout().ty,
878             "checked int binop requires lhs and rhs of same type"
879         );
880     }
881
882     let lhs = in_lhs.load_scalar(fx);
883     let rhs = in_rhs.load_scalar(fx);
884     let res = match bin_op {
885         BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
886         BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
887         BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
888         BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
889         BinOp::Shr => {
890             if !signed {
891                 fx.bcx.ins().ushr(lhs, rhs)
892             } else {
893                 fx.bcx.ins().sshr(lhs, rhs)
894             }
895         }
896         _ => bug!(
897             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
898             bin_op,
899             in_lhs,
900             in_rhs
901         ),
902     };
903
904     // TODO: check for overflow
905     let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
906
907     let out_place = CPlace::new_stack_slot(fx, out_ty);
908     let out_layout = out_place.layout();
909     out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
910
911     out_place.to_cvalue(fx)
912 }
913
914 fn trans_float_binop<'a, 'tcx: 'a>(
915     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
916     bin_op: BinOp,
917     lhs: CValue<'tcx>,
918     rhs: CValue<'tcx>,
919     ty: Ty<'tcx>,
920 ) -> CValue<'tcx> {
921     let res = binop_match! {
922         fx, bin_op, false, lhs, rhs, ty, "float";
923         Add (_) fadd;
924         Sub (_) fsub;
925         Mul (_) fmul;
926         Div (_) fdiv;
927         Rem (_) custom(|| {
928             assert_eq!(lhs.layout().ty, ty);
929             assert_eq!(rhs.layout().ty, ty);
930             match ty.sty {
931                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
932                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
933                 _ => bug!(),
934             }
935         });
936         BitXor (_) bxor;
937         BitAnd (_) band;
938         BitOr (_) bor;
939         Shl (_) bug;
940         Shr (_) bug;
941
942         Eq (_) fcmp(Equal);
943         Lt (_) fcmp(LessThan);
944         Le (_) fcmp(LessThanOrEqual);
945         Ne (_) fcmp(NotEqual);
946         Ge (_) fcmp(GreaterThanOrEqual);
947         Gt (_) fcmp(GreaterThan);
948
949         Offset (_) bug;
950     };
951
952     res
953 }
954
955 fn trans_char_binop<'a, 'tcx: 'a>(
956     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
957     bin_op: BinOp,
958     lhs: CValue<'tcx>,
959     rhs: CValue<'tcx>,
960     ty: Ty<'tcx>,
961 ) -> CValue<'tcx> {
962     let res = binop_match! {
963         fx, bin_op, false, lhs, rhs, ty, "char";
964         Add (_) bug;
965         Sub (_) bug;
966         Mul (_) bug;
967         Div (_) bug;
968         Rem (_) bug;
969         BitXor (_) bug;
970         BitAnd (_) bug;
971         BitOr (_) bug;
972         Shl (_) bug;
973         Shr (_) bug;
974
975         Eq (_) icmp(Equal);
976         Lt (_) icmp(UnsignedLessThan);
977         Le (_) icmp(UnsignedLessThanOrEqual);
978         Ne (_) icmp(NotEqual);
979         Ge (_) icmp(UnsignedGreaterThanOrEqual);
980         Gt (_) icmp(UnsignedGreaterThan);
981
982         Offset (_) bug;
983     };
984
985     res
986 }
987
988 fn trans_ptr_binop<'a, 'tcx: 'a>(
989     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
990     bin_op: BinOp,
991     lhs: CValue<'tcx>,
992     rhs: CValue<'tcx>,
993     ret_ty: Ty<'tcx>,
994 ) -> CValue<'tcx> {
995     match lhs.layout().ty.sty {
996         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
997             if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
998                 binop_match! {
999                     fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1000                     Add (_) bug;
1001                     Sub (_) bug;
1002                     Mul (_) bug;
1003                     Div (_) bug;
1004                     Rem (_) bug;
1005                     BitXor (_) bug;
1006                     BitAnd (_) bug;
1007                     BitOr (_) bug;
1008                     Shl (_) bug;
1009                     Shr (_) bug;
1010
1011                     Eq (_) icmp(Equal);
1012                     Lt (_) icmp(UnsignedLessThan);
1013                     Le (_) icmp(UnsignedLessThanOrEqual);
1014                     Ne (_) icmp(NotEqual);
1015                     Ge (_) icmp(UnsignedGreaterThanOrEqual);
1016                     Gt (_) icmp(UnsignedGreaterThan);
1017
1018                     Offset (_) iadd;
1019                 }
1020             } else {
1021                 let lhs = lhs.load_value_pair(fx).0;
1022                 let rhs = rhs.load_value_pair(fx).0;
1023                 let res = match bin_op {
1024                     BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1025                     BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1026                     _ => unimplemented!(
1027                         "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1028                         bin_op
1029                     ),
1030                 };
1031
1032                 assert_eq!(fx.tcx.types.bool, ret_ty);
1033                 let ret_layout = fx.layout_of(ret_ty);
1034                 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1035             }
1036         }
1037         _ => bug!("trans_ptr_binop on non ptr"),
1038     }
1039 }
1040
1041 pub fn trans_place<'a, 'tcx: 'a>(
1042     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1043     place: &Place<'tcx>,
1044 ) -> CPlace<'tcx> {
1045     match place {
1046         Place::Local(local) => fx.get_local_place(*local),
1047         Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1048         Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1049         Place::Projection(projection) => {
1050             let base = trans_place(fx, &projection.base);
1051             match projection.elem {
1052                 ProjectionElem::Deref => base.place_deref(fx),
1053                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1054                 ProjectionElem::Index(local) => {
1055                     let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1056                     base.place_index(fx, index)
1057                 }
1058                 ProjectionElem::ConstantIndex {
1059                     offset,
1060                     min_length: _,
1061                     from_end,
1062                 } => {
1063                     let index = if !from_end {
1064                         fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1065                     } else {
1066                         let len = codegen_array_len(fx, base);
1067                         fx.bcx.ins().iadd_imm(len, -(offset as i64))
1068                     };
1069                     base.place_index(fx, index)
1070                 }
1071                 ProjectionElem::Subslice { from, to } => unimpl!(
1072                     "projection subslice {:?} from {} to {}",
1073                     projection.base,
1074                     from,
1075                     to
1076                 ),
1077                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1078             }
1079         }
1080     }
1081 }
1082
1083 pub fn trans_operand<'a, 'tcx>(
1084     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1085     operand: &Operand<'tcx>,
1086 ) -> CValue<'tcx> {
1087     match operand {
1088         Operand::Move(place) | Operand::Copy(place) => {
1089             let cplace = trans_place(fx, place);
1090             cplace.to_cvalue(fx)
1091         }
1092         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1093     }
1094 }