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