]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/base.rs
Rollup merge of #104864 - chenyukang:yukang/fix-104700-binding, r=estebank
[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.isa().triple(), 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 = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
394                     let (discr, is_inverted) =
395                         crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
396                     let test_zero = if is_inverted { !test_zero } else { test_zero };
397                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
398                     if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
399                         &fx.bcx, discr, test_zero,
400                     ) {
401                         if taken {
402                             fx.bcx.ins().jump(then_block, &[]);
403                         } else {
404                             fx.bcx.ins().jump(else_block, &[]);
405                         }
406                     } else {
407                         if test_zero {
408                             fx.bcx.ins().brz(discr, then_block, &[]);
409                             fx.bcx.ins().jump(else_block, &[]);
410                         } else {
411                             fx.bcx.ins().brnz(discr, then_block, &[]);
412                             fx.bcx.ins().jump(else_block, &[]);
413                         }
414                     }
415                 } else {
416                     let mut switch = ::cranelift_frontend::Switch::new();
417                     for (value, block) in targets.iter() {
418                         let block = fx.get_block(block);
419                         switch.set_entry(value, block);
420                     }
421                     let otherwise_block = fx.get_block(targets.otherwise());
422                     switch.emit(&mut fx.bcx, discr, otherwise_block);
423                 }
424             }
425             TerminatorKind::Call {
426                 func,
427                 args,
428                 destination,
429                 target,
430                 fn_span,
431                 cleanup: _,
432                 from_hir_call: _,
433             } => {
434                 fx.tcx.sess.time("codegen call", || {
435                     crate::abi::codegen_terminator_call(
436                         fx,
437                         mir::SourceInfo { span: *fn_span, ..source_info },
438                         func,
439                         args,
440                         *destination,
441                         *target,
442                     )
443                 });
444             }
445             TerminatorKind::InlineAsm {
446                 template,
447                 operands,
448                 options,
449                 destination,
450                 line_spans: _,
451                 cleanup: _,
452             } => {
453                 if options.contains(InlineAsmOptions::MAY_UNWIND) {
454                     fx.tcx.sess.span_fatal(
455                         source_info.span,
456                         "cranelift doesn't support unwinding from inline assembly.",
457                     );
458                 }
459
460                 crate::inline_asm::codegen_inline_asm(
461                     fx,
462                     source_info.span,
463                     template,
464                     operands,
465                     *options,
466                     *destination,
467                 );
468             }
469             TerminatorKind::Resume | TerminatorKind::Abort => {
470                 // FIXME implement unwinding
471                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
472             }
473             TerminatorKind::Unreachable => {
474                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
475             }
476             TerminatorKind::Yield { .. }
477             | TerminatorKind::FalseEdge { .. }
478             | TerminatorKind::FalseUnwind { .. }
479             | TerminatorKind::DropAndReplace { .. }
480             | TerminatorKind::GeneratorDrop => {
481                 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
482             }
483             TerminatorKind::Drop { place, target, unwind: _ } => {
484                 let drop_place = codegen_place(fx, *place);
485                 crate::abi::codegen_drop(fx, source_info, drop_place);
486
487                 let target_block = fx.get_block(*target);
488                 fx.bcx.ins().jump(target_block, &[]);
489             }
490         };
491     }
492
493     fx.bcx.seal_all_blocks();
494     fx.bcx.finalize();
495 }
496
497 fn codegen_stmt<'tcx>(
498     fx: &mut FunctionCx<'_, '_, 'tcx>,
499     #[allow(unused_variables)] cur_block: Block,
500     stmt: &Statement<'tcx>,
501 ) {
502     let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
503
504     fx.set_debug_loc(stmt.source_info);
505
506     #[cfg(any())] // This is never true
507     match &stmt.kind {
508         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
509         _ => {
510             if fx.clif_comments.enabled() {
511                 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
512                 fx.add_comment(inst, format!("{:?}", stmt));
513             }
514         }
515     }
516
517     match &stmt.kind {
518         StatementKind::SetDiscriminant { place, variant_index } => {
519             let place = codegen_place(fx, **place);
520             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
521         }
522         StatementKind::Assign(to_place_and_rval) => {
523             let lval = codegen_place(fx, to_place_and_rval.0);
524             let dest_layout = lval.layout();
525             match to_place_and_rval.1 {
526                 Rvalue::Use(ref operand) => {
527                     let val = codegen_operand(fx, operand);
528                     lval.write_cvalue(fx, val);
529                 }
530                 Rvalue::CopyForDeref(place) => {
531                     let cplace = codegen_place(fx, place);
532                     let val = cplace.to_cvalue(fx);
533                     lval.write_cvalue(fx, val)
534                 }
535                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
536                     let place = codegen_place(fx, place);
537                     let ref_ = place.place_ref(fx, lval.layout());
538                     lval.write_cvalue(fx, ref_);
539                 }
540                 Rvalue::ThreadLocalRef(def_id) => {
541                     let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
542                     lval.write_cvalue(fx, val);
543                 }
544                 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
545                     let lhs = codegen_operand(fx, &lhs_rhs.0);
546                     let rhs = codegen_operand(fx, &lhs_rhs.1);
547
548                     let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
549                     lval.write_cvalue(fx, res);
550                 }
551                 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
552                     let lhs = codegen_operand(fx, &lhs_rhs.0);
553                     let rhs = codegen_operand(fx, &lhs_rhs.1);
554
555                     let res = if !fx.tcx.sess.overflow_checks() {
556                         let val =
557                             crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
558                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
559                         CValue::by_val_pair(val, is_overflow, lval.layout())
560                     } else {
561                         crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
562                     };
563
564                     lval.write_cvalue(fx, res);
565                 }
566                 Rvalue::UnaryOp(un_op, ref operand) => {
567                     let operand = codegen_operand(fx, operand);
568                     let layout = operand.layout();
569                     let val = operand.load_scalar(fx);
570                     let res = match un_op {
571                         UnOp::Not => match layout.ty.kind() {
572                             ty::Bool => {
573                                 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
574                                 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
575                             }
576                             ty::Uint(_) | ty::Int(_) => {
577                                 CValue::by_val(fx.bcx.ins().bnot(val), layout)
578                             }
579                             _ => unreachable!("un op Not for {:?}", layout.ty),
580                         },
581                         UnOp::Neg => match layout.ty.kind() {
582                             ty::Int(IntTy::I128) => {
583                                 // FIXME remove this case once ineg.i128 works
584                                 let zero =
585                                     CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
586                                 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
587                             }
588                             ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
589                             ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
590                             _ => unreachable!("un op Neg for {:?}", layout.ty),
591                         },
592                     };
593                     lval.write_cvalue(fx, res);
594                 }
595                 Rvalue::Cast(
596                     CastKind::Pointer(PointerCast::ReifyFnPointer),
597                     ref operand,
598                     to_ty,
599                 ) => {
600                     let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
601                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
602                     match *from_ty.kind() {
603                         ty::FnDef(def_id, substs) => {
604                             let func_ref = fx.get_function_ref(
605                                 Instance::resolve_for_fn_ptr(
606                                     fx.tcx,
607                                     ParamEnv::reveal_all(),
608                                     def_id,
609                                     substs,
610                                 )
611                                 .unwrap()
612                                 .polymorphize(fx.tcx),
613                             );
614                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
615                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
616                         }
617                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
618                     }
619                 }
620                 Rvalue::Cast(
621                     CastKind::Pointer(PointerCast::UnsafeFnPointer),
622                     ref operand,
623                     to_ty,
624                 )
625                 | Rvalue::Cast(
626                     CastKind::Pointer(PointerCast::MutToConstPointer),
627                     ref operand,
628                     to_ty,
629                 )
630                 | Rvalue::Cast(
631                     CastKind::Pointer(PointerCast::ArrayToPointer),
632                     ref operand,
633                     to_ty,
634                 ) => {
635                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
636                     let operand = codegen_operand(fx, operand);
637                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
638                 }
639                 Rvalue::Cast(
640                     CastKind::IntToInt
641                     | CastKind::FloatToFloat
642                     | CastKind::FloatToInt
643                     | CastKind::IntToFloat
644                     | CastKind::FnPtrToPtr
645                     | CastKind::PtrToPtr
646                     | CastKind::PointerExposeAddress
647                     | CastKind::PointerFromExposedAddress,
648                     ref operand,
649                     to_ty,
650                 ) => {
651                     let operand = codegen_operand(fx, operand);
652                     let from_ty = operand.layout().ty;
653                     let to_ty = fx.monomorphize(to_ty);
654
655                     fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
656                         ty.builtin_deref(true)
657                             .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
658                                 has_ptr_meta(fx.tcx, pointee_ty)
659                             })
660                             .unwrap_or(false)
661                     }
662
663                     if is_fat_ptr(fx, from_ty) {
664                         if is_fat_ptr(fx, to_ty) {
665                             // fat-ptr -> fat-ptr
666                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
667                         } else {
668                             // fat-ptr -> thin-ptr
669                             let (ptr, _extra) = operand.load_scalar_pair(fx);
670                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
671                         }
672                     } else {
673                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
674                         let from = operand.load_scalar(fx);
675
676                         let res = clif_int_or_float_cast(
677                             fx,
678                             from,
679                             type_sign(from_ty),
680                             to_clif_ty,
681                             type_sign(to_ty),
682                         );
683                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
684                     }
685                 }
686                 Rvalue::Cast(
687                     CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
688                     ref operand,
689                     _to_ty,
690                 ) => {
691                     let operand = codegen_operand(fx, operand);
692                     match *operand.layout().ty.kind() {
693                         ty::Closure(def_id, substs) => {
694                             let instance = Instance::resolve_closure(
695                                 fx.tcx,
696                                 def_id,
697                                 substs,
698                                 ty::ClosureKind::FnOnce,
699                             )
700                             .expect("failed to normalize and resolve closure during codegen")
701                             .polymorphize(fx.tcx);
702                             let func_ref = fx.get_function_ref(instance);
703                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
704                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
705                         }
706                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
707                     }
708                 }
709                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
710                     let operand = codegen_operand(fx, operand);
711                     operand.unsize_value(fx, lval);
712                 }
713                 Rvalue::Cast(CastKind::DynStar, ref operand, _) => {
714                     let operand = codegen_operand(fx, operand);
715                     operand.coerce_dyn_star(fx, lval);
716                 }
717                 Rvalue::Discriminant(place) => {
718                     let place = codegen_place(fx, place);
719                     let value = place.to_cvalue(fx);
720                     crate::discriminant::codegen_get_discriminant(fx, lval, value, dest_layout);
721                 }
722                 Rvalue::Repeat(ref operand, times) => {
723                     let operand = codegen_operand(fx, operand);
724                     let times = fx
725                         .monomorphize(times)
726                         .eval(fx.tcx, ParamEnv::reveal_all())
727                         .kind()
728                         .try_to_bits(fx.tcx.data_layout.pointer_size)
729                         .unwrap();
730                     if operand.layout().size.bytes() == 0 {
731                         // Do nothing for ZST's
732                     } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
733                         let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
734                         // FIXME use emit_small_memset where possible
735                         let addr = lval.to_ptr().get_addr(fx);
736                         let val = operand.load_scalar(fx);
737                         fx.bcx.call_memset(fx.target_config, addr, val, times);
738                     } else {
739                         let loop_block = fx.bcx.create_block();
740                         let loop_block2 = fx.bcx.create_block();
741                         let done_block = fx.bcx.create_block();
742                         let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
743                         let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
744                         fx.bcx.ins().jump(loop_block, &[zero]);
745
746                         fx.bcx.switch_to_block(loop_block);
747                         let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
748                         fx.bcx.ins().brnz(done, done_block, &[]);
749                         fx.bcx.ins().jump(loop_block2, &[]);
750
751                         fx.bcx.switch_to_block(loop_block2);
752                         let to = lval.place_index(fx, index);
753                         to.write_cvalue(fx, operand);
754                         let index = fx.bcx.ins().iadd_imm(index, 1);
755                         fx.bcx.ins().jump(loop_block, &[index]);
756
757                         fx.bcx.switch_to_block(done_block);
758                         fx.bcx.ins().nop();
759                     }
760                 }
761                 Rvalue::Len(place) => {
762                     let place = codegen_place(fx, place);
763                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
764                     let len = codegen_array_len(fx, place);
765                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
766                 }
767                 Rvalue::ShallowInitBox(ref operand, content_ty) => {
768                     let content_ty = fx.monomorphize(content_ty);
769                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
770                     let operand = codegen_operand(fx, operand);
771                     let operand = operand.load_scalar(fx);
772                     lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
773                 }
774                 Rvalue::NullaryOp(null_op, ty) => {
775                     assert!(lval.layout().ty.is_sized(fx.tcx, ParamEnv::reveal_all()));
776                     let layout = fx.layout_of(fx.monomorphize(ty));
777                     let val = match null_op {
778                         NullOp::SizeOf => layout.size.bytes(),
779                         NullOp::AlignOf => layout.align.abi.bytes(),
780                     };
781                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
782                     lval.write_cvalue(fx, val);
783                 }
784                 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
785                     AggregateKind::Array(_ty) => {
786                         for (i, operand) in operands.iter().enumerate() {
787                             let operand = codegen_operand(fx, operand);
788                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
789                             let to = lval.place_index(fx, index);
790                             to.write_cvalue(fx, operand);
791                         }
792                     }
793                     _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
794                 },
795             }
796         }
797         StatementKind::StorageLive(_)
798         | StatementKind::StorageDead(_)
799         | StatementKind::Deinit(_)
800         | StatementKind::Nop
801         | StatementKind::FakeRead(..)
802         | StatementKind::Retag { .. }
803         | StatementKind::AscribeUserType(..) => {}
804
805         StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
806         StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
807             // We ignore `assume` intrinsics, they are only useful for optimizations
808             NonDivergingIntrinsic::Assume(_) => {}
809             NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
810                 src,
811                 dst,
812                 count,
813             }) => {
814                 let dst = codegen_operand(fx, dst);
815                 let pointee = dst
816                     .layout()
817                     .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
818                     .expect("Expected pointer");
819                 let dst = dst.load_scalar(fx);
820                 let src = codegen_operand(fx, src).load_scalar(fx);
821                 let count = codegen_operand(fx, count).load_scalar(fx);
822                 let elem_size: u64 = pointee.size.bytes();
823                 let bytes = if elem_size != 1 {
824                     fx.bcx.ins().imul_imm(count, elem_size as i64)
825                 } else {
826                     count
827                 };
828                 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
829             }
830         },
831     }
832 }
833
834 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
835     match *place.layout().ty.kind() {
836         ty::Array(_elem_ty, len) => {
837             let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
838             fx.bcx.ins().iconst(fx.pointer_type, len)
839         }
840         ty::Slice(_elem_ty) => {
841             place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
842         }
843         _ => bug!("Rvalue::Len({:?})", place),
844     }
845 }
846
847 pub(crate) fn codegen_place<'tcx>(
848     fx: &mut FunctionCx<'_, '_, 'tcx>,
849     place: Place<'tcx>,
850 ) -> CPlace<'tcx> {
851     let mut cplace = fx.get_local_place(place.local);
852
853     for elem in place.projection {
854         match elem {
855             PlaceElem::Deref => {
856                 cplace = cplace.place_deref(fx);
857             }
858             PlaceElem::OpaqueCast(ty) => cplace = cplace.place_opaque_cast(fx, ty),
859             PlaceElem::Field(field, _ty) => {
860                 cplace = cplace.place_field(fx, field);
861             }
862             PlaceElem::Index(local) => {
863                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
864                 cplace = cplace.place_index(fx, index);
865             }
866             PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
867                 let offset: u64 = offset;
868                 let index = if !from_end {
869                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
870                 } else {
871                     let len = codegen_array_len(fx, cplace);
872                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
873                 };
874                 cplace = cplace.place_index(fx, index);
875             }
876             PlaceElem::Subslice { from, to, from_end } => {
877                 // These indices are generated by slice patterns.
878                 // slice[from:-to] in Python terms.
879
880                 let from: u64 = from;
881                 let to: u64 = to;
882
883                 match cplace.layout().ty.kind() {
884                     ty::Array(elem_ty, _len) => {
885                         assert!(!from_end, "array subslices are never `from_end`");
886                         let elem_layout = fx.layout_of(*elem_ty);
887                         let ptr = cplace.to_ptr();
888                         cplace = CPlace::for_ptr(
889                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
890                             fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
891                         );
892                     }
893                     ty::Slice(elem_ty) => {
894                         assert!(from_end, "slice subslices should be `from_end`");
895                         let elem_layout = fx.layout_of(*elem_ty);
896                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
897                         let len = len.unwrap();
898                         cplace = CPlace::for_ptr_with_extra(
899                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
900                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
901                             cplace.layout(),
902                         );
903                     }
904                     _ => unreachable!(),
905                 }
906             }
907             PlaceElem::Downcast(_adt_def, variant) => {
908                 cplace = cplace.downcast_variant(fx, variant);
909             }
910         }
911     }
912
913     cplace
914 }
915
916 pub(crate) fn codegen_operand<'tcx>(
917     fx: &mut FunctionCx<'_, '_, 'tcx>,
918     operand: &Operand<'tcx>,
919 ) -> CValue<'tcx> {
920     match operand {
921         Operand::Move(place) | Operand::Copy(place) => {
922             let cplace = codegen_place(fx, *place);
923             cplace.to_cvalue(fx)
924         }
925         Operand::Constant(const_) => crate::constant::codegen_constant_operand(fx, const_),
926     }
927 }
928
929 pub(crate) fn codegen_panic<'tcx>(
930     fx: &mut FunctionCx<'_, '_, 'tcx>,
931     msg_str: &str,
932     source_info: mir::SourceInfo,
933 ) {
934     let location = fx.get_caller_location(source_info).load_scalar(fx);
935
936     let msg_ptr = fx.anonymous_str(msg_str);
937     let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
938     let args = [msg_ptr, msg_len, location];
939
940     codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
941 }
942
943 pub(crate) fn codegen_panic_inner<'tcx>(
944     fx: &mut FunctionCx<'_, '_, 'tcx>,
945     lang_item: rustc_hir::LangItem,
946     args: &[Value],
947     span: Span,
948 ) {
949     let def_id = fx
950         .tcx
951         .lang_items()
952         .require(lang_item)
953         .unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
954
955     let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
956     let symbol_name = fx.tcx.symbol_name(instance).name;
957
958     fx.lib_call(
959         &*symbol_name,
960         vec![
961             AbiParam::new(fx.pointer_type),
962             AbiParam::new(fx.pointer_type),
963             AbiParam::new(fx.pointer_type),
964         ],
965         vec![],
966         args,
967     );
968
969     fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
970 }