]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Mark blocks that call cold funs as cold (#1021)
[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<'clif, 'tcx, B: Backend + 'static>(
7     cx: &mut crate::CodegenCx<'clif, '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     let mut debug_context = cx
19         .debug_context
20         .as_mut()
21         .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
22
23     // Make FunctionBuilder
24     let context = &mut cx.cached_context;
25     context.clear();
26     context.func.name = ExternalName::user(0, func_id.as_u32());
27     context.func.signature = sig;
28     context.func.collect_debug_info();
29     let mut func_ctx = FunctionBuilderContext::new();
30     let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
31
32     // Predefine blocks
33     let start_block = bcx.create_block();
34     let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
35
36     // Make FunctionCx
37     let pointer_type = cx.module.target_config().pointer_type();
38     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
39
40     let mut fx = FunctionCx {
41         tcx,
42         module: cx.module,
43         pointer_type,
44
45         instance,
46         mir,
47
48         bcx,
49         block_map,
50         local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
51         caller_location: None, // set by `codegen_fn_prelude`
52         cold_blocks: EntitySet::new(),
53
54         clif_comments,
55         constants_cx: &mut cx.constants_cx,
56         vtables: &mut cx.vtables,
57         source_info_set: indexmap::IndexSet::new(),
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, true));
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     #[cfg(debug_assertions)]
81     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
82
83     // Verify function
84     verify_func(tcx, &clif_comments, &context.func);
85
86     // Perform rust specific optimizations
87     tcx.sess.time("optimize clif ir", || {
88         crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
89     });
90
91     // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
92     // instruction, which doesn't have an encoding.
93     context.compute_cfg();
94     context.compute_domtree();
95     context.eliminate_unreachable_code(cx.module.isa()).unwrap();
96
97     // Define function
98     let module = &mut cx.module;
99     tcx.sess.time(
100         "define function",
101         || module.define_function(
102             func_id,
103             context,
104             &mut cranelift_codegen::binemit::NullTrapSink {},
105         ).unwrap(),
106     );
107
108     // Write optimized function to file for debugging
109     #[cfg(debug_assertions)]
110     {
111         let value_ranges = context
112             .build_value_labels_ranges(cx.module.isa())
113             .expect("value location ranges");
114
115         crate::pretty_clif::write_clif_file(
116             cx.tcx,
117             "opt",
118             instance,
119             &context.func,
120             &clif_comments,
121             Some(&value_ranges),
122         );
123     }
124
125     // Define debuginfo for function
126     let isa = cx.module.isa();
127     let unwind_context = &mut cx.unwind_context;
128     tcx.sess.time("generate debug info", || {
129         debug_context
130             .as_mut()
131             .map(|x| x.define(context, isa, &source_info_set, local_map));
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 = settings::Flags::new(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.as_str();
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 as u64, 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                 cleanup: _,
298                 from_hir_call: _,
299             } => {
300                 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
301                     fx,
302                     bb_data.terminator().source_info.span,
303                     block,
304                     func,
305                     args,
306                     *destination,
307                 ));
308             }
309             TerminatorKind::InlineAsm {
310                 template,
311                 operands,
312                 options: _,
313                 destination,
314             } => {
315                 match template {
316                     &[] => {
317                         assert_eq!(operands, &[]);
318                         match *destination {
319                             Some(destination) => {
320                                 let destination_block = fx.get_block(destination);
321                                 fx.bcx.ins().jump(destination_block, &[]);
322                             }
323                             None => bug!(),
324                         }
325
326                         // Black box
327                     }
328                     _ => unimpl_fatal!(fx.tcx, bb_data.terminator().source_info.span, "Inline assembly is not supported"),
329                 }
330             }
331             TerminatorKind::Resume | TerminatorKind::Abort => {
332                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
333             }
334             TerminatorKind::Unreachable => {
335                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
336             }
337             TerminatorKind::Yield { .. }
338             | TerminatorKind::FalseEdges { .. }
339             | TerminatorKind::FalseUnwind { .. }
340             | TerminatorKind::DropAndReplace { .. }
341             | TerminatorKind::GeneratorDrop => {
342                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
343             }
344             TerminatorKind::Drop {
345                 location,
346                 target,
347                 unwind: _,
348             } => {
349                 let drop_place = trans_place(fx, *location);
350                 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
351
352                 let target_block = fx.get_block(*target);
353                 fx.bcx.ins().jump(target_block, &[]);
354             }
355         };
356     }
357
358     fx.bcx.seal_all_blocks();
359     fx.bcx.finalize();
360 }
361
362 fn trans_stmt<'tcx>(
363     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
364     #[allow(unused_variables)]
365     cur_block: Block,
366     stmt: &Statement<'tcx>,
367 ) {
368     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
369
370     fx.set_debug_loc(stmt.source_info);
371
372     #[cfg(false_debug_assertions)]
373     match &stmt.kind {
374         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
375         _ => {
376             let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
377             fx.add_comment(inst, format!("{:?}", stmt));
378         }
379     }
380
381     match &stmt.kind {
382         StatementKind::SetDiscriminant {
383             place,
384             variant_index,
385         } => {
386             let place = trans_place(fx, **place);
387             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
388         }
389         StatementKind::Assign(to_place_and_rval) => {
390             let lval = trans_place(fx, to_place_and_rval.0);
391             let dest_layout = lval.layout();
392             match &to_place_and_rval.1 {
393                 Rvalue::Use(operand) => {
394                     let val = trans_operand(fx, operand);
395                     lval.write_cvalue(fx, val);
396                 }
397                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
398                     let place = trans_place(fx, *place);
399                     place.write_place_ref(fx, lval);
400                 }
401                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
402                     let lhs = trans_operand(fx, lhs);
403                     let rhs = trans_operand(fx, rhs);
404
405                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
406                     lval.write_cvalue(fx, res);
407                 }
408                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
409                     let lhs = trans_operand(fx, lhs);
410                     let rhs = trans_operand(fx, rhs);
411
412                     let res = if !fx.tcx.sess.overflow_checks() {
413                         let val =
414                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
415                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
416                         CValue::by_val_pair(val, is_overflow, lval.layout())
417                     } else {
418                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
419                     };
420
421                     lval.write_cvalue(fx, res);
422                 }
423                 Rvalue::UnaryOp(un_op, operand) => {
424                     let operand = trans_operand(fx, operand);
425                     let layout = operand.layout();
426                     let val = operand.load_scalar(fx);
427                     let res = match un_op {
428                         UnOp::Not => {
429                             match layout.ty.kind {
430                                 ty::Bool => {
431                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
432                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
433                                 }
434                                 ty::Uint(_) | ty::Int(_) => {
435                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
436                                 }
437                                 _ => unreachable!("un op Not for {:?}", layout.ty),
438                             }
439                         }
440                         UnOp::Neg => match layout.ty.kind {
441                             ty::Int(IntTy::I128) => {
442                                 // FIXME remove this case once ineg.i128 works
443                                 let zero = CValue::const_val(fx, layout, 0);
444                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
445                             }
446                             ty::Int(_) => {
447                                 CValue::by_val(fx.bcx.ins().ineg(val), layout)
448                             }
449                             ty::Float(_) => {
450                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
451                             }
452                             _ => unreachable!("un op Neg for {:?}", layout.ty),
453                         },
454                     };
455                     lval.write_cvalue(fx, res);
456                 }
457                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
458                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
459                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
460                     match from_ty.kind {
461                         ty::FnDef(def_id, substs) => {
462                             let func_ref = fx.get_function_ref(
463                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
464                                     .unwrap(),
465                             );
466                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
467                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
468                         }
469                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
470                     }
471                 }
472                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
473                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
474                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
475                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
476                     let operand = trans_operand(fx, operand);
477                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
478                 }
479                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
480                     let operand = trans_operand(fx, operand);
481                     let from_ty = operand.layout().ty;
482                     let to_ty = fx.monomorphize(to_ty);
483
484                     fn is_fat_ptr<'tcx>(
485                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
486                         ty: Ty<'tcx>,
487                     ) -> bool {
488                         ty.builtin_deref(true)
489                             .map(
490                                 |ty::TypeAndMut {
491                                      ty: pointee_ty,
492                                      mutbl: _,
493                                  }| has_ptr_meta(fx.tcx, pointee_ty),
494                             )
495                             .unwrap_or(false)
496                     }
497
498                     if is_fat_ptr(fx, from_ty) {
499                         if is_fat_ptr(fx, to_ty) {
500                             // fat-ptr -> fat-ptr
501                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
502                         } else {
503                             // fat-ptr -> thin-ptr
504                             let (ptr, _extra) = operand.load_scalar_pair(fx);
505                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
506                         }
507                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
508                         // enum -> discriminant value
509                         assert!(adt_def.is_enum());
510                         match to_ty.kind {
511                             ty::Uint(_) | ty::Int(_) => {}
512                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
513                         }
514
515                         let discr = crate::discriminant::codegen_get_discriminant(
516                             fx,
517                             operand,
518                             fx.layout_of(to_ty),
519                         );
520                         lval.write_cvalue(fx, discr);
521                     } else {
522                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
523                         let from = operand.load_scalar(fx);
524
525                         let res = clif_int_or_float_cast(
526                             fx,
527                             from,
528                             type_sign(from_ty),
529                             to_clif_ty,
530                             type_sign(to_ty),
531                         );
532                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
533                     }
534                 }
535                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
536                     let operand = trans_operand(fx, operand);
537                     match operand.layout().ty.kind {
538                         ty::Closure(def_id, substs) => {
539                             let instance = Instance::resolve_closure(
540                                 fx.tcx,
541                                 def_id,
542                                 substs,
543                                 ty::ClosureKind::FnOnce,
544                             );
545                             let func_ref = fx.get_function_ref(instance);
546                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
547                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
548                         }
549                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
550                     }
551                 }
552                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
553                     let operand = trans_operand(fx, operand);
554                     operand.unsize_value(fx, lval);
555                 }
556                 Rvalue::Discriminant(place) => {
557                     let place = trans_place(fx, *place);
558                     let value = place.to_cvalue(fx);
559                     let discr =
560                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
561                     lval.write_cvalue(fx, discr);
562                 }
563                 Rvalue::Repeat(operand, times) => {
564                     let operand = trans_operand(fx, operand);
565                     let times = fx
566                         .monomorphize(times)
567                         .eval(fx.tcx, ParamEnv::reveal_all())
568                         .val
569                         .try_to_bits(fx.tcx.data_layout.pointer_size)
570                         .unwrap();
571                     for i in 0..times {
572                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
573                         let to = lval.place_index(fx, index);
574                         to.write_cvalue(fx, operand);
575                     }
576                 }
577                 Rvalue::Len(place) => {
578                     let place = trans_place(fx, *place);
579                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
580                     let len = codegen_array_len(fx, place);
581                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
582                 }
583                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
584                     use rustc_hir::lang_items::ExchangeMallocFnLangItem;
585
586                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
587                     let content_ty = fx.monomorphize(content_ty);
588                     let layout = fx.layout_of(content_ty);
589                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
590                     let llalign = fx
591                         .bcx
592                         .ins()
593                         .iconst(usize_type, layout.align.abi.bytes() as i64);
594                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
595
596                     // Allocate space:
597                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
598                         Ok(id) => id,
599                         Err(s) => {
600                             fx.tcx
601                                 .sess
602                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
603                         }
604                     };
605                     let instance = ty::Instance::mono(fx.tcx, def_id);
606                     let func_ref = fx.get_function_ref(instance);
607                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
608                     let ptr = fx.bcx.inst_results(call)[0];
609                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
610                 }
611                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
612                     assert!(lval
613                         .layout()
614                         .ty
615                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
616                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
617                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
618                     lval.write_cvalue(fx, val);
619                 }
620                 Rvalue::Aggregate(kind, operands) => match **kind {
621                     AggregateKind::Array(_ty) => {
622                         for (i, operand) in operands.into_iter().enumerate() {
623                             let operand = trans_operand(fx, operand);
624                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
625                             let to = lval.place_index(fx, index);
626                             to.write_cvalue(fx, operand);
627                         }
628                     }
629                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
630                 },
631             }
632         }
633         StatementKind::StorageLive(_)
634         | StatementKind::StorageDead(_)
635         | StatementKind::Nop
636         | StatementKind::FakeRead(..)
637         | StatementKind::Retag { .. }
638         | StatementKind::AscribeUserType(..) => {}
639
640         StatementKind::LlvmInlineAsm(asm) => {
641             use rustc_span::symbol::Symbol;
642             let LlvmInlineAsm {
643                 asm,
644                 outputs: _,
645                 inputs: _,
646             } = &**asm;
647             let rustc_hir::LlvmInlineAsmInner {
648                 asm: asm_code, // Name
649                 outputs,       // Vec<Name>
650                 inputs,        // Vec<Name>
651                 clobbers,      // Vec<Name>
652                 volatile,      // bool
653                 alignstack,    // bool
654                 dialect: _,    // rustc_ast::ast::AsmDialect
655                 asm_str_style: _,
656             } = asm;
657             match &*asm_code.as_str() {
658                 cpuid if cpuid.contains("cpuid") => {
659                     crate::trap::trap_unimplemented(
660                         fx,
661                         "__cpuid_count arch intrinsic is not supported",
662                     );
663                 }
664                 "xgetbv" => {
665                     assert_eq!(inputs, &[Symbol::intern("{ecx}")]);
666
667                     assert_eq!(outputs.len(), 2);
668                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
669                         assert_eq!(&outputs[i].constraint.as_str(), c);
670                         assert!(!outputs[i].is_rw);
671                         assert!(!outputs[i].is_indirect);
672                     }
673
674                     assert_eq!(clobbers, &[]);
675
676                     assert!(!volatile);
677                     assert!(!alignstack);
678
679                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
680                 }
681                 _ => unimpl_fatal!(fx.tcx, stmt.source_info.span, "Inline assembly is not supported"),
682             }
683         }
684     }
685 }
686
687 fn codegen_array_len<'tcx>(
688     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
689     place: CPlace<'tcx>,
690 ) -> Value {
691     match place.layout().ty.kind {
692         ty::Array(_elem_ty, len) => {
693             let len = fx.monomorphize(&len)
694                 .eval(fx.tcx, ParamEnv::reveal_all())
695                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
696             fx.bcx.ins().iconst(fx.pointer_type, len)
697         }
698         ty::Slice(_elem_ty) => place
699             .to_ptr_maybe_unsized()
700             .1
701             .expect("Length metadata for slice place"),
702         _ => bug!("Rvalue::Len({:?})", place),
703     }
704 }
705
706 pub(crate) fn trans_place<'tcx>(
707     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
708     place: Place<'tcx>,
709 ) -> CPlace<'tcx> {
710     let mut cplace = fx.get_local_place(place.local);
711
712     for elem in place.projection {
713         match *elem {
714             PlaceElem::Deref => {
715                 cplace = cplace.place_deref(fx);
716             }
717             PlaceElem::Field(field, _ty) => {
718                 cplace = cplace.place_field(fx, field);
719             }
720             PlaceElem::Index(local) => {
721                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
722                 cplace = cplace.place_index(fx, index);
723             }
724             PlaceElem::ConstantIndex {
725                 offset,
726                 min_length: _,
727                 from_end,
728             } => {
729                 let index = if !from_end {
730                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
731                 } else {
732                     let len = codegen_array_len(fx, cplace);
733                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
734                 };
735                 cplace = cplace.place_index(fx, index);
736             }
737             PlaceElem::Subslice { from, to, from_end } => {
738                 // These indices are generated by slice patterns.
739                 // slice[from:-to] in Python terms.
740
741                 match cplace.layout().ty.kind {
742                     ty::Array(elem_ty, _len) => {
743                         assert!(!from_end, "array subslices are never `from_end`");
744                         let elem_layout = fx.layout_of(elem_ty);
745                         let ptr = cplace.to_ptr();
746                         cplace = CPlace::for_ptr(
747                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
748                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
749                         );
750                     }
751                     ty::Slice(elem_ty) => {
752                         assert!(from_end, "slice subslices should be `from_end`");
753                         let elem_layout = fx.layout_of(elem_ty);
754                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
755                         let len = len.unwrap();
756                         cplace = CPlace::for_ptr_with_extra(
757                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
758                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
759                             cplace.layout(),
760                         );
761                     }
762                     _ => unreachable!(),
763                 }
764             }
765             PlaceElem::Downcast(_adt_def, variant) => {
766                 cplace = cplace.downcast_variant(fx, variant);
767             }
768         }
769     }
770
771     cplace
772 }
773
774 pub(crate) fn trans_operand<'tcx>(
775     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
776     operand: &Operand<'tcx>,
777 ) -> CValue<'tcx> {
778     match operand {
779         Operand::Move(place) | Operand::Copy(place) => {
780             let cplace = trans_place(fx, *place);
781             cplace.to_cvalue(fx)
782         }
783         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
784     }
785 }