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