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