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