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