]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Move all cold code to the end of the function
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
3
4 use crate::prelude::*;
5
6 pub 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 ebb's
33     let start_ebb = bcx.create_ebb();
34     let ebb_map: IndexVec<BasicBlock, Ebb> = (0..mir.basic_blocks().len()).map(|_| bcx.create_ebb()).collect();
35     let mut cold_ebbs = EntitySet::new();
36     for (bb, &ebb) in ebb_map.iter_enumerated() {
37         if mir.basic_blocks()[bb].is_cleanup {
38             cold_ebbs.insert(ebb);
39         }
40     }
41
42     // Make FunctionCx
43     let pointer_type = cx.module.target_config().pointer_type();
44     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
45
46     let mut fx = FunctionCx {
47         tcx,
48         module: cx.module,
49         pointer_type,
50
51         instance,
52         mir,
53
54         bcx,
55         ebb_map,
56         local_map: HashMap::new(),
57         caller_location: None, // set by `codegen_fn_prelude`
58         cold_ebbs,
59
60         clif_comments,
61         constants_cx: &mut cx.constants_cx,
62         vtables: &mut cx.vtables,
63         source_info_set: indexmap::IndexSet::new(),
64     };
65
66     if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
67         let entry_block = fx.bcx.create_ebb();
68         fx.bcx.append_ebb_params_for_function_params(entry_block);
69         fx.bcx.switch_to_block(entry_block);
70         crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
71     } else {
72         tcx.sess.time("codegen clif ir", || {
73             tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_ebb));
74             codegen_fn_content(&mut fx);
75         });
76     }
77
78     // Recover all necessary data from fx, before accessing func will prevent future access to it.
79     let instance = fx.instance;
80     let mut clif_comments = fx.clif_comments;
81     let source_info_set = fx.source_info_set;
82     let local_map = fx.local_map;
83     let cold_ebbs = fx.cold_ebbs;
84
85     #[cfg(debug_assertions)]
86     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
87
88     // Verify function
89     verify_func(tcx, &clif_comments, &context.func);
90
91     // Perform rust specific optimizations
92     tcx.sess.time("optimize clif ir", || {
93         crate::optimize::optimize_function(tcx, instance, context, &cold_ebbs, &mut clif_comments);
94     });
95
96     // Define function
97     let module = &mut cx.module;
98     tcx.sess.time("define function", || module.define_function(func_id, context).unwrap());
99
100     // Write optimized function to file for debugging
101     #[cfg(debug_assertions)]
102     {
103         let value_ranges = context
104             .build_value_labels_ranges(cx.module.isa())
105             .expect("value location ranges");
106
107         crate::pretty_clif::write_clif_file(
108             cx.tcx,
109             "opt",
110             instance,
111             &context.func,
112             &clif_comments,
113             Some(&value_ranges),
114         );
115     }
116
117     // Define debuginfo for function
118     let isa = cx.module.isa();
119     tcx.sess.time("generate debug info", || {
120         debug_context
121             .as_mut()
122             .map(|x| x.define(context, isa, &source_info_set, local_map));
123     });
124
125     // Clear context to make it usable for the next function
126     context.clear();
127 }
128
129 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
130     tcx.sess.time("verify clif ir", || {
131         let flags = settings::Flags::new(settings::builder());
132         match ::cranelift_codegen::verify_function(&func, &flags) {
133             Ok(_) => {}
134             Err(err) => {
135                 tcx.sess.err(&format!("{:?}", err));
136                 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
137                     &func,
138                     None,
139                     Some(Box::new(writer)),
140                     err,
141                 );
142                 tcx.sess
143                     .fatal(&format!("cranelift verify error:\n{}", pretty_error));
144             }
145         }
146     });
147 }
148
149 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
150     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
151         if bb_data.is_cleanup {
152             // Unwinding after panicking is not supported
153             continue;
154         }
155
156         let ebb = fx.get_ebb(bb);
157         fx.bcx.switch_to_block(ebb);
158
159         fx.bcx.ins().nop();
160         for stmt in &bb_data.statements {
161             fx.set_debug_loc(stmt.source_info);
162             trans_stmt(fx, ebb, stmt);
163         }
164
165         #[cfg(debug_assertions)]
166         {
167             let mut terminator_head = "\n".to_string();
168             bb_data
169                 .terminator()
170                 .kind
171                 .fmt_head(&mut terminator_head)
172                 .unwrap();
173             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
174             fx.add_comment(inst, terminator_head);
175         }
176
177         fx.set_debug_loc(bb_data.terminator().source_info);
178
179         match &bb_data.terminator().kind {
180             TerminatorKind::Goto { target } => {
181                 let ebb = fx.get_ebb(*target);
182                 fx.bcx.ins().jump(ebb, &[]);
183             }
184             TerminatorKind::Return => {
185                 crate::abi::codegen_return(fx);
186             }
187             TerminatorKind::Assert {
188                 cond,
189                 expected,
190                 msg,
191                 target,
192                 cleanup: _,
193             } => {
194                 if !fx.tcx.sess.overflow_checks() {
195                     if let mir::interpret::PanicInfo::OverflowNeg = *msg {
196                         let target = fx.get_ebb(*target);
197                         fx.bcx.ins().jump(target, &[]);
198                         continue;
199                     }
200                 }
201                 let cond = trans_operand(fx, cond).load_scalar(fx);
202
203                 let target = fx.get_ebb(*target);
204                 let failure = fx.bcx.create_ebb();
205                 fx.cold_ebbs.insert(failure);
206
207                 if *expected {
208                     fx.bcx.ins().brz(cond, failure, &[]);
209                 } else {
210                     fx.bcx.ins().brnz(cond, failure, &[]);
211                 };
212                 fx.bcx.ins().jump(target, &[]);
213
214                 fx.bcx.switch_to_block(failure);
215                 trap_panic(
216                     fx,
217                     format!(
218                         "[panic] Assert {:?} at {:?} failed.",
219                         msg,
220                         bb_data.terminator().source_info.span
221                     ),
222                 );
223             }
224
225             TerminatorKind::SwitchInt {
226                 discr,
227                 switch_ty: _,
228                 values,
229                 targets,
230             } => {
231                 let discr = trans_operand(fx, discr).load_scalar(fx);
232                 let mut switch = ::cranelift_frontend::Switch::new();
233                 for (i, value) in values.iter().enumerate() {
234                     let ebb = fx.get_ebb(targets[i]);
235                     switch.set_entry(*value as u64, ebb);
236                 }
237                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
238                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
239             }
240             TerminatorKind::Call {
241                 func,
242                 args,
243                 destination,
244                 cleanup: _,
245                 from_hir_call: _,
246             } => {
247                 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
248                     fx,
249                     bb_data.terminator().source_info.span,
250                     func,
251                     args,
252                     destination,
253                 ));
254             }
255             TerminatorKind::Resume | TerminatorKind::Abort => {
256                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
257             }
258             TerminatorKind::Unreachable => {
259                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
260             }
261             TerminatorKind::Yield { .. }
262             | TerminatorKind::FalseEdges { .. }
263             | TerminatorKind::FalseUnwind { .. }
264             | TerminatorKind::DropAndReplace { .. }
265             | TerminatorKind::GeneratorDrop => {
266                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
267             }
268             TerminatorKind::Drop {
269                 location,
270                 target,
271                 unwind: _,
272             } => {
273                 let drop_place = trans_place(fx, location);
274                 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
275
276                 let target_ebb = fx.get_ebb(*target);
277                 fx.bcx.ins().jump(target_ebb, &[]);
278             }
279         };
280     }
281
282     fx.bcx.seal_all_blocks();
283     fx.bcx.finalize();
284 }
285
286 fn trans_stmt<'tcx>(
287     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
288     cur_ebb: Ebb,
289     stmt: &Statement<'tcx>,
290 ) {
291     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
292
293     fx.set_debug_loc(stmt.source_info);
294
295     #[cfg(debug_assertions)]
296     match &stmt.kind {
297         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
298         _ => {
299             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
300             fx.add_comment(inst, format!("{:?}", stmt));
301         }
302     }
303
304     match &stmt.kind {
305         StatementKind::SetDiscriminant {
306             place,
307             variant_index,
308         } => {
309             let place = trans_place(fx, place);
310             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
311         }
312         StatementKind::Assign(to_place_and_rval) => {
313             let lval = trans_place(fx, &to_place_and_rval.0);
314             let dest_layout = lval.layout();
315             match &to_place_and_rval.1 {
316                 Rvalue::Use(operand) => {
317                     let val = trans_operand(fx, operand);
318                     lval.write_cvalue(fx, val);
319                 }
320                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
321                     let place = trans_place(fx, place);
322                     place.write_place_ref(fx, lval);
323                 }
324                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
325                     let lhs = trans_operand(fx, lhs);
326                     let rhs = trans_operand(fx, rhs);
327
328                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
329                     lval.write_cvalue(fx, res);
330                 }
331                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
332                     let lhs = trans_operand(fx, lhs);
333                     let rhs = trans_operand(fx, rhs);
334
335                     let res = if !fx.tcx.sess.overflow_checks() {
336                         let val =
337                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
338                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
339                         CValue::by_val_pair(val, is_overflow, lval.layout())
340                     } else {
341                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
342                     };
343
344                     lval.write_cvalue(fx, res);
345                 }
346                 Rvalue::UnaryOp(un_op, operand) => {
347                     let operand = trans_operand(fx, operand);
348                     let layout = operand.layout();
349                     let val = operand.load_scalar(fx);
350                     let res = match un_op {
351                         UnOp::Not => {
352                             match layout.ty.kind {
353                                 ty::Bool => {
354                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
355                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
356                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
357                                 }
358                                 ty::Uint(_) | ty::Int(_) => {
359                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
360                                 }
361                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
362                             }
363                         }
364                         UnOp::Neg => match layout.ty.kind {
365                             ty::Int(_) => {
366                                 let zero = CValue::const_val(fx, layout.ty, 0);
367                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
368                             }
369                             ty::Float(_) => {
370                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
371                             }
372                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
373                         },
374                     };
375                     lval.write_cvalue(fx, res);
376                 }
377                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
378                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
379                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
380                     match from_ty.kind {
381                         ty::FnDef(def_id, substs) => {
382                             let func_ref = fx.get_function_ref(
383                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
384                                     .unwrap(),
385                             );
386                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
387                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
388                         }
389                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
390                     }
391                 }
392                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
393                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
394                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
395                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
396                     let operand = trans_operand(fx, operand);
397                     lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
398                 }
399                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
400                     let operand = trans_operand(fx, operand);
401                     let from_ty = operand.layout().ty;
402                     let to_ty = fx.monomorphize(to_ty);
403
404                     fn is_fat_ptr<'tcx>(
405                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
406                         ty: Ty<'tcx>,
407                     ) -> bool {
408                         ty.builtin_deref(true)
409                             .map(
410                                 |ty::TypeAndMut {
411                                      ty: pointee_ty,
412                                      mutbl: _,
413                                  }| has_ptr_meta(fx.tcx, pointee_ty),
414                             )
415                             .unwrap_or(false)
416                     }
417
418                     if is_fat_ptr(fx, from_ty) {
419                         if is_fat_ptr(fx, to_ty) {
420                             // fat-ptr -> fat-ptr
421                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
422                         } else {
423                             // fat-ptr -> thin-ptr
424                             let (ptr, _extra) = operand.load_scalar_pair(fx);
425                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
426                         }
427                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
428                         // enum -> discriminant value
429                         assert!(adt_def.is_enum());
430                         match to_ty.kind {
431                             ty::Uint(_) | ty::Int(_) => {}
432                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
433                         }
434
435                         let discr = crate::discriminant::codegen_get_discriminant(
436                             fx,
437                             operand,
438                             fx.layout_of(to_ty),
439                         );
440                         lval.write_cvalue(fx, discr);
441                     } else {
442                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
443                         let from = operand.load_scalar(fx);
444
445                         let res = clif_int_or_float_cast(
446                             fx,
447                             from,
448                             type_sign(from_ty),
449                             to_clif_ty,
450                             type_sign(to_ty),
451                         );
452                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
453                     }
454                 }
455                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
456                     let operand = trans_operand(fx, operand);
457                     match operand.layout().ty.kind {
458                         ty::Closure(def_id, substs) => {
459                             let instance = Instance::resolve_closure(
460                                 fx.tcx,
461                                 def_id,
462                                 substs,
463                                 ty::ClosureKind::FnOnce,
464                             );
465                             let func_ref = fx.get_function_ref(instance);
466                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
467                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
468                         }
469                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
470                     }
471                 }
472                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
473                     let operand = trans_operand(fx, operand);
474                     operand.unsize_value(fx, lval);
475                 }
476                 Rvalue::Discriminant(place) => {
477                     let place = trans_place(fx, place);
478                     let value = place.to_cvalue(fx);
479                     let discr =
480                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
481                     lval.write_cvalue(fx, discr);
482                 }
483                 Rvalue::Repeat(operand, times) => {
484                     let operand = trans_operand(fx, operand);
485                     for i in 0..*times {
486                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
487                         let to = lval.place_index(fx, index);
488                         to.write_cvalue(fx, operand);
489                     }
490                 }
491                 Rvalue::Len(place) => {
492                     let place = trans_place(fx, place);
493                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
494                     let len = codegen_array_len(fx, place);
495                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
496                 }
497                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
498                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
499
500                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
501                     let content_ty = fx.monomorphize(content_ty);
502                     let layout = fx.layout_of(content_ty);
503                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
504                     let llalign = fx
505                         .bcx
506                         .ins()
507                         .iconst(usize_type, layout.align.abi.bytes() as i64);
508                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
509
510                     // Allocate space:
511                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
512                         Ok(id) => id,
513                         Err(s) => {
514                             fx.tcx
515                                 .sess
516                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
517                         }
518                     };
519                     let instance = ty::Instance::mono(fx.tcx, def_id);
520                     let func_ref = fx.get_function_ref(instance);
521                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
522                     let ptr = fx.bcx.inst_results(call)[0];
523                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
524                 }
525                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
526                     assert!(lval
527                         .layout()
528                         .ty
529                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
530                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
531                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
532                     lval.write_cvalue(fx, val);
533                 }
534                 Rvalue::Aggregate(kind, operands) => match **kind {
535                     AggregateKind::Array(_ty) => {
536                         for (i, operand) in operands.into_iter().enumerate() {
537                             let operand = trans_operand(fx, operand);
538                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
539                             let to = lval.place_index(fx, index);
540                             to.write_cvalue(fx, operand);
541                         }
542                     }
543                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
544                 },
545             }
546         }
547         StatementKind::StorageLive(_)
548         | StatementKind::StorageDead(_)
549         | StatementKind::Nop
550         | StatementKind::FakeRead(..)
551         | StatementKind::Retag { .. }
552         | StatementKind::AscribeUserType(..) => {}
553
554         StatementKind::InlineAsm(asm) => {
555             use syntax::ast::Name;
556             let InlineAsm {
557                 asm,
558                 outputs: _,
559                 inputs: _,
560             } = &**asm;
561             let rustc_hir::InlineAsmInner {
562                 asm: asm_code, // Name
563                 outputs,       // Vec<Name>
564                 inputs,        // Vec<Name>
565                 clobbers,      // Vec<Name>
566                 volatile,      // bool
567                 alignstack,    // bool
568                 dialect: _,    // syntax::ast::AsmDialect
569                 asm_str_style: _,
570             } = asm;
571             match &*asm_code.as_str() {
572                 "" => {
573                     assert_eq!(inputs, &[Name::intern("r")]);
574                     assert!(outputs.is_empty(), "{:?}", outputs);
575
576                     // Black box
577                 }
578                 "cpuid" | "cpuid\n" => {
579                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
580
581                     assert_eq!(outputs.len(), 4);
582                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
583                         .iter()
584                         .enumerate()
585                     {
586                         assert_eq!(&outputs[i].constraint.as_str(), c);
587                         assert!(!outputs[i].is_rw);
588                         assert!(!outputs[i].is_indirect);
589                     }
590
591                     assert_eq!(clobbers, &[Name::intern("rbx")]);
592
593                     assert!(!volatile);
594                     assert!(!alignstack);
595
596                     crate::trap::trap_unimplemented(
597                         fx,
598                         "__cpuid_count arch intrinsic is not supported",
599                     );
600                 }
601                 "xgetbv" => {
602                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
603
604                     assert_eq!(outputs.len(), 2);
605                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
606                         assert_eq!(&outputs[i].constraint.as_str(), c);
607                         assert!(!outputs[i].is_rw);
608                         assert!(!outputs[i].is_indirect);
609                     }
610
611                     assert_eq!(clobbers, &[]);
612
613                     assert!(!volatile);
614                     assert!(!alignstack);
615
616                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
617                 }
618                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
619                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
620                 }
621                 _ => unimpl!("Inline assembly is not supported"),
622             }
623         }
624     }
625 }
626
627 fn codegen_array_len<'tcx>(
628     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
629     place: CPlace<'tcx>,
630 ) -> Value {
631     match place.layout().ty.kind {
632         ty::Array(_elem_ty, len) => {
633             let len = crate::constant::force_eval_const(fx, len)
634                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
635             fx.bcx.ins().iconst(fx.pointer_type, len)
636         }
637         ty::Slice(_elem_ty) => place
638             .to_ptr_maybe_unsized(fx)
639             .1
640             .expect("Length metadata for slice place"),
641         _ => bug!("Rvalue::Len({:?})", place),
642     }
643 }
644
645 pub fn trans_place<'tcx>(
646     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
647     place: &Place<'tcx>,
648 ) -> CPlace<'tcx> {
649     let mut cplace = match &place.base {
650         PlaceBase::Local(local) => fx.get_local_place(*local),
651         PlaceBase::Static(static_) => match static_.kind {
652             StaticKind::Static => {
653                 // Statics can't be generic, so `static_.ty` doesn't need to be monomorphized.
654                 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
655             }
656             StaticKind::Promoted(promoted, substs) => {
657                 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
658                 let ty = fx.monomorphize(&static_.ty);
659                 crate::constant::trans_promoted(fx, instance, promoted, ty)
660             }
661         },
662     };
663
664     for elem in &*place.projection {
665         match *elem {
666             PlaceElem::Deref => {
667                 cplace = cplace.place_deref(fx);
668             }
669             PlaceElem::Field(field, _ty) => {
670                 cplace = cplace.place_field(fx, field);
671             }
672             PlaceElem::Index(local) => {
673                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
674                 cplace = cplace.place_index(fx, index);
675             }
676             PlaceElem::ConstantIndex {
677                 offset,
678                 min_length: _,
679                 from_end,
680             } => {
681                 let index = if !from_end {
682                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
683                 } else {
684                     let len = codegen_array_len(fx, cplace);
685                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
686                 };
687                 cplace = cplace.place_index(fx, index);
688             }
689             PlaceElem::Subslice { from, to, from_end } => {
690                 // These indices are generated by slice patterns.
691                 // slice[from:-to] in Python terms.
692
693                 match cplace.layout().ty.kind {
694                     ty::Array(elem_ty, len) => {
695                         let elem_layout = fx.layout_of(elem_ty);
696                         let ptr = cplace.to_ptr(fx);
697                         let len = crate::constant::force_eval_const(fx, len)
698                             .eval_usize(fx.tcx, ParamEnv::reveal_all());
699                         cplace = CPlace::for_ptr(
700                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
701                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
702                         );
703                     }
704                     ty::Slice(elem_ty) => {
705                         assert!(from_end, "slice subslices should be `from_end`");
706                         let elem_layout = fx.layout_of(elem_ty);
707                         let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
708                         let len = len.unwrap();
709                         cplace = CPlace::for_ptr_with_extra(
710                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
711                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
712                             cplace.layout(),
713                         );
714                     }
715                     _ => unreachable!(),
716                 }
717             }
718             PlaceElem::Downcast(_adt_def, variant) => {
719                 cplace = cplace.downcast_variant(fx, variant);
720             }
721         }
722     }
723
724     cplace
725 }
726
727 pub fn trans_operand<'tcx>(
728     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
729     operand: &Operand<'tcx>,
730 ) -> CValue<'tcx> {
731     match operand {
732         Operand::Move(place) | Operand::Copy(place) => {
733             let cplace = trans_place(fx, place);
734             cplace.to_cvalue(fx)
735         }
736         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
737     }
738 }