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