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