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