]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Silence some warnings
[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 block's
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: HashMap::new(),
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     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_block();
62         fx.bcx.append_block_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_block));
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_blocks = fx.cold_blocks;
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_blocks, &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 block = fx.get_block(bb);
146         fx.bcx.switch_to_block(block);
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 block's as cold.
154             // fx.cold_blocks.insert(block);
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, block, 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(block).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 block = fx.get_block(*target);
180                 fx.bcx.ins().jump(block, &[]);
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::AssertKind::OverflowNeg = *msg {
194                         let target = fx.get_block(*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_block(*target);
202                 let failure = fx.bcx.create_block();
203                 fx.cold_blocks.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 block = fx.get_block(targets[i]);
233                     switch.set_entry(*value as u64, block);
234                 }
235                 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
236                 switch.emit(&mut fx.bcx, discr, otherwise_block);
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_block = fx.get_block(*target);
275                 fx.bcx.ins().jump(target_block, &[]);
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     #[allow(unused_variables)]
287     cur_block: Block,
288     stmt: &Statement<'tcx>,
289 ) {
290     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
291
292     fx.set_debug_loc(stmt.source_info);
293
294     #[cfg(false_debug_assertions)]
295     match &stmt.kind {
296         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
297         _ => {
298             let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
299             fx.add_comment(inst, format!("{:?}", stmt));
300         }
301     }
302
303     match &stmt.kind {
304         StatementKind::SetDiscriminant {
305             place,
306             variant_index,
307         } => {
308             let place = trans_place(fx, place);
309             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
310         }
311         StatementKind::Assign(to_place_and_rval) => {
312             let lval = trans_place(fx, &to_place_and_rval.0);
313             let dest_layout = lval.layout();
314             match &to_place_and_rval.1 {
315                 Rvalue::Use(operand) => {
316                     let val = trans_operand(fx, operand);
317                     lval.write_cvalue(fx, val);
318                 }
319                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
320                     let place = trans_place(fx, place);
321                     place.write_place_ref(fx, lval);
322                 }
323                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
324                     let lhs = trans_operand(fx, lhs);
325                     let rhs = trans_operand(fx, rhs);
326
327                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
328                     lval.write_cvalue(fx, res);
329                 }
330                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
331                     let lhs = trans_operand(fx, lhs);
332                     let rhs = trans_operand(fx, rhs);
333
334                     let res = if !fx.tcx.sess.overflow_checks() {
335                         let val =
336                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
337                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
338                         CValue::by_val_pair(val, is_overflow, lval.layout())
339                     } else {
340                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
341                     };
342
343                     lval.write_cvalue(fx, res);
344                 }
345                 Rvalue::UnaryOp(un_op, operand) => {
346                     let operand = trans_operand(fx, operand);
347                     let layout = operand.layout();
348                     let val = operand.load_scalar(fx);
349                     let res = match un_op {
350                         UnOp::Not => {
351                             match layout.ty.kind {
352                                 ty::Bool => {
353                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
354                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
355                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
356                                 }
357                                 ty::Uint(_) | ty::Int(_) => {
358                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
359                                 }
360                                 _ => unreachable!("un op Not for {:?}", layout.ty),
361                             }
362                         }
363                         UnOp::Neg => match layout.ty.kind {
364                             ty::Int(IntTy::I128) => {
365                                 // FIXME remove this case once ineg.i128 works
366                                 let zero = CValue::const_val(fx, layout, 0);
367                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
368                             }
369                             ty::Int(_) => {
370                                 CValue::by_val(fx.bcx.ins().ineg(val), layout)
371                             }
372                             ty::Float(_) => {
373                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
374                             }
375                             _ => unreachable!("un op Neg for {:?}", layout.ty),
376                         },
377                     };
378                     lval.write_cvalue(fx, res);
379                 }
380                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
381                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
382                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
383                     match from_ty.kind {
384                         ty::FnDef(def_id, substs) => {
385                             let func_ref = fx.get_function_ref(
386                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
387                                     .unwrap(),
388                             );
389                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
390                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
391                         }
392                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
393                     }
394                 }
395                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
396                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
397                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
398                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
399                     let operand = trans_operand(fx, operand);
400                     lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
401                 }
402                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
403                     let operand = trans_operand(fx, operand);
404                     let from_ty = operand.layout().ty;
405                     let to_ty = fx.monomorphize(to_ty);
406
407                     fn is_fat_ptr<'tcx>(
408                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
409                         ty: Ty<'tcx>,
410                     ) -> bool {
411                         ty.builtin_deref(true)
412                             .map(
413                                 |ty::TypeAndMut {
414                                      ty: pointee_ty,
415                                      mutbl: _,
416                                  }| has_ptr_meta(fx.tcx, pointee_ty),
417                             )
418                             .unwrap_or(false)
419                     }
420
421                     if is_fat_ptr(fx, from_ty) {
422                         if is_fat_ptr(fx, to_ty) {
423                             // fat-ptr -> fat-ptr
424                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
425                         } else {
426                             // fat-ptr -> thin-ptr
427                             let (ptr, _extra) = operand.load_scalar_pair(fx);
428                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
429                         }
430                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
431                         // enum -> discriminant value
432                         assert!(adt_def.is_enum());
433                         match to_ty.kind {
434                             ty::Uint(_) | ty::Int(_) => {}
435                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
436                         }
437
438                         let discr = crate::discriminant::codegen_get_discriminant(
439                             fx,
440                             operand,
441                             fx.layout_of(to_ty),
442                         );
443                         lval.write_cvalue(fx, discr);
444                     } else {
445                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
446                         let from = operand.load_scalar(fx);
447
448                         let res = clif_int_or_float_cast(
449                             fx,
450                             from,
451                             type_sign(from_ty),
452                             to_clif_ty,
453                             type_sign(to_ty),
454                         );
455                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
456                     }
457                 }
458                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
459                     let operand = trans_operand(fx, operand);
460                     match operand.layout().ty.kind {
461                         ty::Closure(def_id, substs) => {
462                             let instance = Instance::resolve_closure(
463                                 fx.tcx,
464                                 def_id,
465                                 substs,
466                                 ty::ClosureKind::FnOnce,
467                             );
468                             let func_ref = fx.get_function_ref(instance);
469                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
470                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
471                         }
472                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
473                     }
474                 }
475                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
476                     let operand = trans_operand(fx, operand);
477                     operand.unsize_value(fx, lval);
478                 }
479                 Rvalue::Discriminant(place) => {
480                     let place = trans_place(fx, place);
481                     let value = place.to_cvalue(fx);
482                     let discr =
483                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
484                     lval.write_cvalue(fx, discr);
485                 }
486                 Rvalue::Repeat(operand, times) => {
487                     let operand = trans_operand(fx, operand);
488                     for i in 0..*times {
489                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
490                         let to = lval.place_index(fx, index);
491                         to.write_cvalue(fx, operand);
492                     }
493                 }
494                 Rvalue::Len(place) => {
495                     let place = trans_place(fx, place);
496                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
497                     let len = codegen_array_len(fx, place);
498                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
499                 }
500                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
501                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
502
503                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
504                     let content_ty = fx.monomorphize(content_ty);
505                     let layout = fx.layout_of(content_ty);
506                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
507                     let llalign = fx
508                         .bcx
509                         .ins()
510                         .iconst(usize_type, layout.align.abi.bytes() as i64);
511                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
512
513                     // Allocate space:
514                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
515                         Ok(id) => id,
516                         Err(s) => {
517                             fx.tcx
518                                 .sess
519                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
520                         }
521                     };
522                     let instance = ty::Instance::mono(fx.tcx, def_id);
523                     let func_ref = fx.get_function_ref(instance);
524                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
525                     let ptr = fx.bcx.inst_results(call)[0];
526                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
527                 }
528                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
529                     assert!(lval
530                         .layout()
531                         .ty
532                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
533                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
534                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
535                     lval.write_cvalue(fx, val);
536                 }
537                 Rvalue::Aggregate(kind, operands) => match **kind {
538                     AggregateKind::Array(_ty) => {
539                         for (i, operand) in operands.into_iter().enumerate() {
540                             let operand = trans_operand(fx, operand);
541                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
542                             let to = lval.place_index(fx, index);
543                             to.write_cvalue(fx, operand);
544                         }
545                     }
546                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
547                 },
548             }
549         }
550         StatementKind::StorageLive(_)
551         | StatementKind::StorageDead(_)
552         | StatementKind::Nop
553         | StatementKind::FakeRead(..)
554         | StatementKind::Retag { .. }
555         | StatementKind::AscribeUserType(..) => {}
556
557         StatementKind::InlineAsm(asm) => {
558             use syntax::ast::Name;
559             let InlineAsm {
560                 asm,
561                 outputs: _,
562                 inputs: _,
563             } = &**asm;
564             let rustc_hir::InlineAsmInner {
565                 asm: asm_code, // Name
566                 outputs,       // Vec<Name>
567                 inputs,        // Vec<Name>
568                 clobbers,      // Vec<Name>
569                 volatile,      // bool
570                 alignstack,    // bool
571                 dialect: _,    // syntax::ast::AsmDialect
572                 asm_str_style: _,
573             } = asm;
574             match &*asm_code.as_str() {
575                 "" => {
576                     assert_eq!(inputs, &[Name::intern("r")]);
577                     assert!(outputs.is_empty(), "{:?}", outputs);
578
579                     // Black box
580                 }
581                 "cpuid" | "cpuid\n" => {
582                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
583
584                     assert_eq!(outputs.len(), 4);
585                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
586                         .iter()
587                         .enumerate()
588                     {
589                         assert_eq!(&outputs[i].constraint.as_str(), c);
590                         assert!(!outputs[i].is_rw);
591                         assert!(!outputs[i].is_indirect);
592                     }
593
594                     assert_eq!(clobbers, &[Name::intern("rbx")]);
595
596                     assert!(!volatile);
597                     assert!(!alignstack);
598
599                     crate::trap::trap_unimplemented(
600                         fx,
601                         "__cpuid_count arch intrinsic is not supported",
602                     );
603                 }
604                 "xgetbv" => {
605                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
606
607                     assert_eq!(outputs.len(), 2);
608                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
609                         assert_eq!(&outputs[i].constraint.as_str(), c);
610                         assert!(!outputs[i].is_rw);
611                         assert!(!outputs[i].is_indirect);
612                     }
613
614                     assert_eq!(clobbers, &[]);
615
616                     assert!(!volatile);
617                     assert!(!alignstack);
618
619                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
620                 }
621                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
622                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
623                 }
624                 _ => unimpl!("Inline assembly is not supported"),
625             }
626         }
627     }
628 }
629
630 fn codegen_array_len<'tcx>(
631     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
632     place: CPlace<'tcx>,
633 ) -> Value {
634     match place.layout().ty.kind {
635         ty::Array(_elem_ty, len) => {
636             let len = fx.monomorphize(&len)
637                 .eval(fx.tcx, ParamEnv::reveal_all())
638                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
639             fx.bcx.ins().iconst(fx.pointer_type, len)
640         }
641         ty::Slice(_elem_ty) => place
642             .to_ptr_maybe_unsized(fx)
643             .1
644             .expect("Length metadata for slice place"),
645         _ => bug!("Rvalue::Len({:?})", place),
646     }
647 }
648
649 pub fn trans_place<'tcx>(
650     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
651     place: &Place<'tcx>,
652 ) -> CPlace<'tcx> {
653     let mut cplace = fx.get_local_place(place.local);
654
655     for elem in &*place.projection {
656         match *elem {
657             PlaceElem::Deref => {
658                 cplace = cplace.place_deref(fx);
659             }
660             PlaceElem::Field(field, _ty) => {
661                 cplace = cplace.place_field(fx, field);
662             }
663             PlaceElem::Index(local) => {
664                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
665                 cplace = cplace.place_index(fx, index);
666             }
667             PlaceElem::ConstantIndex {
668                 offset,
669                 min_length: _,
670                 from_end,
671             } => {
672                 let index = if !from_end {
673                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
674                 } else {
675                     let len = codegen_array_len(fx, cplace);
676                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
677                 };
678                 cplace = cplace.place_index(fx, index);
679             }
680             PlaceElem::Subslice { from, to, from_end } => {
681                 // These indices are generated by slice patterns.
682                 // slice[from:-to] in Python terms.
683
684                 match cplace.layout().ty.kind {
685                     ty::Array(elem_ty, _len) => {
686                         assert!(!from_end, "array subslices are never `from_end`");
687                         let elem_layout = fx.layout_of(elem_ty);
688                         let ptr = cplace.to_ptr(fx);
689                         cplace = CPlace::for_ptr(
690                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
691                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
692                         );
693                     }
694                     ty::Slice(elem_ty) => {
695                         assert!(from_end, "slice subslices should be `from_end`");
696                         let elem_layout = fx.layout_of(elem_ty);
697                         let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
698                         let len = len.unwrap();
699                         cplace = CPlace::for_ptr_with_extra(
700                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
701                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
702                             cplace.layout(),
703                         );
704                     }
705                     _ => unreachable!(),
706                 }
707             }
708             PlaceElem::Downcast(_adt_def, variant) => {
709                 cplace = cplace.downcast_variant(fx, variant);
710             }
711         }
712     }
713
714     cplace
715 }
716
717 pub fn trans_operand<'tcx>(
718     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
719     operand: &Operand<'tcx>,
720 ) -> CValue<'tcx> {
721     match operand {
722         Operand::Move(place) | Operand::Copy(place) => {
723             let cplace = trans_place(fx, place);
724             cplace.to_cvalue(fx)
725         }
726         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
727     }
728 }