]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Merge pull request #1070 from bjorn3/cpuid
[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).polymorphize(fx.tcx);
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                                     .polymorphize(fx.tcx),
474                             );
475                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
476                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
477                         }
478                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
479                     }
480                 }
481                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
482                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
483                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
484                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
485                     let operand = trans_operand(fx, operand);
486                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
487                 }
488                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
489                     let operand = trans_operand(fx, operand);
490                     let from_ty = operand.layout().ty;
491                     let to_ty = fx.monomorphize(to_ty);
492
493                     fn is_fat_ptr<'tcx>(
494                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
495                         ty: Ty<'tcx>,
496                     ) -> bool {
497                         ty.builtin_deref(true)
498                             .map(
499                                 |ty::TypeAndMut {
500                                      ty: pointee_ty,
501                                      mutbl: _,
502                                  }| has_ptr_meta(fx.tcx, pointee_ty),
503                             )
504                             .unwrap_or(false)
505                     }
506
507                     if is_fat_ptr(fx, from_ty) {
508                         if is_fat_ptr(fx, to_ty) {
509                             // fat-ptr -> fat-ptr
510                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
511                         } else {
512                             // fat-ptr -> thin-ptr
513                             let (ptr, _extra) = operand.load_scalar_pair(fx);
514                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
515                         }
516                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
517                         // enum -> discriminant value
518                         assert!(adt_def.is_enum());
519                         match to_ty.kind {
520                             ty::Uint(_) | ty::Int(_) => {}
521                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
522                         }
523
524                         use rustc_target::abi::{TagEncoding, Int, Variants};
525
526                         match &operand.layout().variants {
527                             Variants::Single { index } => {
528                                 let discr = operand.layout().ty.discriminant_for_variant(fx.tcx, *index).unwrap();
529                                 let discr = if discr.ty.is_signed() {
530                                     rustc_middle::mir::interpret::sign_extend(discr.val, fx.layout_of(discr.ty).size)
531                                 } else {
532                                     discr.val
533                                 };
534
535                                 let discr = CValue::const_val(fx, fx.layout_of(to_ty), discr);
536                                 lval.write_cvalue(fx, discr);
537                             }
538                             Variants::Multiple {
539                                 tag,
540                                 tag_field,
541                                 tag_encoding: TagEncoding::Direct,
542                                 variants: _,
543                             } => {
544                                 let cast_to = fx.clif_type(dest_layout.ty).unwrap();
545
546                                 // Read the tag/niche-encoded discriminant from memory.
547                                 let encoded_discr = operand.value_field(fx, mir::Field::new(*tag_field));
548                                 let encoded_discr = encoded_discr.load_scalar(fx);
549
550                                 // Decode the discriminant (specifically if it's niche-encoded).
551                                 let signed = match tag.value {
552                                     Int(_, signed) => signed,
553                                     _ => false,
554                                 };
555                                 let val = clif_intcast(fx, encoded_discr, cast_to, signed);
556                                 let val = CValue::by_val(val, dest_layout);
557                                 lval.write_cvalue(fx, val);
558                             }
559                             Variants::Multiple { ..} => unreachable!(),
560                         }
561                     } else {
562                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
563                         let from = operand.load_scalar(fx);
564
565                         let res = clif_int_or_float_cast(
566                             fx,
567                             from,
568                             type_sign(from_ty),
569                             to_clif_ty,
570                             type_sign(to_ty),
571                         );
572                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
573                     }
574                 }
575                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
576                     let operand = trans_operand(fx, operand);
577                     match operand.layout().ty.kind {
578                         ty::Closure(def_id, substs) => {
579                             let instance = Instance::resolve_closure(
580                                 fx.tcx,
581                                 def_id,
582                                 substs,
583                                 ty::ClosureKind::FnOnce,
584                             ).polymorphize(fx.tcx);
585                             let func_ref = fx.get_function_ref(instance);
586                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
587                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
588                         }
589                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
590                     }
591                 }
592                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
593                     let operand = trans_operand(fx, operand);
594                     operand.unsize_value(fx, lval);
595                 }
596                 Rvalue::Discriminant(place) => {
597                     let place = trans_place(fx, *place);
598                     let value = place.to_cvalue(fx);
599                     let discr =
600                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
601                     lval.write_cvalue(fx, discr);
602                 }
603                 Rvalue::Repeat(operand, times) => {
604                     let operand = trans_operand(fx, operand);
605                     let times = fx
606                         .monomorphize(times)
607                         .eval(fx.tcx, ParamEnv::reveal_all())
608                         .val
609                         .try_to_bits(fx.tcx.data_layout.pointer_size)
610                         .unwrap();
611                     for i in 0..times {
612                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
613                         let to = lval.place_index(fx, index);
614                         to.write_cvalue(fx, operand);
615                     }
616                 }
617                 Rvalue::Len(place) => {
618                     let place = trans_place(fx, *place);
619                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
620                     let len = codegen_array_len(fx, place);
621                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
622                 }
623                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
624                     use rustc_hir::lang_items::ExchangeMallocFnLangItem;
625
626                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
627                     let content_ty = fx.monomorphize(content_ty);
628                     let layout = fx.layout_of(content_ty);
629                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
630                     let llalign = fx
631                         .bcx
632                         .ins()
633                         .iconst(usize_type, layout.align.abi.bytes() as i64);
634                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
635
636                     // Allocate space:
637                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
638                         Ok(id) => id,
639                         Err(s) => {
640                             fx.tcx
641                                 .sess
642                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
643                         }
644                     };
645                     let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
646                     let func_ref = fx.get_function_ref(instance);
647                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
648                     let ptr = fx.bcx.inst_results(call)[0];
649                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
650                 }
651                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
652                     assert!(lval
653                         .layout()
654                         .ty
655                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
656                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
657                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
658                     lval.write_cvalue(fx, val);
659                 }
660                 Rvalue::Aggregate(kind, operands) => match **kind {
661                     AggregateKind::Array(_ty) => {
662                         for (i, operand) in operands.into_iter().enumerate() {
663                             let operand = trans_operand(fx, operand);
664                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
665                             let to = lval.place_index(fx, index);
666                             to.write_cvalue(fx, operand);
667                         }
668                     }
669                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
670                 },
671             }
672         }
673         StatementKind::StorageLive(_)
674         | StatementKind::StorageDead(_)
675         | StatementKind::Nop
676         | StatementKind::FakeRead(..)
677         | StatementKind::Retag { .. }
678         | StatementKind::AscribeUserType(..) => {}
679
680         StatementKind::LlvmInlineAsm(asm) => {
681             use rustc_span::symbol::Symbol;
682             let LlvmInlineAsm {
683                 asm,
684                 outputs,
685                 inputs,
686             } = &**asm;
687             let rustc_hir::LlvmInlineAsmInner {
688                 asm: asm_code, // Name
689                 outputs: output_names, // Vec<LlvmInlineAsmOutput>
690                 inputs: input_names,   // Vec<Name>
691                 clobbers,      // Vec<Name>
692                 volatile,      // bool
693                 alignstack,    // bool
694                 dialect: _,
695                 asm_str_style: _,
696             } = asm;
697             match asm_code.as_str().trim() {
698                 "" => {
699                     // Black box
700                 }
701                 "mov %rbx, %rsi\n                  cpuid\n                  xchg %rbx, %rsi" => {
702                     assert_eq!(input_names, &[Symbol::intern("{eax}"), Symbol::intern("{ecx}")]);
703                     assert_eq!(output_names.len(), 4);
704                     for (i, c) in (&["={eax}", "={esi}", "={ecx}", "={edx}"]).iter().enumerate() {
705                         assert_eq!(&output_names[i].constraint.as_str(), c);
706                         assert!(!output_names[i].is_rw);
707                         assert!(!output_names[i].is_indirect);
708                     }
709
710                     assert_eq!(clobbers, &[]);
711
712                     assert!(!volatile);
713                     assert!(!alignstack);
714
715                     assert_eq!(inputs.len(), 2);
716                     let leaf = trans_operand(fx, &inputs[0].1).load_scalar(fx); // %eax
717                     let subleaf = trans_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx
718
719                     let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf);
720
721                     assert_eq!(outputs.len(), 4);
722                     trans_place(fx, outputs[0]).write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
723                     trans_place(fx, outputs[1]).write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
724                     trans_place(fx, outputs[2]).write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
725                     trans_place(fx, outputs[3]).write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
726                 }
727                 "xgetbv" => {
728                     assert_eq!(input_names, &[Symbol::intern("{ecx}")]);
729
730                     assert_eq!(output_names.len(), 2);
731                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
732                         assert_eq!(&output_names[i].constraint.as_str(), c);
733                         assert!(!output_names[i].is_rw);
734                         assert!(!output_names[i].is_indirect);
735                     }
736
737                     assert_eq!(clobbers, &[]);
738
739                     assert!(!volatile);
740                     assert!(!alignstack);
741
742                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
743                 }
744                 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
745                 _ if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") => {
746                     crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
747                 }
748                 _ if fx.tcx.symbol_name(fx.instance).name == "__alloca" => {
749                     crate::trap::trap_unimplemented(fx, "Alloca is not supported");
750                 }
751                 // Used in sys::windows::abort_internal
752                 "int $$0x29" => {
753                     crate::trap::trap_unimplemented(fx, "Windows abort");
754                 }
755                 _ => fx.tcx.sess.span_fatal(stmt.source_info.span, "Inline assembly is not supported"),
756             }
757         }
758     }
759 }
760
761 fn codegen_array_len<'tcx>(
762     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
763     place: CPlace<'tcx>,
764 ) -> Value {
765     match place.layout().ty.kind {
766         ty::Array(_elem_ty, len) => {
767             let len = fx.monomorphize(&len)
768                 .eval(fx.tcx, ParamEnv::reveal_all())
769                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
770             fx.bcx.ins().iconst(fx.pointer_type, len)
771         }
772         ty::Slice(_elem_ty) => place
773             .to_ptr_maybe_unsized()
774             .1
775             .expect("Length metadata for slice place"),
776         _ => bug!("Rvalue::Len({:?})", place),
777     }
778 }
779
780 pub(crate) fn trans_place<'tcx>(
781     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
782     place: Place<'tcx>,
783 ) -> CPlace<'tcx> {
784     let mut cplace = fx.get_local_place(place.local);
785
786     for elem in place.projection {
787         match elem {
788             PlaceElem::Deref => {
789                 cplace = cplace.place_deref(fx);
790             }
791             PlaceElem::Field(field, _ty) => {
792                 cplace = cplace.place_field(fx, field);
793             }
794             PlaceElem::Index(local) => {
795                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
796                 cplace = cplace.place_index(fx, index);
797             }
798             PlaceElem::ConstantIndex {
799                 offset,
800                 min_length: _,
801                 from_end,
802             } => {
803                 let index = if !from_end {
804                     fx.bcx.ins().iconst(fx.pointer_type, i64::from(offset))
805                 } else {
806                     let len = codegen_array_len(fx, cplace);
807                     fx.bcx.ins().iadd_imm(len, -i64::from(offset))
808                 };
809                 cplace = cplace.place_index(fx, index);
810             }
811             PlaceElem::Subslice { from, to, from_end } => {
812                 // These indices are generated by slice patterns.
813                 // slice[from:-to] in Python terms.
814
815                 match cplace.layout().ty.kind {
816                     ty::Array(elem_ty, _len) => {
817                         assert!(!from_end, "array subslices are never `from_end`");
818                         let elem_layout = fx.layout_of(elem_ty);
819                         let ptr = cplace.to_ptr();
820                         cplace = CPlace::for_ptr(
821                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
822                             fx.layout_of(fx.tcx.mk_array(elem_ty, u64::from(to) - u64::from(from))),
823                         );
824                     }
825                     ty::Slice(elem_ty) => {
826                         assert!(from_end, "slice subslices should be `from_end`");
827                         let elem_layout = fx.layout_of(elem_ty);
828                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
829                         let len = len.unwrap();
830                         cplace = CPlace::for_ptr_with_extra(
831                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
832                             fx.bcx.ins().iadd_imm(len, -(i64::from(from) + i64::from(to))),
833                             cplace.layout(),
834                         );
835                     }
836                     _ => unreachable!(),
837                 }
838             }
839             PlaceElem::Downcast(_adt_def, variant) => {
840                 cplace = cplace.downcast_variant(fx, variant);
841             }
842         }
843     }
844
845     cplace
846 }
847
848 pub(crate) fn trans_operand<'tcx>(
849     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
850     operand: &Operand<'tcx>,
851 ) -> CValue<'tcx> {
852     match operand {
853         Operand::Move(place) | Operand::Copy(place) => {
854             let cplace = trans_place(fx, *place);
855             cplace.to_cvalue(fx)
856         }
857         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
858     }
859 }