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