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