]> git.lizzy.rs Git - rust.git/blobdiff - src/base.rs
Implement isize -> raw-ptr cast
[rust.git] / src / base.rs
index cb4ed7900dd8559c6f25131921f2b8df8e098611..556e01aa3a2198855888cef7f86603d203b0b324 100644 (file)
 use crate::prelude::*;
 
-pub fn trans_mono_item<'a, 'tcx: 'a>(
-    cx: &mut CodegenCx<'a, 'tcx, CurrentBackend>,
-    context: &mut Context,
+struct PrintOnPanic<F: Fn() -> String>(F);
+impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
+    fn drop(&mut self) {
+        if ::std::thread::panicking() {
+            println!("{}", (self.0)());
+        }
+    }
+}
+
+pub fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
+    cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
     mono_item: MonoItem<'tcx>,
+    linkage: Linkage,
 ) {
     let tcx = cx.tcx;
-
     match mono_item {
-        MonoItem::Fn(inst) => match inst {
-            Instance {
-                def: InstanceDef::Item(def_id),
-                substs: _,
-            } => {
-                let mut mir = ::std::io::Cursor::new(Vec::new());
-                ::rustc_mir::util::write_mir_pretty(tcx, Some(def_id), &mut mir).unwrap();
-                tcx.sess.warn(&format!(
-                    "{:?}:\n\n{}",
-                    inst,
-                    String::from_utf8_lossy(&mir.into_inner())
-                ));
-
-                let (func_id, mut func) = cx.predefine_function(inst);
-
-                let comments = trans_fn(cx, &mut func, inst);
-
-                let mut writer = crate::pretty_clif::CommentWriter(comments);
-                let mut cton = String::new();
-                ::cranelift::codegen::write::decorate_function(&mut writer, &mut cton, &func, None)
-                    .unwrap();
-                tcx.sess.warn(&cton);
-
-                let flags = settings::Flags::new(settings::builder());
-                match ::cranelift::codegen::verify_function(&func, &flags) {
-                    Ok(_) => {}
-                    Err(err) => {
-                        tcx.sess.err(&format!("{:?}", err));
-                        let pretty_error =
-                            ::cranelift::codegen::print_errors::pretty_verifier_error(
-                                &func,
-                                None,
-                                Some(Box::new(writer)),
-                                &err,
-                            );
-                        tcx.sess
-                            .fatal(&format!("cretonne verify error:\n{}", pretty_error));
+        MonoItem::Fn(inst) => {
+            let _inst_guard =
+                PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
+            debug_assert!(!inst.substs.needs_infer());
+            let _mir_guard = PrintOnPanic(|| {
+                match inst.def {
+                    InstanceDef::Item(_)
+                    | InstanceDef::DropGlue(_, _)
+                    | InstanceDef::Virtual(_, _)
+                        if inst.def_id().krate == LOCAL_CRATE =>
+                    {
+                        let mut mir = ::std::io::Cursor::new(Vec::new());
+                        crate::rustc_mir::util::write_mir_pretty(
+                            tcx,
+                            Some(inst.def_id()),
+                            &mut mir,
+                        )
+                        .unwrap();
+                        String::from_utf8(mir.into_inner()).unwrap()
+                    }
+                    _ => {
+                        // FIXME fix write_mir_pretty for these instances
+                        format!("{:#?}", tcx.instance_mir(inst.def))
                     }
                 }
+            });
 
-                context.func = func;
-                // TODO: cranelift doesn't yet support some of the things needed
-                if cx
-                    .tcx
-                    .sess
-                    .crate_types
-                    .get()
-                    .contains(&CrateType::Executable)
-                {
-                    cx.module.define_function(func_id, context).unwrap();
-                    cx.defined_functions.push(func_id);
-                }
-
-                context.clear();
-            }
-            Instance {
-                def: InstanceDef::DropGlue(_, _),
-                substs: _,
-            } => unimpl!("Unimplemented drop glue instance"),
-            inst => unimpl!("Unimplemented instance {:?}", inst),
-        },
+            trans_fn(cx, inst, linkage);
+        }
         MonoItem::Static(def_id) => {
-            crate::constant::codegen_static(cx, def_id);
+            crate::constant::codegen_static(&mut cx.ccx, def_id);
         }
-        MonoItem::GlobalAsm(node_id) => cx
-            .tcx
+        MonoItem::GlobalAsm(node_id) => tcx
             .sess
             .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
     }
 }
 
-pub fn trans_fn<'a, 'tcx: 'a>(
-    cx: &mut CodegenCx<'a, 'tcx, CurrentBackend>,
-    f: &mut Function,
+fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
+    cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
     instance: Instance<'tcx>,
-) -> HashMap<Inst, String> {
-    let mir = cx.tcx.optimized_mir(instance.def_id());
+    linkage: Linkage,
+) {
+    let tcx = cx.tcx;
+
+    // Step 1. Get mir
+    let mir = tcx.instance_mir(instance.def);
+
+    // Step 2. Declare function
+    let (name, sig) = get_function_name_and_sig(tcx, instance, false);
+    let func_id = cx.module
+        .declare_function(&name, linkage, &sig)
+        .unwrap();
+    let mut debug_context = cx.debug_context.as_mut().map(|debug_context| FunctionDebugContext::new(
+        tcx,
+        debug_context,
+        mir,
+        &name,
+        &sig,
+    ));
+
+    // Step 3. Make FunctionBuilder
+    let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
     let mut func_ctx = FunctionBuilderContext::new();
-    let mut bcx: FunctionBuilder<Variable> = FunctionBuilder::new(f, &mut func_ctx);
+    let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
 
+    // Step 4. Predefine ebb's
     let start_ebb = bcx.create_ebb();
-    bcx.switch_to_block(start_ebb);
     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
         ebb_map.insert(bb, bcx.create_ebb());
     }
 
+    // Step 5. Make FunctionCx
+    let pointer_type = cx.module.target_config().pointer_type();
+    let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
+
     let mut fx = FunctionCx {
-        tcx: cx.tcx,
-        module: &mut cx.module,
+        tcx,
+        module: cx.module,
+        pointer_type,
+
         instance,
         mir,
+
         bcx,
-        param_substs: {
-            assert!(!instance.substs.needs_infer());
-            instance.substs
-        },
         ebb_map,
         local_map: HashMap::new(),
-        comments: HashMap::new(),
-        constants: &mut cx.constants,
+
+        clif_comments,
+        constants: &mut cx.ccx,
+        caches: &mut cx.caches,
+        source_info_set: indexmap::IndexSet::new(),
     };
-    let fx = &mut fx;
 
-    crate::abi::codegen_fn_prelude(fx, start_ebb);
+    // Step 6. Codegen function
+    with_unimpl_span(fx.mir.span, || {
+        crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
+        codegen_fn_content(&mut fx);
+    });
+    let source_info_set = fx.source_info_set.clone();
+
+    // Step 7. Write function to file for debugging
+    #[cfg(debug_assertions)]
+    fx.write_clif_file();
+
+    // Step 8. Verify function
+    verify_func(tcx, fx.clif_comments, &func);
+
+    // Step 9. Define function
+    cx.caches.context.func = func;
+    cx.module
+        .define_function_peek_compiled(func_id, &mut cx.caches.context, |size, context, isa| {
+            debug_context.as_mut().map(|x| x.define(tcx, size, context, isa, &source_info_set));
+        })
+        .unwrap();
+    //let module = &mut cx.module;
+    //let caches = &cx.caches;
+    cx.caches.context.clear();
+}
 
-    fx.bcx
-        .ins()
-        .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
+fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
+    let flags = settings::Flags::new(settings::builder());
+    match ::cranelift::codegen::verify_function(&func, &flags) {
+        Ok(_) => {}
+        Err(err) => {
+            tcx.sess.err(&format!("{:?}", err));
+            let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
+                &func,
+                None,
+                Some(Box::new(&writer)),
+                err,
+            );
+            tcx.sess
+                .fatal(&format!("cranelift verify error:\n{}", pretty_error));
+        }
+    }
+}
+
+fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
+    for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
+        if bb_data.is_cleanup {
+            // Unwinding after panicking is not supported
+            continue;
+        }
 
-    for (bb, bb_data) in mir.basic_blocks().iter_enumerated() {
         let ebb = fx.get_ebb(bb);
         fx.bcx.switch_to_block(ebb);
 
         fx.bcx.ins().nop();
         for stmt in &bb_data.statements {
+            fx.set_debug_loc(stmt.source_info);
             trans_stmt(fx, ebb, stmt);
         }
 
-        let mut terminator_head = "\n".to_string();
-        bb_data
-            .terminator()
-            .kind
-            .fmt_head(&mut terminator_head)
-            .unwrap();
-        let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
-        fx.add_comment(inst, terminator_head);
+        #[cfg(debug_assertions)]
+        {
+            let mut terminator_head = "\n".to_string();
+            bb_data
+                .terminator()
+                .kind
+                .fmt_head(&mut terminator_head)
+                .unwrap();
+            let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
+            fx.add_comment(inst, terminator_head);
+        }
+
+        fx.set_debug_loc(bb_data.terminator().source_info);
 
         match &bb_data.terminator().kind {
             TerminatorKind::Goto { target } => {
@@ -151,7 +200,7 @@ pub fn trans_fn<'a, 'tcx: 'a>(
                 target,
                 cleanup: _,
             } => {
-                let cond = trans_operand(fx, cond).load_value(fx);
+                let cond = trans_operand(fx, cond).load_scalar(fx);
                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
                 let cond = fx.bcx.ins().uextend(types::I32, cond);
                 let target = fx.get_ebb(*target);
@@ -160,7 +209,7 @@ pub fn trans_fn<'a, 'tcx: 'a>(
                 } else {
                     fx.bcx.ins().brz(cond, target, &[]);
                 };
-                fx.bcx.ins().trap(TrapCode::User(!0));
+                trap_panic(&mut fx.bcx);
             }
 
             TerminatorKind::SwitchInt {
@@ -169,60 +218,103 @@ pub fn trans_fn<'a, 'tcx: 'a>(
                 values,
                 targets,
             } => {
-                fx.bcx.ins().trap(TrapCode::User(0));
-                // TODO: prevent panics on large and negative disciminants
-                if false {
-                    let discr = trans_operand(fx, discr).load_value(fx);
-                    let mut jt_data = JumpTableData::new();
-                    for (i, value) in values.iter().enumerate() {
-                        let ebb = fx.get_ebb(targets[i]);
-                        jt_data.set_entry(*value as usize, ebb);
-                    }
-                    let jump_table = fx.bcx.create_jump_table(jt_data);
-                    fx.bcx.ins().br_table(discr, jump_table);
-                    let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
-                    fx.bcx.ins().jump(otherwise_ebb, &[]);
+                let discr = trans_operand(fx, discr).load_scalar(fx);
+                let mut switch = ::cranelift::frontend::Switch::new();
+                for (i, value) in values.iter().enumerate() {
+                    let ebb = fx.get_ebb(targets[i]);
+                    switch.set_entry(*value as u64, ebb);
                 }
+                let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
+                switch.emit(&mut fx.bcx, discr, otherwise_ebb);
             }
             TerminatorKind::Call {
                 func,
                 args,
                 destination,
                 cleanup: _,
+                from_hir_call: _,
             } => {
-                crate::abi::codegen_call(fx, func, args, destination);
+                crate::abi::codegen_terminator_call(fx, func, args, destination);
             }
             TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
-                fx.bcx.ins().trap(TrapCode::User(!0));
+                trap_unreachable(&mut fx.bcx);
             }
             TerminatorKind::Yield { .. }
             | TerminatorKind::FalseEdges { .. }
-            | TerminatorKind::FalseUnwind { .. } => {
+            | TerminatorKind::FalseUnwind { .. }
+            | TerminatorKind::DropAndReplace { .. }
+            | TerminatorKind::GeneratorDrop => {
                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
             }
-            TerminatorKind::Drop { target, .. } | TerminatorKind::DropAndReplace { target, .. } => {
-                // TODO call drop impl
-                // unimplemented!("terminator {:?}", bb_data.terminator());
+            TerminatorKind::Drop {
+                location,
+                target,
+                unwind: _,
+            } => {
+                let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
+                let ty = fx.monomorphize(&ty);
+                let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
+
+                if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
+                    // we don't actually need to drop anything
+                } else {
+                    let drop_place = trans_place(fx, location);
+                    let drop_fn_ty = drop_fn.ty(fx.tcx);
+                    match ty.sty {
+                        ty::Dynamic(..) => {
+                            crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
+                        }
+                        _ => {
+                            let arg_place = CPlace::new_stack_slot(
+                                fx,
+                                fx.tcx.mk_ref(
+                                    &ty::RegionKind::ReErased,
+                                    TypeAndMut {
+                                        ty,
+                                        mutbl: crate::rustc::hir::Mutability::MutMutable,
+                                    },
+                                ),
+                            );
+                            drop_place.write_place_ref(fx, arg_place);
+                            let arg_value = arg_place.to_cvalue(fx);
+                            crate::abi::codegen_call_inner(
+                                fx,
+                                None,
+                                drop_fn_ty,
+                                vec![arg_value],
+                                None,
+                            );
+                        }
+                    }
+                }
+
                 let target_ebb = fx.get_ebb(*target);
                 fx.bcx.ins().jump(target_ebb, &[]);
             }
-            TerminatorKind::GeneratorDrop => {
-                unimplemented!("terminator GeneratorDrop");
-            }
         };
     }
 
     fx.bcx.seal_all_blocks();
     fx.bcx.finalize();
-
-    fx.comments.clone()
 }
 
-fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &Statement<'tcx>) {
-    fx.tcx.sess.warn(&format!("stmt {:?}", stmt));
+fn trans_stmt<'a, 'tcx: 'a>(
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
+    cur_ebb: Ebb,
+    stmt: &Statement<'tcx>,
+) {
+    let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
 
-    let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
-    fx.add_comment(inst, format!("{:?}", stmt));
+    fx.set_debug_loc(stmt.source_info);
+
+    #[cfg(debug_assertions)]
+    match &stmt.kind {
+        StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
+        _ => {
+            let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
+            fx.add_comment(inst, format!("{:?}", stmt));
+        }
+    }
 
     match &stmt.kind {
         StatementKind::SetDiscriminant {
@@ -258,8 +350,9 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                     if *variant_index != dataful_variant {
                         let niche = place.place_field(fx, mir::Field::new(0));
                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
-                        let niche_value = ((variant_index - *niche_variants.start()) as u128)
-                            .wrapping_add(niche_start);
+                        let niche_value =
+                            ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
+                                .wrapping_add(niche_start);
                         // FIXME(eddyb) Check the actual primitive type here.
                         let niche_llval = if niche_value == 0 {
                             CValue::const_val(fx, niche.layout().ty, 0)
@@ -274,54 +367,46 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
         StatementKind::Assign(to_place, rval) => {
             let lval = trans_place(fx, to_place);
             let dest_layout = lval.layout();
-            match rval {
+            match &**rval {
                 Rvalue::Use(operand) => {
                     let val = trans_operand(fx, operand);
                     lval.write_cvalue(fx, val);
                 }
                 Rvalue::Ref(_, _, place) => {
                     let place = trans_place(fx, place);
-                    let addr = place.expect_addr();
-                    lval.write_cvalue(fx, CValue::ByVal(addr, dest_layout));
+                    place.write_place_ref(fx, lval);
                 }
                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
-                    let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
+                    let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
                     let lhs = trans_operand(fx, lhs);
                     let rhs = trans_operand(fx, rhs);
 
                     let res = match ty.sty {
-                        TypeVariants::TyBool => {
-                            trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
-                        }
-                        TypeVariants::TyUint(_) => {
+                        ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
+                        ty::Uint(_) => {
                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
                         }
-                        TypeVariants::TyInt(_) => {
+                        ty::Int(_) => {
                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
                         }
-                        TypeVariants::TyFloat(_) => {
-                            trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
-                        }
-                        TypeVariants::TyChar => {
-                            trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
-                        }
-                        TypeVariants::TyRawPtr(..) => {
-                            trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty)
-                        }
+                        ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
+                        ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
+                        ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
+                        ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
                     };
                     lval.write_cvalue(fx, res);
                 }
                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
-                    let ty = fx.monomorphize(&lhs.ty(&fx.mir.local_decls, fx.tcx));
+                    let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
                     let lhs = trans_operand(fx, lhs);
                     let rhs = trans_operand(fx, rhs);
 
                     let res = match ty.sty {
-                        TypeVariants::TyUint(_) => {
+                        ty::Uint(_) => {
                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
                         }
-                        TypeVariants::TyInt(_) => {
+                        ty::Int(_) => {
                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
                         }
                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
@@ -329,27 +414,45 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                     lval.write_cvalue(fx, res);
                 }
                 Rvalue::UnaryOp(un_op, operand) => {
-                    let ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
-                    let layout = fx.layout_of(ty);
-                    let val = trans_operand(fx, operand).load_value(fx);
+                    let operand = trans_operand(fx, operand);
+                    let layout = operand.layout();
+                    let val = operand.load_scalar(fx);
                     let res = match un_op {
-                        UnOp::Not => fx.bcx.ins().bnot(val),
-                        UnOp::Neg => match ty.sty {
-                            TypeVariants::TyInt(_) => {
-                                let clif_ty = fx.cton_type(ty).unwrap();
+                        UnOp::Not => {
+                            match layout.ty.sty {
+                                ty::Bool => {
+                                    let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
+                                    let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
+                                    fx.bcx.ins().bint(types::I8, res)
+                                }
+                                ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
+                                _ => unimplemented!("un op Not for {:?}", layout.ty),
+                            }
+                        }
+                        UnOp::Neg => match layout.ty.sty {
+                            ty::Int(_) => {
+                                let clif_ty = fx.clif_type(layout.ty).unwrap();
                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
                                 fx.bcx.ins().isub(zero, val)
                             }
-                            TypeVariants::TyFloat(_) => fx.bcx.ins().fneg(val),
-                            _ => unimplemented!("un op Neg for {:?}", ty),
+                            ty::Float(_) => fx.bcx.ins().fneg(val),
+                            _ => unimplemented!("un op Neg for {:?}", layout.ty),
                         },
                     };
                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
                 }
                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
-                    let operand = trans_operand(fx, operand);
                     let layout = fx.layout_of(ty);
-                    lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
+                    match fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx)).sty {
+                        ty::FnDef(def_id, substs) => {
+                            let func_ref = fx.get_function_ref(
+                                Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap(),
+                            );
+                            let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
+                            lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
+                        }
+                        _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
+                    }
                 }
                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
                     let operand = trans_operand(fx, operand);
@@ -360,39 +463,53 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                     let operand = trans_operand(fx, operand);
                     let from_ty = operand.layout().ty;
                     match (&from_ty.sty, &to_ty.sty) {
-                        (TypeVariants::TyRef(..), TypeVariants::TyRef(..))
-                        | (TypeVariants::TyRef(..), TypeVariants::TyRawPtr(..))
-                        | (TypeVariants::TyRawPtr(..), TypeVariants::TyRef(..))
-                        | (TypeVariants::TyRawPtr(..), TypeVariants::TyRawPtr(..)) => {
+                        (ty::Ref(..), ty::Ref(..))
+                        | (ty::Ref(..), ty::RawPtr(..))
+                        | (ty::RawPtr(..), ty::Ref(..))
+                        | (ty::RawPtr(..), ty::RawPtr(..))
+                        | (ty::FnPtr(..), ty::RawPtr(..)) => {
                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
                         }
-                        (TypeVariants::TyRawPtr(..), TypeVariants::TyUint(_))
-                        | (TypeVariants::TyFnPtr(..), TypeVariants::TyUint(_))
-                            if to_ty.sty == fx.tcx.types.usize.sty =>
+                        (ty::RawPtr(..), ty::Uint(_))
+                        | (ty::RawPtr(..), ty::Int(_))
+                        | (ty::FnPtr(..), ty::Uint(_))
+                            if to_ty.sty == fx.tcx.types.usize.sty
+                                || to_ty.sty == fx.tcx.types.isize.sty
+                                || fx.clif_type(to_ty).unwrap() == pointer_ty(fx.tcx) =>
                         {
                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
                         }
-                        (TypeVariants::TyUint(_), TypeVariants::TyRawPtr(..))
-                            if from_ty.sty == fx.tcx.types.usize.sty =>
-                        {
+                        (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
+                            lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
+                        }
+                        (ty::Int(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.isize.sty => {
                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
                         }
-                        (TypeVariants::TyChar, TypeVariants::TyUint(_))
-                        | (TypeVariants::TyUint(_), TypeVariants::TyChar)
-                        | (TypeVariants::TyUint(_), TypeVariants::TyInt(_))
-                        | (TypeVariants::TyUint(_), TypeVariants::TyUint(_)) => {
-                            let from = operand.load_value(fx);
-                            let res = crate::common::cton_intcast(fx, from, from_ty, to_ty, false);
+                        (ty::Char, ty::Uint(_))
+                        | (ty::Uint(_), ty::Char)
+                        | (ty::Uint(_), ty::Int(_))
+                        | (ty::Uint(_), ty::Uint(_)) => {
+                            let from = operand.load_scalar(fx);
+                            let res = crate::common::clif_intcast(
+                                fx,
+                                from,
+                                fx.clif_type(to_ty).unwrap(),
+                                false,
+                            );
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
-                        (TypeVariants::TyInt(_), TypeVariants::TyInt(_))
-                        | (TypeVariants::TyInt(_), TypeVariants::TyUint(_)) => {
-                            let from = operand.load_value(fx);
-                            let res = crate::common::cton_intcast(fx, from, from_ty, to_ty, true);
+                        (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
+                            let from = operand.load_scalar(fx);
+                            let res = crate::common::clif_intcast(
+                                fx,
+                                from,
+                                fx.clif_type(to_ty).unwrap(),
+                                true,
+                            );
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
-                        (TypeVariants::TyFloat(from_flt), TypeVariants::TyFloat(to_flt)) => {
-                            let from = operand.load_value(fx);
+                        (ty::Float(from_flt), ty::Float(to_flt)) => {
+                            let from = operand.load_scalar(fx);
                             let res = match (from_flt, to_flt) {
                                 (FloatTy::F32, FloatTy::F64) => {
                                     fx.bcx.ins().fpromote(types::F64, from)
@@ -404,22 +521,47 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                             };
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
-                        (TypeVariants::TyInt(_), TypeVariants::TyFloat(_)) => {
-                            let from = operand.load_value(fx);
-                            let f_type = fx.cton_type(to_ty).unwrap();
+                        (ty::Float(_), ty::Int(_)) => {
+                            let from = operand.load_scalar(fx);
+                            let i_type = fx.clif_type(to_ty).unwrap();
+                            let res = fx.bcx.ins().fcvt_to_sint_sat(i_type, from);
+                            lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
+                        }
+                        (ty::Float(_), ty::Uint(_)) => {
+                            let from = operand.load_scalar(fx);
+                            let i_type = fx.clif_type(to_ty).unwrap();
+                            let res = fx.bcx.ins().fcvt_to_uint_sat(i_type, from);
+                            lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
+                        }
+                        (ty::Int(_), ty::Float(_)) => {
+                            let from_ty = fx.clif_type(from_ty).unwrap();
+                            let from = operand.load_scalar(fx);
+                            // FIXME missing encoding for fcvt_from_sint.f32.i8
+                            let from = if from_ty == types::I8 || from_ty == types::I16 {
+                                fx.bcx.ins().sextend(types::I32, from)
+                            } else {
+                                from
+                            };
+                            let f_type = fx.clif_type(to_ty).unwrap();
                             let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
-                        (TypeVariants::TyUint(_), TypeVariants::TyFloat(_)) => {
-                            let from = operand.load_value(fx);
-                            let f_type = fx.cton_type(to_ty).unwrap();
+                        (ty::Uint(_), ty::Float(_)) => {
+                            let from_ty = fx.clif_type(from_ty).unwrap();
+                            let from = operand.load_scalar(fx);
+                            // FIXME missing encoding for fcvt_from_uint.f32.i8
+                            let from = if from_ty == types::I8 || from_ty == types::I16 {
+                                fx.bcx.ins().uextend(types::I32, from)
+                            } else {
+                                from
+                            };
+                            let f_type = fx.clif_type(to_ty).unwrap();
                             let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
-                        (TypeVariants::TyBool, TypeVariants::TyUint(_))
-                        | (TypeVariants::TyBool, TypeVariants::TyInt(_)) => {
-                            let to_ty = fx.cton_type(to_ty).unwrap();
-                            let from = operand.load_value(fx);
+                        (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
+                            let to_ty = fx.clif_type(to_ty).unwrap();
+                            let from = operand.load_scalar(fx);
                             let res = if to_ty != types::I8 {
                                 fx.bcx.ins().uextend(to_ty, from)
                             } else {
@@ -427,14 +569,19 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                             };
                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
                         }
+                        (ty::Adt(adt_def, _substs), ty::Uint(_)) | (ty::Adt(adt_def, _substs), ty::Int(_)) if adt_def.is_enum() => {
+                            let discr = trans_get_discriminant(fx, operand, fx.layout_of(to_ty));
+                            lval.write_cvalue(fx, discr);
+                        }
                         _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
                     }
                 }
                 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
                     unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
                 }
-                Rvalue::Cast(CastKind::Unsize, operand, ty) => {
-                    unimpl!("rval unsize {:?} {:?}", operand, ty);
+                Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
+                    let operand = trans_operand(fx, operand);
+                    operand.unsize_value(fx, lval);
                 }
                 Rvalue::Discriminant(place) => {
                     let place = trans_place(fx, place).to_cvalue(fx);
@@ -444,19 +591,49 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                 Rvalue::Repeat(operand, times) => {
                     let operand = trans_operand(fx, operand);
                     for i in 0..*times {
-                        let index = fx.bcx.ins().iconst(types::I64, i as i64);
+                        let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
                         let to = lval.place_index(fx, index);
                         to.write_cvalue(fx, operand);
                     }
                 }
-                Rvalue::Len(lval) => unimpl!("rval len {:?}", lval),
-                Rvalue::NullaryOp(NullOp::Box, ty) => unimplemented!("rval box {:?}", ty),
+                Rvalue::Len(place) => {
+                    let place = trans_place(fx, place);
+                    let usize_layout = fx.layout_of(fx.tcx.types.usize);
+                    let len = codegen_array_len(fx, place);
+                    lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
+                }
+                Rvalue::NullaryOp(NullOp::Box, content_ty) => {
+                    use rustc::middle::lang_items::ExchangeMallocFnLangItem;
+
+                    let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
+                    let layout = fx.layout_of(content_ty);
+                    let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
+                    let llalign = fx
+                        .bcx
+                        .ins()
+                        .iconst(usize_type, layout.align.abi.bytes() as i64);
+                    let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
+
+                    // Allocate space:
+                    let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
+                        Ok(id) => id,
+                        Err(s) => {
+                            fx.tcx
+                                .sess
+                                .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
+                        }
+                    };
+                    let instance = ty::Instance::mono(fx.tcx, def_id);
+                    let func_ref = fx.get_function_ref(instance);
+                    let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
+                    let ptr = fx.bcx.inst_results(call)[0];
+                    lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
+                }
                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
-                    assert!(
-                        lval.layout()
-                            .ty
-                            .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
-                    );
+                    assert!(lval
+                        .layout()
+                        .ty
+                        .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
                     let ty_size = fx.layout_of(ty).size.bytes();
                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
                     lval.write_cvalue(fx, val);
@@ -465,7 +642,7 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
                     AggregateKind::Array(_ty) => {
                         for (i, operand) in operands.into_iter().enumerate() {
                             let operand = trans_operand(fx, operand);
-                            let index = fx.bcx.ins().iconst(types::I64, i as i64);
+                            let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
                             let to = lval.place_index(fx, index);
                             to.write_cvalue(fx, operand);
                         }
@@ -477,30 +654,48 @@ fn trans_stmt<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, cur_ebb: Ebb, stmt: &
         StatementKind::StorageLive(_)
         | StatementKind::StorageDead(_)
         | StatementKind::Nop
-        | StatementKind::ReadForMatch(_)
-        | StatementKind::Validate(_, _)
-        | StatementKind::EndRegion(_)
-        | StatementKind::UserAssertTy(_, _) => {}
+        | StatementKind::FakeRead(..)
+        | StatementKind::Retag { .. }
+        | StatementKind::AscribeUserType(..) => {}
 
         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
     }
 }
 
+fn codegen_array_len<'a, 'tcx: 'a>(
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
+    place: CPlace<'tcx>,
+) -> Value {
+    match place.layout().ty.sty {
+        ty::Array(_elem_ty, len) => {
+            let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
+            fx.bcx.ins().iconst(fx.pointer_type, len)
+        }
+        ty::Slice(_elem_ty) => {
+            place.to_addr_maybe_unsized(fx).1.expect("Length metadata for slice place")
+        }
+        _ => bug!("Rvalue::Len({:?})", place),
+    }
+}
+
 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     value: CValue<'tcx>,
     dest_layout: TyLayout<'tcx>,
 ) -> CValue<'tcx> {
     let layout = value.layout();
 
     if layout.abi == layout::Abi::Uninhabited {
-        fx.bcx.ins().trap(TrapCode::User(!0));
+        trap_unreachable(&mut fx.bcx);
     }
     match layout.variants {
         layout::Variants::Single { index } => {
-            let discr_val = layout.ty.ty_adt_def().map_or(index as u128, |def| {
-                def.discriminant_for_variant(fx.tcx, index).val
-            });
+            let discr_val = layout
+                .ty
+                .ty_adt_def()
+                .map_or(index.as_u32() as u128, |def| {
+                    def.discriminant_for_variant(fx.tcx, index).val
+                });
             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
         }
         layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
@@ -508,7 +703,7 @@ pub fn trans_get_discriminant<'a, 'tcx: 'a>(
 
     let discr = value.value_field(fx, mir::Field::new(0));
     let discr_ty = discr.layout().ty;
-    let lldiscr = discr.load_value(fx);
+    let lldiscr = discr.load_scalar(fx);
     match layout.variants {
         layout::Variants::Single { .. } => bug!(),
         layout::Variants::Tagged { ref tag, .. } => {
@@ -516,7 +711,7 @@ pub fn trans_get_discriminant<'a, 'tcx: 'a>(
                 layout::Int(_, signed) => signed,
                 _ => false,
             };
-            let val = cton_intcast(fx, lldiscr, discr_ty, dest_layout.ty, signed);
+            let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
             return CValue::ByVal(val, dest_layout);
         }
         layout::Variants::NicheFilling {
@@ -525,8 +720,8 @@ pub fn trans_get_discriminant<'a, 'tcx: 'a>(
             niche_start,
             ..
         } => {
-            let niche_llty = fx.cton_type(discr_ty).unwrap();
-            let dest_cton_ty = fx.cton_type(dest_layout.ty).unwrap();
+            let niche_llty = fx.clif_type(discr_ty).unwrap();
+            let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
             if niche_variants.start() == niche_variants.end() {
                 let b = fx
                     .bcx
@@ -535,28 +730,29 @@ pub fn trans_get_discriminant<'a, 'tcx: 'a>(
                 let if_true = fx
                     .bcx
                     .ins()
-                    .iconst(dest_cton_ty, *niche_variants.start() as u64 as i64);
+                    .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
                 let if_false = fx
                     .bcx
                     .ins()
-                    .iconst(dest_cton_ty, dataful_variant as u64 as i64);
+                    .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
                 let val = fx.bcx.ins().select(b, if_true, if_false);
                 return CValue::ByVal(val, dest_layout);
             } else {
                 // Rebase from niche values to discriminant values.
-                let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
+                let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
                 let b = fx.bcx.ins().icmp_imm(
                     IntCC::UnsignedLessThanOrEqual,
                     lldiscr,
-                    *niche_variants.end() as u64 as i64,
+                    niche_variants.end().as_u32() as i64,
                 );
-                let if_true = cton_intcast(fx, lldiscr, discr_ty, dest_layout.ty, false);
+                let if_true =
+                    clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
                 let if_false = fx
                     .bcx
                     .ins()
-                    .iconst(dest_cton_ty, dataful_variant as u64 as i64);
+                    .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
                 let val = fx.bcx.ins().select(b, if_true, if_false);
                 return CValue::ByVal(val, dest_layout);
             }
@@ -565,25 +761,26 @@ pub fn trans_get_discriminant<'a, 'tcx: 'a>(
 }
 
 macro_rules! binop_match {
-    (@single $fx:expr, $bug_fmt:expr, $var:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
+    (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
     };
-    (@single $fx:expr, $bug_fmt:expr, $var:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
+    (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
         assert_eq!($fx.tcx.types.bool, $ret_ty);
         let ret_layout = $fx.layout_of($ret_ty);
+
         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
     }};
-    (@single $fx:expr, $bug_fmt:expr, $var:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
+    (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
         assert_eq!($fx.tcx.types.bool, $ret_ty);
         let ret_layout = $fx.layout_of($ret_ty);
         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
     }};
-    (@single $fx:expr, $bug_fmt:expr, $var:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
+    (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
         $body
     }};
-    (@single $fx:expr, $bug_fmt:expr, $var:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
+    (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
         let ret_layout = $fx.layout_of($ret_ty);
         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
     }};
@@ -593,18 +790,18 @@ macro_rules! binop_match {
             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
         )*
     ) => {{
-        let lhs = $lhs.load_value($fx);
-        let rhs = $rhs.load_value($fx);
+        let lhs = $lhs.load_scalar($fx);
+        let rhs = $rhs.load_scalar($fx);
         match ($bin_op, $signed) {
             $(
-                (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
+                (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
             )*
         }
     }}
 }
 
 fn trans_bool_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
     lhs: CValue<'tcx>,
     rhs: CValue<'tcx>,
@@ -637,7 +834,7 @@ fn trans_bool_binop<'a, 'tcx: 'a>(
 }
 
 pub fn trans_int_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
     lhs: CValue<'tcx>,
     rhs: CValue<'tcx>,
@@ -683,69 +880,55 @@ pub fn trans_int_binop<'a, 'tcx: 'a>(
 }
 
 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
-    lhs: CValue<'tcx>,
-    rhs: CValue<'tcx>,
+    in_lhs: CValue<'tcx>,
+    in_rhs: CValue<'tcx>,
     out_ty: Ty<'tcx>,
     signed: bool,
 ) -> CValue<'tcx> {
     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
         assert_eq!(
-            lhs.layout().ty,
-            rhs.layout().ty,
+            in_lhs.layout().ty,
+            in_rhs.layout().ty,
             "checked int binop requires lhs and rhs of same type"
         );
     }
-    let res_ty = match out_ty.sty {
-        TypeVariants::TyTuple(tys) => tys[0],
+
+    let lhs = in_lhs.load_scalar(fx);
+    let rhs = in_rhs.load_scalar(fx);
+    let res = match bin_op {
+        BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
+        BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
+        BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
+        BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
+        BinOp::Shr => {
+            if !signed {
+                fx.bcx.ins().ushr(lhs, rhs)
+            } else {
+                fx.bcx.ins().sshr(lhs, rhs)
+            }
+        }
         _ => bug!(
-            "Checked int binop requires tuple as output, but got {:?}",
-            out_ty
+            "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
+            bin_op,
+            in_lhs,
+            in_rhs
         ),
     };
 
-    let res = binop_match! {
-        fx, bin_op, signed, lhs, rhs, res_ty, "checked int/uint";
-        Add (_) iadd;
-        Sub (_) isub;
-        Mul (_) imul;
-        Div (_) bug;
-        Rem (_) bug;
-        BitXor (_) bug;
-        BitAnd (_) bug;
-        BitOr (_) bug;
-        Shl (_) ishl;
-        Shr (false) ushr;
-        Shr (true) sshr;
-
-        Eq (_) bug;
-        Lt (_) bug;
-        Le (_) bug;
-        Ne (_) bug;
-        Ge (_) bug;
-        Gt (_) bug;
-
-        Offset (_) bug;
-    };
-
     // TODO: check for overflow
-    let has_overflow = CValue::const_val(fx, fx.tcx.types.bool, 0);
+    let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
 
-    let out_place = CPlace::temp(fx, out_ty);
-    out_place
-        .place_field(fx, mir::Field::new(0))
-        .write_cvalue(fx, res);
-    println!("abc");
-    out_place
-        .place_field(fx, mir::Field::new(1))
-        .write_cvalue(fx, has_overflow);
+    let out_place = CPlace::new_stack_slot(fx, out_ty);
+    let out_layout = out_place.layout();
+    out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
 
     out_place.to_cvalue(fx)
 }
 
 fn trans_float_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
     lhs: CValue<'tcx>,
     rhs: CValue<'tcx>,
@@ -761,8 +944,8 @@ fn trans_float_binop<'a, 'tcx: 'a>(
             assert_eq!(lhs.layout().ty, ty);
             assert_eq!(rhs.layout().ty, ty);
             match ty.sty {
-                TypeVariants::TyFloat(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
-                TypeVariants::TyFloat(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
+                ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
+                ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
                 _ => bug!(),
             }
         });
@@ -786,7 +969,7 @@ fn trans_float_binop<'a, 'tcx: 'a>(
 }
 
 fn trans_char_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
     lhs: CValue<'tcx>,
     rhs: CValue<'tcx>,
@@ -819,46 +1002,78 @@ fn trans_char_binop<'a, 'tcx: 'a>(
 }
 
 fn trans_ptr_binop<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     bin_op: BinOp,
     lhs: CValue<'tcx>,
     rhs: CValue<'tcx>,
-    ty: Ty<'tcx>,
+    ret_ty: Ty<'tcx>,
 ) -> CValue<'tcx> {
-    match lhs.layout().ty.sty {
-        TypeVariants::TyRawPtr(TypeAndMut { ty, mutbl: _ }) => {
-            if !ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
-                unimpl!("Unsized values are not yet implemented");
-            }
-        }
+    let not_fat = match lhs.layout().ty.sty {
+        ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()),
+        ty::FnPtr(..) => true,
         _ => bug!("trans_ptr_binop on non ptr"),
-    }
-    binop_match! {
-        fx, bin_op, false, lhs, rhs, ty, "ptr";
-        Add (_) bug;
-        Sub (_) bug;
-        Mul (_) bug;
-        Div (_) bug;
-        Rem (_) bug;
-        BitXor (_) bug;
-        BitAnd (_) bug;
-        BitOr (_) bug;
-        Shl (_) bug;
-        Shr (_) bug;
+    };
+    if not_fat {
+        if let BinOp::Offset = bin_op {
+            let (base, offset) = (lhs, rhs.load_scalar(fx));
+            let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
+            let pointee_size = fx.layout_of(pointee_ty).size.bytes();
+            let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
+            let base_val = base.load_scalar(fx);
+            let res = fx.bcx.ins().iadd(base_val, ptr_diff);
+            return CValue::ByVal(res, base.layout());
+        }
 
-        Eq (_) icmp(Equal);
-        Lt (_) icmp(UnsignedLessThan);
-        Le (_) icmp(UnsignedLessThanOrEqual);
-        Ne (_) icmp(NotEqual);
-        Ge (_) icmp(UnsignedGreaterThanOrEqual);
-        Gt (_) icmp(UnsignedGreaterThan);
+        binop_match! {
+            fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
+            Add (_) bug;
+            Sub (_) bug;
+            Mul (_) bug;
+            Div (_) bug;
+            Rem (_) bug;
+            BitXor (_) bug;
+            BitAnd (_) bug;
+            BitOr (_) bug;
+            Shl (_) bug;
+            Shr (_) bug;
+
+            Eq (_) icmp(Equal);
+            Lt (_) icmp(UnsignedLessThan);
+            Le (_) icmp(UnsignedLessThanOrEqual);
+            Ne (_) icmp(NotEqual);
+            Ge (_) icmp(UnsignedGreaterThanOrEqual);
+            Gt (_) icmp(UnsignedGreaterThan);
 
-        Offset (_) iadd;
+            Offset (_) bug; // Handled above
+        }
+    } else {
+        let (lhs_ptr, lhs_extra) = lhs.load_value_pair(fx);
+        let (rhs_ptr, rhs_extra) = rhs.load_value_pair(fx);
+        let res = match bin_op {
+            BinOp::Eq => {
+                let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
+                let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
+                fx.bcx.ins().band(ptr_eq, extra_eq)
+            }
+            BinOp::Ne => {
+                let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
+                let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
+                fx.bcx.ins().bor(ptr_ne, extra_ne)
+            }
+            _ => unimplemented!(
+                "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
+                bin_op
+            ),
+        };
+
+        assert_eq!(fx.tcx.types.bool, ret_ty);
+        let ret_layout = fx.layout_of(ret_ty);
+        CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
     }
 }
 
 pub fn trans_place<'a, 'tcx: 'a>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     place: &Place<'tcx>,
 ) -> CPlace<'tcx> {
     match place {
@@ -868,37 +1083,26 @@ pub fn trans_place<'a, 'tcx: 'a>(
         Place::Projection(projection) => {
             let base = trans_place(fx, &projection.base);
             match projection.elem {
-                ProjectionElem::Deref => {
-                    let layout = fx.layout_of(place.ty(&*fx.mir, fx.tcx).to_ty(fx.tcx));
-                    if layout.is_unsized() {
-                        unimpl!("Unsized places are not yet implemented");
-                    }
-                    CPlace::Addr(base.to_cvalue(fx).load_value(fx), layout)
-                }
+                ProjectionElem::Deref => base.place_deref(fx),
                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
                 ProjectionElem::Index(local) => {
-                    let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
+                    let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
                     base.place_index(fx, index)
                 }
                 ProjectionElem::ConstantIndex {
                     offset,
                     min_length: _,
-                    from_end: false,
-                } => unimplemented!(
-                    "projection const index {:?} offset {:?} not from end",
-                    projection.base,
-                    offset
-                ),
-                ProjectionElem::ConstantIndex {
-                    offset,
-                    min_length: _,
-                    from_end: true,
-                } => unimplemented!(
-                    "projection const index {:?} offset {:?} from end",
-                    projection.base,
-                    offset
-                ),
-                ProjectionElem::Subslice { from, to } => unimplemented!(
+                    from_end,
+                } => {
+                    let index = if !from_end {
+                        fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
+                    } else {
+                        let len = codegen_array_len(fx, base);
+                        fx.bcx.ins().iadd_imm(len, -(offset as i64))
+                    };
+                    base.place_index(fx, index)
+                }
+                ProjectionElem::Subslice { from, to } => unimpl!(
                     "projection subslice {:?} from {} to {}",
                     projection.base,
                     from,
@@ -911,7 +1115,7 @@ pub fn trans_place<'a, 'tcx: 'a>(
 }
 
 pub fn trans_operand<'a, 'tcx>(
-    fx: &mut FunctionCx<'a, 'tcx>,
+    fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
     operand: &Operand<'tcx>,
 ) -> CValue<'tcx> {
     match operand {