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