]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Merge commit '35d9c6bf256968e1b40e0d554607928bdf9cebea' into sync_cg_clif-2022-02-23
[rust.git] / src / base.rs
1 //! Codegen of a single function
2
3 use rustc_ast::InlineAsmOptions;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiOf;
7
8 use indexmap::IndexSet;
9
10 use crate::constant::ConstantCx;
11 use crate::prelude::*;
12 use crate::pretty_clif::CommentWriter;
13
14 pub(crate) fn codegen_fn<'tcx>(
15     cx: &mut crate::CodegenCx<'tcx>,
16     module: &mut dyn Module,
17     instance: Instance<'tcx>,
18 ) {
19     let tcx = cx.tcx;
20
21     let _inst_guard =
22         crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
23     debug_assert!(!instance.substs.needs_infer());
24
25     let mir = tcx.instance_mir(instance.def);
26     let _mir_guard = crate::PrintOnPanic(|| {
27         let mut buf = Vec::new();
28         rustc_middle::mir::write_mir_pretty(tcx, Some(instance.def_id()), &mut buf).unwrap();
29         String::from_utf8_lossy(&buf).into_owned()
30     });
31
32     // Declare function
33     let symbol_name = tcx.symbol_name(instance);
34     let sig = get_function_sig(tcx, module.isa().triple(), instance);
35     let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
36
37     cx.cached_context.clear();
38
39     // Make the FunctionBuilder
40     let mut func_ctx = FunctionBuilderContext::new();
41     let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
42     func.name = ExternalName::user(0, func_id.as_u32());
43     func.signature = sig;
44     func.collect_debug_info();
45
46     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
47
48     // Predefine blocks
49     let start_block = bcx.create_block();
50     let block_map: IndexVec<BasicBlock, Block> =
51         (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
52
53     // Make FunctionCx
54     let target_config = module.target_config();
55     let pointer_type = target_config.pointer_type();
56     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
57
58     let mut fx = FunctionCx {
59         cx,
60         module,
61         tcx,
62         target_config,
63         pointer_type,
64         constants_cx: ConstantCx::new(),
65
66         instance,
67         symbol_name,
68         mir,
69         fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
70
71         bcx,
72         block_map,
73         local_map: IndexVec::with_capacity(mir.local_decls.len()),
74         caller_location: None, // set by `codegen_fn_prelude`
75
76         clif_comments,
77         source_info_set: indexmap::IndexSet::new(),
78         next_ssa_var: 0,
79     };
80
81     let arg_uninhabited = fx
82         .mir
83         .args_iter()
84         .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
85
86     if !crate::constant::check_constants(&mut fx) {
87         fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
88         fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
89         crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
90     } else if arg_uninhabited {
91         fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
92         fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
93         crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
94     } else {
95         tcx.sess.time("codegen clif ir", || {
96             tcx.sess
97                 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
98             codegen_fn_content(&mut fx);
99         });
100     }
101
102     // Recover all necessary data from fx, before accessing func will prevent future access to it.
103     let instance = fx.instance;
104     let clif_comments = fx.clif_comments;
105     let source_info_set = fx.source_info_set;
106     let local_map = fx.local_map;
107
108     fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
109
110     crate::pretty_clif::write_clif_file(
111         tcx,
112         "unopt",
113         module.isa(),
114         instance,
115         &func,
116         &clif_comments,
117     );
118
119     // Verify function
120     verify_func(tcx, &clif_comments, &func);
121
122     compile_fn(
123         cx,
124         module,
125         instance,
126         symbol_name.name,
127         func_id,
128         func,
129         clif_comments,
130         source_info_set,
131         local_map,
132     );
133 }
134
135 fn compile_fn<'tcx>(
136     cx: &mut crate::CodegenCx<'tcx>,
137     module: &mut dyn Module,
138     instance: Instance<'tcx>,
139     symbol_name: &str,
140     func_id: FuncId,
141     func: Function,
142     mut clif_comments: CommentWriter,
143     source_info_set: IndexSet<SourceInfo>,
144     local_map: IndexVec<mir::Local, CPlace<'tcx>>,
145 ) {
146     let tcx = cx.tcx;
147
148     // Store function in context
149     let context = &mut cx.cached_context;
150     context.clear();
151     context.func = func;
152
153     // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
154     // instruction, which doesn't have an encoding.
155     context.compute_cfg();
156     context.compute_domtree();
157     context.eliminate_unreachable_code(module.isa()).unwrap();
158     context.dce(module.isa()).unwrap();
159     // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
160     // invalidate it when it would change.
161     context.domtree.clear();
162
163     // Perform rust specific optimizations
164     tcx.sess.time("optimize clif ir", || {
165         crate::optimize::optimize_function(
166             tcx,
167             module.isa(),
168             instance,
169             context,
170             &mut clif_comments,
171         );
172     });
173
174     // Define function
175     tcx.sess.time("define function", || {
176         context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
177         module.define_function(func_id, context).unwrap()
178     });
179
180     // Write optimized function to file for debugging
181     crate::pretty_clif::write_clif_file(
182         tcx,
183         "opt",
184         module.isa(),
185         instance,
186         &context.func,
187         &clif_comments,
188     );
189
190     if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
191         crate::pretty_clif::write_ir_file(
192             tcx,
193             || format!("{}.vcode", tcx.symbol_name(instance).name),
194             |file| file.write_all(disasm.as_bytes()),
195         )
196     }
197
198     // Define debuginfo for function
199     let isa = module.isa();
200     let debug_context = &mut cx.debug_context;
201     let unwind_context = &mut cx.unwind_context;
202     tcx.sess.time("generate debug info", || {
203         if let Some(debug_context) = debug_context {
204             debug_context.define_function(
205                 instance,
206                 func_id,
207                 symbol_name,
208                 isa,
209                 context,
210                 &source_info_set,
211                 local_map,
212             );
213         }
214         unwind_context.add_function(func_id, &context, isa);
215     });
216 }
217
218 pub(crate) fn verify_func(
219     tcx: TyCtxt<'_>,
220     writer: &crate::pretty_clif::CommentWriter,
221     func: &Function,
222 ) {
223     tcx.sess.time("verify clif ir", || {
224         let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
225         match cranelift_codegen::verify_function(&func, &flags) {
226             Ok(_) => {}
227             Err(err) => {
228                 tcx.sess.err(&format!("{:?}", err));
229                 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
230                     &func,
231                     Some(Box::new(writer)),
232                     err,
233                 );
234                 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
235             }
236         }
237     });
238 }
239
240 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
241     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
242         let block = fx.get_block(bb);
243         fx.bcx.switch_to_block(block);
244
245         if bb_data.is_cleanup {
246             // Unwinding after panicking is not supported
247             continue;
248
249             // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
250             // so for cleanup blocks.
251         }
252
253         fx.bcx.ins().nop();
254         for stmt in &bb_data.statements {
255             fx.set_debug_loc(stmt.source_info);
256             codegen_stmt(fx, block, stmt);
257         }
258
259         if fx.clif_comments.enabled() {
260             let mut terminator_head = "\n".to_string();
261             bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
262             let inst = fx.bcx.func.layout.last_inst(block).unwrap();
263             fx.add_comment(inst, terminator_head);
264         }
265
266         let source_info = bb_data.terminator().source_info;
267         fx.set_debug_loc(source_info);
268
269         match &bb_data.terminator().kind {
270             TerminatorKind::Goto { target } => {
271                 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
272                     let mut can_immediately_return = true;
273                     for stmt in &fx.mir[*target].statements {
274                         if let StatementKind::StorageDead(_) = stmt.kind {
275                         } else {
276                             // FIXME Can sometimes happen, see rust-lang/rust#70531
277                             can_immediately_return = false;
278                             break;
279                         }
280                     }
281
282                     if can_immediately_return {
283                         crate::abi::codegen_return(fx);
284                         continue;
285                     }
286                 }
287
288                 let block = fx.get_block(*target);
289                 fx.bcx.ins().jump(block, &[]);
290             }
291             TerminatorKind::Return => {
292                 crate::abi::codegen_return(fx);
293             }
294             TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
295                 if !fx.tcx.sess.overflow_checks() {
296                     if let mir::AssertKind::OverflowNeg(_) = *msg {
297                         let target = fx.get_block(*target);
298                         fx.bcx.ins().jump(target, &[]);
299                         continue;
300                     }
301                 }
302                 let cond = codegen_operand(fx, cond).load_scalar(fx);
303
304                 let target = fx.get_block(*target);
305                 let failure = fx.bcx.create_block();
306                 // FIXME Mark failure block as cold once Cranelift supports it
307
308                 if *expected {
309                     fx.bcx.ins().brz(cond, failure, &[]);
310                 } else {
311                     fx.bcx.ins().brnz(cond, failure, &[]);
312                 };
313                 fx.bcx.ins().jump(target, &[]);
314
315                 fx.bcx.switch_to_block(failure);
316                 fx.bcx.ins().nop();
317
318                 match msg {
319                     AssertKind::BoundsCheck { ref len, ref index } => {
320                         let len = codegen_operand(fx, len).load_scalar(fx);
321                         let index = codegen_operand(fx, index).load_scalar(fx);
322                         let location = fx.get_caller_location(source_info.span).load_scalar(fx);
323
324                         codegen_panic_inner(
325                             fx,
326                             rustc_hir::LangItem::PanicBoundsCheck,
327                             &[index, len, location],
328                             source_info.span,
329                         );
330                     }
331                     _ => {
332                         let msg_str = msg.description();
333                         codegen_panic(fx, msg_str, source_info.span);
334                     }
335                 }
336             }
337
338             TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
339                 let discr = codegen_operand(fx, discr).load_scalar(fx);
340
341                 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
342                     || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
343                 if use_bool_opt {
344                     assert_eq!(targets.iter().count(), 1);
345                     let (then_value, then_block) = targets.iter().next().unwrap();
346                     let then_block = fx.get_block(then_block);
347                     let else_block = fx.get_block(targets.otherwise());
348                     let test_zero = match then_value {
349                         0 => true,
350                         1 => false,
351                         _ => unreachable!("{:?}", targets),
352                     };
353
354                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
355                     let (discr, is_inverted) =
356                         crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
357                     let test_zero = if is_inverted { !test_zero } else { test_zero };
358                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
359                     if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
360                         &fx.bcx, discr, test_zero,
361                     ) {
362                         if taken {
363                             fx.bcx.ins().jump(then_block, &[]);
364                         } else {
365                             fx.bcx.ins().jump(else_block, &[]);
366                         }
367                     } else {
368                         if test_zero {
369                             fx.bcx.ins().brz(discr, then_block, &[]);
370                             fx.bcx.ins().jump(else_block, &[]);
371                         } else {
372                             fx.bcx.ins().brnz(discr, then_block, &[]);
373                             fx.bcx.ins().jump(else_block, &[]);
374                         }
375                     }
376                 } else {
377                     let mut switch = ::cranelift_frontend::Switch::new();
378                     for (value, block) in targets.iter() {
379                         let block = fx.get_block(block);
380                         switch.set_entry(value, block);
381                     }
382                     let otherwise_block = fx.get_block(targets.otherwise());
383                     switch.emit(&mut fx.bcx, discr, otherwise_block);
384                 }
385             }
386             TerminatorKind::Call {
387                 func,
388                 args,
389                 destination,
390                 fn_span,
391                 cleanup: _,
392                 from_hir_call: _,
393             } => {
394                 fx.tcx.sess.time("codegen call", || {
395                     crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
396                 });
397             }
398             TerminatorKind::InlineAsm {
399                 template,
400                 operands,
401                 options,
402                 destination,
403                 line_spans: _,
404                 cleanup: _,
405             } => {
406                 if options.contains(InlineAsmOptions::MAY_UNWIND) {
407                     fx.tcx.sess.span_fatal(
408                         source_info.span,
409                         "cranelift doesn't support unwinding from inline assembly.",
410                     );
411                 }
412
413                 crate::inline_asm::codegen_inline_asm(
414                     fx,
415                     source_info.span,
416                     template,
417                     operands,
418                     *options,
419                 );
420
421                 match *destination {
422                     Some(destination) => {
423                         let destination_block = fx.get_block(destination);
424                         fx.bcx.ins().jump(destination_block, &[]);
425                     }
426                     None => {
427                         crate::trap::trap_unreachable(
428                             fx,
429                             "[corruption] Returned from noreturn inline asm",
430                         );
431                     }
432                 }
433             }
434             TerminatorKind::Resume | TerminatorKind::Abort => {
435                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
436             }
437             TerminatorKind::Unreachable => {
438                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
439             }
440             TerminatorKind::Yield { .. }
441             | TerminatorKind::FalseEdge { .. }
442             | TerminatorKind::FalseUnwind { .. }
443             | TerminatorKind::DropAndReplace { .. }
444             | TerminatorKind::GeneratorDrop => {
445                 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
446             }
447             TerminatorKind::Drop { place, target, unwind: _ } => {
448                 let drop_place = codegen_place(fx, *place);
449                 crate::abi::codegen_drop(fx, source_info.span, drop_place);
450
451                 let target_block = fx.get_block(*target);
452                 fx.bcx.ins().jump(target_block, &[]);
453             }
454         };
455     }
456
457     fx.bcx.seal_all_blocks();
458     fx.bcx.finalize();
459 }
460
461 fn codegen_stmt<'tcx>(
462     fx: &mut FunctionCx<'_, '_, 'tcx>,
463     #[allow(unused_variables)] cur_block: Block,
464     stmt: &Statement<'tcx>,
465 ) {
466     let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
467
468     fx.set_debug_loc(stmt.source_info);
469
470     #[cfg(disabled)]
471     match &stmt.kind {
472         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
473         _ => {
474             if fx.clif_comments.enabled() {
475                 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
476                 fx.add_comment(inst, format!("{:?}", stmt));
477             }
478         }
479     }
480
481     match &stmt.kind {
482         StatementKind::SetDiscriminant { place, variant_index } => {
483             let place = codegen_place(fx, **place);
484             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
485         }
486         StatementKind::Assign(to_place_and_rval) => {
487             let lval = codegen_place(fx, to_place_and_rval.0);
488             let dest_layout = lval.layout();
489             match to_place_and_rval.1 {
490                 Rvalue::Use(ref operand) => {
491                     let val = codegen_operand(fx, operand);
492                     lval.write_cvalue(fx, val);
493                 }
494                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
495                     let place = codegen_place(fx, place);
496                     let ref_ = place.place_ref(fx, lval.layout());
497                     lval.write_cvalue(fx, ref_);
498                 }
499                 Rvalue::ThreadLocalRef(def_id) => {
500                     let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
501                     lval.write_cvalue(fx, val);
502                 }
503                 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
504                     let lhs = codegen_operand(fx, &lhs_rhs.0);
505                     let rhs = codegen_operand(fx, &lhs_rhs.1);
506
507                     let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
508                     lval.write_cvalue(fx, res);
509                 }
510                 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
511                     let lhs = codegen_operand(fx, &lhs_rhs.0);
512                     let rhs = codegen_operand(fx, &lhs_rhs.1);
513
514                     let res = if !fx.tcx.sess.overflow_checks() {
515                         let val =
516                             crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
517                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
518                         CValue::by_val_pair(val, is_overflow, lval.layout())
519                     } else {
520                         crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
521                     };
522
523                     lval.write_cvalue(fx, res);
524                 }
525                 Rvalue::UnaryOp(un_op, ref operand) => {
526                     let operand = codegen_operand(fx, operand);
527                     let layout = operand.layout();
528                     let val = operand.load_scalar(fx);
529                     let res = match un_op {
530                         UnOp::Not => match layout.ty.kind() {
531                             ty::Bool => {
532                                 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
533                                 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
534                             }
535                             ty::Uint(_) | ty::Int(_) => {
536                                 CValue::by_val(fx.bcx.ins().bnot(val), layout)
537                             }
538                             _ => unreachable!("un op Not for {:?}", layout.ty),
539                         },
540                         UnOp::Neg => match layout.ty.kind() {
541                             ty::Int(IntTy::I128) => {
542                                 // FIXME remove this case once ineg.i128 works
543                                 let zero =
544                                     CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
545                                 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
546                             }
547                             ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
548                             ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
549                             _ => unreachable!("un op Neg for {:?}", layout.ty),
550                         },
551                     };
552                     lval.write_cvalue(fx, res);
553                 }
554                 Rvalue::Cast(
555                     CastKind::Pointer(PointerCast::ReifyFnPointer),
556                     ref operand,
557                     to_ty,
558                 ) => {
559                     let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
560                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
561                     match *from_ty.kind() {
562                         ty::FnDef(def_id, substs) => {
563                             let func_ref = fx.get_function_ref(
564                                 Instance::resolve_for_fn_ptr(
565                                     fx.tcx,
566                                     ParamEnv::reveal_all(),
567                                     def_id,
568                                     substs,
569                                 )
570                                 .unwrap()
571                                 .polymorphize(fx.tcx),
572                             );
573                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
574                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
575                         }
576                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
577                     }
578                 }
579                 Rvalue::Cast(
580                     CastKind::Pointer(PointerCast::UnsafeFnPointer),
581                     ref operand,
582                     to_ty,
583                 )
584                 | Rvalue::Cast(
585                     CastKind::Pointer(PointerCast::MutToConstPointer),
586                     ref operand,
587                     to_ty,
588                 )
589                 | Rvalue::Cast(
590                     CastKind::Pointer(PointerCast::ArrayToPointer),
591                     ref operand,
592                     to_ty,
593                 ) => {
594                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
595                     let operand = codegen_operand(fx, operand);
596                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
597                 }
598                 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
599                     let operand = codegen_operand(fx, operand);
600                     let from_ty = operand.layout().ty;
601                     let to_ty = fx.monomorphize(to_ty);
602
603                     fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
604                         ty.builtin_deref(true)
605                             .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
606                                 has_ptr_meta(fx.tcx, pointee_ty)
607                             })
608                             .unwrap_or(false)
609                     }
610
611                     if is_fat_ptr(fx, from_ty) {
612                         if is_fat_ptr(fx, to_ty) {
613                             // fat-ptr -> fat-ptr
614                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
615                         } else {
616                             // fat-ptr -> thin-ptr
617                             let (ptr, _extra) = operand.load_scalar_pair(fx);
618                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
619                         }
620                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
621                         // enum -> discriminant value
622                         assert!(adt_def.is_enum());
623                         match to_ty.kind() {
624                             ty::Uint(_) | ty::Int(_) => {}
625                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
626                         }
627                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
628
629                         let discriminant = crate::discriminant::codegen_get_discriminant(
630                             fx,
631                             operand,
632                             fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
633                         )
634                         .load_scalar(fx);
635
636                         let res = crate::cast::clif_intcast(
637                             fx,
638                             discriminant,
639                             to_clif_ty,
640                             to_ty.is_signed(),
641                         );
642                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
643                     } else {
644                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
645                         let from = operand.load_scalar(fx);
646
647                         let res = clif_int_or_float_cast(
648                             fx,
649                             from,
650                             type_sign(from_ty),
651                             to_clif_ty,
652                             type_sign(to_ty),
653                         );
654                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
655                     }
656                 }
657                 Rvalue::Cast(
658                     CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
659                     ref operand,
660                     _to_ty,
661                 ) => {
662                     let operand = codegen_operand(fx, operand);
663                     match *operand.layout().ty.kind() {
664                         ty::Closure(def_id, substs) => {
665                             let instance = Instance::resolve_closure(
666                                 fx.tcx,
667                                 def_id,
668                                 substs,
669                                 ty::ClosureKind::FnOnce,
670                             )
671                             .polymorphize(fx.tcx);
672                             let func_ref = fx.get_function_ref(instance);
673                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
674                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
675                         }
676                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
677                     }
678                 }
679                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
680                     let operand = codegen_operand(fx, operand);
681                     operand.unsize_value(fx, lval);
682                 }
683                 Rvalue::Discriminant(place) => {
684                     let place = codegen_place(fx, place);
685                     let value = place.to_cvalue(fx);
686                     let discr =
687                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
688                     lval.write_cvalue(fx, discr);
689                 }
690                 Rvalue::Repeat(ref operand, times) => {
691                     let operand = codegen_operand(fx, operand);
692                     let times = fx
693                         .monomorphize(times)
694                         .eval(fx.tcx, ParamEnv::reveal_all())
695                         .val()
696                         .try_to_bits(fx.tcx.data_layout.pointer_size)
697                         .unwrap();
698                     if operand.layout().size.bytes() == 0 {
699                         // Do nothing for ZST's
700                     } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
701                         let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
702                         // FIXME use emit_small_memset where possible
703                         let addr = lval.to_ptr().get_addr(fx);
704                         let val = operand.load_scalar(fx);
705                         fx.bcx.call_memset(fx.target_config, addr, val, times);
706                     } else {
707                         let loop_block = fx.bcx.create_block();
708                         let loop_block2 = fx.bcx.create_block();
709                         let done_block = fx.bcx.create_block();
710                         let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
711                         let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
712                         fx.bcx.ins().jump(loop_block, &[zero]);
713
714                         fx.bcx.switch_to_block(loop_block);
715                         let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
716                         fx.bcx.ins().brnz(done, done_block, &[]);
717                         fx.bcx.ins().jump(loop_block2, &[]);
718
719                         fx.bcx.switch_to_block(loop_block2);
720                         let to = lval.place_index(fx, index);
721                         to.write_cvalue(fx, operand);
722                         let index = fx.bcx.ins().iadd_imm(index, 1);
723                         fx.bcx.ins().jump(loop_block, &[index]);
724
725                         fx.bcx.switch_to_block(done_block);
726                         fx.bcx.ins().nop();
727                     }
728                 }
729                 Rvalue::Len(place) => {
730                     let place = codegen_place(fx, place);
731                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
732                     let len = codegen_array_len(fx, place);
733                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
734                 }
735                 Rvalue::ShallowInitBox(ref operand, content_ty) => {
736                     let content_ty = fx.monomorphize(content_ty);
737                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
738                     let operand = codegen_operand(fx, operand);
739                     let operand = operand.load_scalar(fx);
740                     lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
741                 }
742                 Rvalue::NullaryOp(null_op, ty) => {
743                     assert!(
744                         lval.layout()
745                             .ty
746                             .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
747                     );
748                     let layout = fx.layout_of(fx.monomorphize(ty));
749                     let val = match null_op {
750                         NullOp::SizeOf => layout.size.bytes(),
751                         NullOp::AlignOf => layout.align.abi.bytes(),
752                     };
753                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
754                     lval.write_cvalue(fx, val);
755                 }
756                 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
757                     AggregateKind::Array(_ty) => {
758                         for (i, operand) in operands.iter().enumerate() {
759                             let operand = codegen_operand(fx, operand);
760                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
761                             let to = lval.place_index(fx, index);
762                             to.write_cvalue(fx, operand);
763                         }
764                     }
765                     _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
766                 },
767             }
768         }
769         StatementKind::StorageLive(_)
770         | StatementKind::StorageDead(_)
771         | StatementKind::Nop
772         | StatementKind::FakeRead(..)
773         | StatementKind::Retag { .. }
774         | StatementKind::AscribeUserType(..) => {}
775
776         StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
777         StatementKind::CopyNonOverlapping(inner) => {
778             let dst = codegen_operand(fx, &inner.dst);
779             let pointee = dst
780                 .layout()
781                 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
782                 .expect("Expected pointer");
783             let dst = dst.load_scalar(fx);
784             let src = codegen_operand(fx, &inner.src).load_scalar(fx);
785             let count = codegen_operand(fx, &inner.count).load_scalar(fx);
786             let elem_size: u64 = pointee.size.bytes();
787             let bytes =
788                 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
789             fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
790         }
791     }
792 }
793
794 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
795     match *place.layout().ty.kind() {
796         ty::Array(_elem_ty, len) => {
797             let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
798             fx.bcx.ins().iconst(fx.pointer_type, len)
799         }
800         ty::Slice(_elem_ty) => {
801             place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
802         }
803         _ => bug!("Rvalue::Len({:?})", place),
804     }
805 }
806
807 pub(crate) fn codegen_place<'tcx>(
808     fx: &mut FunctionCx<'_, '_, 'tcx>,
809     place: Place<'tcx>,
810 ) -> CPlace<'tcx> {
811     let mut cplace = fx.get_local_place(place.local);
812
813     for elem in place.projection {
814         match elem {
815             PlaceElem::Deref => {
816                 cplace = cplace.place_deref(fx);
817             }
818             PlaceElem::Field(field, _ty) => {
819                 cplace = cplace.place_field(fx, field);
820             }
821             PlaceElem::Index(local) => {
822                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
823                 cplace = cplace.place_index(fx, index);
824             }
825             PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
826                 let offset: u64 = offset;
827                 let index = if !from_end {
828                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
829                 } else {
830                     let len = codegen_array_len(fx, cplace);
831                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
832                 };
833                 cplace = cplace.place_index(fx, index);
834             }
835             PlaceElem::Subslice { from, to, from_end } => {
836                 // These indices are generated by slice patterns.
837                 // slice[from:-to] in Python terms.
838
839                 let from: u64 = from;
840                 let to: u64 = to;
841
842                 match cplace.layout().ty.kind() {
843                     ty::Array(elem_ty, _len) => {
844                         assert!(!from_end, "array subslices are never `from_end`");
845                         let elem_layout = fx.layout_of(*elem_ty);
846                         let ptr = cplace.to_ptr();
847                         cplace = CPlace::for_ptr(
848                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
849                             fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
850                         );
851                     }
852                     ty::Slice(elem_ty) => {
853                         assert!(from_end, "slice subslices should be `from_end`");
854                         let elem_layout = fx.layout_of(*elem_ty);
855                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
856                         let len = len.unwrap();
857                         cplace = CPlace::for_ptr_with_extra(
858                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
859                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
860                             cplace.layout(),
861                         );
862                     }
863                     _ => unreachable!(),
864                 }
865             }
866             PlaceElem::Downcast(_adt_def, variant) => {
867                 cplace = cplace.downcast_variant(fx, variant);
868             }
869         }
870     }
871
872     cplace
873 }
874
875 pub(crate) fn codegen_operand<'tcx>(
876     fx: &mut FunctionCx<'_, '_, 'tcx>,
877     operand: &Operand<'tcx>,
878 ) -> CValue<'tcx> {
879     match operand {
880         Operand::Move(place) | Operand::Copy(place) => {
881             let cplace = codegen_place(fx, *place);
882             cplace.to_cvalue(fx)
883         }
884         Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
885     }
886 }
887
888 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
889     let location = fx.get_caller_location(span).load_scalar(fx);
890
891     let msg_ptr = fx.anonymous_str(msg_str);
892     let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
893     let args = [msg_ptr, msg_len, location];
894
895     codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
896 }
897
898 pub(crate) fn codegen_panic_inner<'tcx>(
899     fx: &mut FunctionCx<'_, '_, 'tcx>,
900     lang_item: rustc_hir::LangItem,
901     args: &[Value],
902     span: Span,
903 ) {
904     let def_id =
905         fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
906
907     let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
908     let symbol_name = fx.tcx.symbol_name(instance).name;
909
910     fx.lib_call(
911         &*symbol_name,
912         vec![
913             AbiParam::new(fx.pointer_type),
914             AbiParam::new(fx.pointer_type),
915             AbiParam::new(fx.pointer_type),
916         ],
917         vec![],
918         args,
919     );
920
921     crate::trap::trap_unreachable(fx, "panic lang item returned");
922 }