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