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