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