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