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