]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Don't omit overflow checks for *_with_overflow intrinsics when compiling without...
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2
3 use crate::prelude::*;
4
5 pub fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
6     cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7     instance: Instance<'tcx>,
8     linkage: Linkage,
9 ) {
10     let tcx = cx.tcx;
11
12     let mir = tcx.instance_mir(instance.def);
13
14     // Declare function
15     let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16     let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17     let mut debug_context = cx
18         .debug_context
19         .as_mut()
20         .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
21
22     // Make FunctionBuilder
23     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24     let mut func_ctx = FunctionBuilderContext::new();
25     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
26
27     // Predefine ebb's
28     let start_ebb = bcx.create_ebb();
29     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
30     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
31         ebb_map.insert(bb, bcx.create_ebb());
32     }
33
34     // Make FunctionCx
35     let pointer_type = cx.module.target_config().pointer_type();
36     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
37
38     let mut fx = FunctionCx {
39         tcx,
40         module: cx.module,
41         pointer_type,
42
43         instance,
44         mir,
45
46         bcx,
47         ebb_map,
48         local_map: HashMap::new(),
49
50         clif_comments,
51         constants: &mut cx.ccx,
52         caches: &mut cx.caches,
53         source_info_set: indexmap::IndexSet::new(),
54     };
55
56     with_unimpl_span(fx.mir.span, || {
57         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58         codegen_fn_content(&mut fx);
59     });
60
61     // Recover all necessary data from fx, before accessing func will prevent future access to it.
62     let instance = fx.instance;
63     let clif_comments = fx.clif_comments;
64     let source_info_set = fx.source_info_set;
65
66     #[cfg(debug_assertions)]
67     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
68
69     // Verify function
70     verify_func(tcx, &clif_comments, &func);
71
72     // Define function
73     let context = &mut cx.caches.context;
74     context.func = func;
75     cx.module
76         .define_function(func_id, context)
77         .unwrap();
78
79     let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
80
81     // Write optimized function to file for debugging
82     #[cfg(debug_assertions)]
83     crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
84
85     // Define debuginfo for function
86     let isa = cx.module.isa();
87     debug_context
88         .as_mut()
89         .map(|x| x.define(tcx, context, isa, &source_info_set));
90
91     // Clear context to make it usable for the next function
92     context.clear();
93 }
94
95 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
96     let flags = settings::Flags::new(settings::builder());
97     match ::cranelift::codegen::verify_function(&func, &flags) {
98         Ok(_) => {}
99         Err(err) => {
100             tcx.sess.err(&format!("{:?}", err));
101             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
102                 &func,
103                 None,
104                 Some(Box::new(writer)),
105                 err,
106             );
107             tcx.sess
108                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
109         }
110     }
111 }
112
113 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
114     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
115         if bb_data.is_cleanup {
116             // Unwinding after panicking is not supported
117             continue;
118         }
119
120         let ebb = fx.get_ebb(bb);
121         fx.bcx.switch_to_block(ebb);
122
123         fx.bcx.ins().nop();
124         for stmt in &bb_data.statements {
125             fx.set_debug_loc(stmt.source_info);
126             trans_stmt(fx, ebb, stmt);
127         }
128
129         #[cfg(debug_assertions)]
130         {
131             let mut terminator_head = "\n".to_string();
132             bb_data
133                 .terminator()
134                 .kind
135                 .fmt_head(&mut terminator_head)
136                 .unwrap();
137             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
138             fx.add_comment(inst, terminator_head);
139         }
140
141         fx.set_debug_loc(bb_data.terminator().source_info);
142
143         match &bb_data.terminator().kind {
144             TerminatorKind::Goto { target } => {
145                 let ebb = fx.get_ebb(*target);
146                 fx.bcx.ins().jump(ebb, &[]);
147             }
148             TerminatorKind::Return => {
149                 crate::abi::codegen_return(fx);
150             }
151             TerminatorKind::Assert {
152                 cond,
153                 expected,
154                 msg,
155                 target,
156                 cleanup: _,
157             } => {
158                 let cond = trans_operand(fx, cond).load_scalar(fx);
159                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
160                 let cond = fx.bcx.ins().uextend(types::I32, cond);
161                 let target = fx.get_ebb(*target);
162                 if *expected {
163                     fx.bcx.ins().brnz(cond, target, &[]);
164                 } else {
165                     fx.bcx.ins().brz(cond, target, &[]);
166                 };
167                 trap_panic(fx, format!("[panic] Assert {:?} at {:?} failed.", msg, bb_data.terminator().source_info.span));
168             }
169
170             TerminatorKind::SwitchInt {
171                 discr,
172                 switch_ty: _,
173                 values,
174                 targets,
175             } => {
176                 let discr = trans_operand(fx, discr).load_scalar(fx);
177                 let mut switch = ::cranelift::frontend::Switch::new();
178                 for (i, value) in values.iter().enumerate() {
179                     let ebb = fx.get_ebb(targets[i]);
180                     switch.set_entry(*value as u64, ebb);
181                 }
182                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
183                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
184             }
185             TerminatorKind::Call {
186                 func,
187                 args,
188                 destination,
189                 cleanup: _,
190                 from_hir_call: _,
191             } => {
192                 crate::abi::codegen_terminator_call(fx, func, args, destination);
193             }
194             TerminatorKind::Resume | TerminatorKind::Abort => {
195                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
196             }
197             TerminatorKind::Unreachable => {
198                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
199             }
200             TerminatorKind::Yield { .. }
201             | TerminatorKind::FalseEdges { .. }
202             | TerminatorKind::FalseUnwind { .. }
203             | TerminatorKind::DropAndReplace { .. }
204             | TerminatorKind::GeneratorDrop => {
205                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
206             }
207             TerminatorKind::Drop {
208                 location,
209                 target,
210                 unwind: _,
211             } => {
212                 let drop_place = trans_place(fx, location);
213                 crate::abi::codegen_drop(fx, drop_place);
214
215                 let target_ebb = fx.get_ebb(*target);
216                 fx.bcx.ins().jump(target_ebb, &[]);
217             }
218         };
219     }
220
221     fx.bcx.seal_all_blocks();
222     fx.bcx.finalize();
223 }
224
225 fn trans_stmt<'a, 'tcx: 'a>(
226     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
227     cur_ebb: Ebb,
228     stmt: &Statement<'tcx>,
229 ) {
230     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
231
232     fx.set_debug_loc(stmt.source_info);
233
234     #[cfg(debug_assertions)]
235     match &stmt.kind {
236         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
237         _ => {
238             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
239             fx.add_comment(inst, format!("{:?}", stmt));
240         }
241     }
242
243     match &stmt.kind {
244         StatementKind::SetDiscriminant {
245             place,
246             variant_index,
247         } => {
248             let place = trans_place(fx, place);
249             let layout = place.layout();
250             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
251                 return;
252             }
253             match layout.variants {
254                 layout::Variants::Single { index } => {
255                     assert_eq!(index, *variant_index);
256                 }
257                 layout::Variants::Multiple {
258                     discr: _,
259                     discr_index,
260                     discr_kind: layout::DiscriminantKind::Tag,
261                     variants: _,
262                 } => {
263                     let ptr = place.place_field(fx, mir::Field::new(discr_index));
264                     let to = layout
265                         .ty
266                         .discriminant_for_variant(fx.tcx, *variant_index)
267                         .unwrap()
268                         .val;
269                     let discr = CValue::const_val(fx, ptr.layout().ty, to);
270                     ptr.write_cvalue(fx, discr);
271                 }
272                 layout::Variants::Multiple {
273                     discr: _,
274                     discr_index,
275                     discr_kind: layout::DiscriminantKind::Niche {
276                         dataful_variant,
277                         ref niche_variants,
278                         niche_start,
279                     },
280                     variants: _,
281                 } => {
282                     if *variant_index != dataful_variant {
283                         let niche = place.place_field(fx, mir::Field::new(discr_index));
284                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
285                         let niche_value =
286                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
287                                 .wrapping_add(niche_start);
288                         // FIXME(eddyb) Check the actual primitive type here.
289                         let niche_llval = if niche_value == 0 {
290                             CValue::const_val(fx, niche.layout().ty, 0)
291                         } else {
292                             CValue::const_val(fx, niche.layout().ty, niche_value)
293                         };
294                         niche.write_cvalue(fx, niche_llval);
295                     }
296                 }
297             }
298         }
299         StatementKind::Assign(to_place, rval) => {
300             let lval = trans_place(fx, to_place);
301             let dest_layout = lval.layout();
302             match &**rval {
303                 Rvalue::Use(operand) => {
304                     let val = trans_operand(fx, operand);
305                     lval.write_cvalue(fx, val);
306                 }
307                 Rvalue::Ref(_, _, place) => {
308                     let place = trans_place(fx, place);
309                     place.write_place_ref(fx, lval);
310                 }
311                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
312                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
313                     let lhs = trans_operand(fx, lhs);
314                     let rhs = trans_operand(fx, rhs);
315
316                     let res = match ty.sty {
317                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs),
318                         ty::Uint(_) => {
319                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
320                         }
321                         ty::Int(_) => {
322                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
323                         }
324                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
325                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
326                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
327                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
328                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
329                     };
330                     lval.write_cvalue(fx, res);
331                 }
332                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
333                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
334                     let lhs = trans_operand(fx, lhs);
335                     let rhs = trans_operand(fx, rhs);
336
337                     let signed = match ty.sty {
338                         ty::Uint(_) => false,
339                         ty::Int(_) => true,
340                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
341                     };
342
343                     let res = if !fx.tcx.sess.overflow_checks() {
344                         let val = trans_int_binop(fx, *bin_op, lhs, rhs, lhs.layout().ty, signed).load_scalar(fx);
345                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
346                         CValue::by_val_pair(val, is_overflow, lval.layout())
347                     } else {
348                         trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, signed)
349                     };
350
351                     lval.write_cvalue(fx, res);
352                 }
353                 Rvalue::UnaryOp(un_op, operand) => {
354                     let operand = trans_operand(fx, operand);
355                     let layout = operand.layout();
356                     let val = operand.load_scalar(fx);
357                     let res = match un_op {
358                         UnOp::Not => {
359                             match layout.ty.sty {
360                                 ty::Bool => {
361                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
362                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
363                                     fx.bcx.ins().bint(types::I8, res)
364                                 }
365                                 ty::Uint(_) | ty::Int(_) => {
366                                     fx.bcx.ins().bnot(val)
367                                 }
368                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
369                             }
370                         }
371                         UnOp::Neg => match layout.ty.sty {
372                             ty::Int(_) => {
373                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
374                                 if clif_ty == types::I128 {
375                                     crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
376                                 } else {
377                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
378                                     fx.bcx.ins().isub(zero, val)
379                                 }
380                             }
381                             ty::Float(_) => fx.bcx.ins().fneg(val),
382                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
383                         },
384                     };
385                     lval.write_cvalue(fx, CValue::by_val(res, layout));
386                 }
387                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
388                     let layout = fx.layout_of(ty);
389                     match fx
390                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
391                         .sty
392                     {
393                         ty::FnDef(def_id, substs) => {
394                             let func_ref = fx.get_function_ref(
395                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
396                                     .unwrap(),
397                             );
398                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
399                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
400                         }
401                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
402                     }
403                 }
404                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
405                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
406                     let operand = trans_operand(fx, operand);
407                     let layout = fx.layout_of(ty);
408                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
409                 }
410                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
411                     let operand = trans_operand(fx, operand);
412                     let from_ty = operand.layout().ty;
413
414                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
415                         ty
416                             .builtin_deref(true)
417                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
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.sty {
431                         // enum -> discriminant value
432                         assert!(adt_def.is_enum());
433                         match to_ty.sty {
434                             ty::Uint(_) | ty::Int(_) => {},
435                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
436                         }
437
438                         // FIXME avoid forcing to stack
439                         let place =
440                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
441                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
442                         lval.write_cvalue(fx, discr);
443                     } else {
444                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
445                         let from = operand.load_scalar(fx);
446
447                         let signed = match from_ty.sty {
448                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
449                             ty::Int(..) => true,
450                             ty::Float(..) => false, // `signed` is unused for floats
451                             _ => panic!("{}", from_ty),
452                         };
453
454                         let res = clif_int_or_float_cast(fx, from, to_clif_ty, signed);
455                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
456                     }
457                 }
458                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
459                     let operand = trans_operand(fx, operand);
460                     match operand.layout().ty.sty {
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                         _ => {
473                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
474                         }
475                     }
476                 }
477                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
478                     let operand = trans_operand(fx, operand);
479                     operand.unsize_value(fx, lval);
480                 }
481                 Rvalue::Discriminant(place) => {
482                     let place = trans_place(fx, place);
483                     let discr = trans_get_discriminant(fx, place, 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 layout = fx.layout_of(content_ty);
505                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
506                     let llalign = fx
507                         .bcx
508                         .ins()
509                         .iconst(usize_type, layout.align.abi.bytes() as i64);
510                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
511
512                     // Allocate space:
513                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
514                         Ok(id) => id,
515                         Err(s) => {
516                             fx.tcx
517                                 .sess
518                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
519                         }
520                     };
521                     let instance = ty::Instance::mono(fx.tcx, def_id);
522                     let func_ref = fx.get_function_ref(instance);
523                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
524                     let ptr = fx.bcx.inst_results(call)[0];
525                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
526                 }
527                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
528                     assert!(lval
529                         .layout()
530                         .ty
531                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
532                     let ty_size = fx.layout_of(ty).size.bytes();
533                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
534                     lval.write_cvalue(fx, val);
535                 }
536                 Rvalue::Aggregate(kind, operands) => match **kind {
537                     AggregateKind::Array(_ty) => {
538                         for (i, operand) in operands.into_iter().enumerate() {
539                             let operand = trans_operand(fx, operand);
540                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
541                             let to = lval.place_index(fx, index);
542                             to.write_cvalue(fx, operand);
543                         }
544                     }
545                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
546                 },
547             }
548         }
549         StatementKind::StorageLive(_)
550         | StatementKind::StorageDead(_)
551         | StatementKind::Nop
552         | StatementKind::FakeRead(..)
553         | StatementKind::Retag { .. }
554         | StatementKind::AscribeUserType(..) => {}
555
556         StatementKind::InlineAsm(asm) => {
557             use syntax::ast::Name;
558             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
559             let rustc::hir::InlineAsm {
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                 ctxt: _,
569             } = asm;
570             match &*asm_code.as_str() {
571                 "cpuid" | "cpuid\n" => {
572                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
573
574                     assert_eq!(outputs.len(), 4);
575                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
576                         assert_eq!(&outputs[i].constraint.as_str(), c);
577                         assert!(!outputs[i].is_rw);
578                         assert!(!outputs[i].is_indirect);
579                     }
580
581                     assert_eq!(clobbers, &[Name::intern("rbx")]);
582
583                     assert!(!volatile);
584                     assert!(!alignstack);
585
586                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
587                 }
588                 "xgetbv" => {
589                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
590
591                     assert_eq!(outputs.len(), 2);
592                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
593                         assert_eq!(&outputs[i].constraint.as_str(), c);
594                         assert!(!outputs[i].is_rw);
595                         assert!(!outputs[i].is_indirect);
596                     }
597
598                     assert_eq!(clobbers, &[]);
599
600                     assert!(!volatile);
601                     assert!(!alignstack);
602
603                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
604                 }
605                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
606                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
607                 }
608                 _ => unimpl!("Inline assembly is not supported"),
609             }
610         }
611     }
612 }
613
614 fn codegen_array_len<'a, 'tcx: 'a>(
615     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
616     place: CPlace<'tcx>,
617 ) -> Value {
618     match place.layout().ty.sty {
619         ty::Array(_elem_ty, len) => {
620             let len = crate::constant::force_eval_const(fx, len)
621                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
622             fx.bcx.ins().iconst(fx.pointer_type, len)
623         }
624         ty::Slice(_elem_ty) => place
625             .to_addr_maybe_unsized(fx)
626             .1
627             .expect("Length metadata for slice place"),
628         _ => bug!("Rvalue::Len({:?})", place),
629     }
630 }
631
632 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
633     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
634     place: CPlace<'tcx>,
635     dest_layout: TyLayout<'tcx>,
636 ) -> CValue<'tcx> {
637     let layout = place.layout();
638
639     if layout.abi == layout::Abi::Uninhabited {
640         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
641     }
642
643     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
644         layout::Variants::Single { index } => {
645             let discr_val = layout
646                 .ty
647                 .ty_adt_def()
648                 .map_or(index.as_u32() as u128, |def| {
649                     def.discriminant_for_variant(fx.tcx, *index).val
650                 });
651             return CValue::const_val(fx, dest_layout.ty, discr_val);
652         }
653         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
654             (discr, *discr_index, discr_kind)
655         }
656     };
657
658     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
659     let discr_ty = discr.layout().ty;
660     let lldiscr = discr.load_scalar(fx);
661     match discr_kind {
662         layout::DiscriminantKind::Tag => {
663             let signed = match discr_scalar.value {
664                 layout::Int(_, signed) => signed,
665                 _ => false,
666             };
667             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
668             return CValue::by_val(val, dest_layout);
669         }
670         layout::DiscriminantKind::Niche {
671             dataful_variant,
672             ref niche_variants,
673             niche_start,
674         } => {
675             let niche_llty = fx.clif_type(discr_ty).unwrap();
676             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
677             if niche_variants.start() == niche_variants.end() {
678                 let b = fx
679                     .bcx
680                     .ins()
681                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
682                 let if_true = fx
683                     .bcx
684                     .ins()
685                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
686                 let if_false = fx
687                     .bcx
688                     .ins()
689                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
690                 let val = fx.bcx.ins().select(b, if_true, if_false);
691                 return CValue::by_val(val, dest_layout);
692             } else {
693                 // Rebase from niche values to discriminant values.
694                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
695                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
696                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
697                 let b = fx.bcx.ins().icmp_imm(
698                     IntCC::UnsignedLessThanOrEqual,
699                     lldiscr,
700                     niche_variants.end().as_u32() as i64,
701                 );
702                 let if_true =
703                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
704                 let if_false = fx
705                     .bcx
706                     .ins()
707                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
708                 let val = fx.bcx.ins().select(b, if_true, if_false);
709                 return CValue::by_val(val, dest_layout);
710             }
711         }
712     }
713 }
714
715 macro_rules! binop_match {
716     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
717         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
718     };
719     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
720         assert_eq!($fx.tcx.types.bool, $ret_ty);
721         let ret_layout = $fx.layout_of($ret_ty);
722
723         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
724         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
725     }};
726     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
727         assert_eq!($fx.tcx.types.bool, $ret_ty);
728         let ret_layout = $fx.layout_of($ret_ty);
729         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
730         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
731     }};
732     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
733         $body
734     }};
735     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
736         let ret_layout = $fx.layout_of($ret_ty);
737         CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
738     }};
739     (
740         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
741         $(
742             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
743         )*
744     ) => {{
745         let lhs = $lhs.load_scalar($fx);
746         let rhs = $rhs.load_scalar($fx);
747         match ($bin_op, $signed) {
748             $(
749                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
750             )*
751         }
752     }}
753 }
754
755 fn trans_bool_binop<'a, 'tcx: 'a>(
756     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
757     bin_op: BinOp,
758     lhs: CValue<'tcx>,
759     rhs: CValue<'tcx>,
760 ) -> CValue<'tcx> {
761     let res = binop_match! {
762         fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "bool";
763         Add (_) bug;
764         Sub (_) bug;
765         Mul (_) bug;
766         Div (_) bug;
767         Rem (_) bug;
768         BitXor (_) bxor;
769         BitAnd (_) band;
770         BitOr (_) bor;
771         Shl (_) bug;
772         Shr (_) bug;
773
774         Eq (_) icmp(Equal);
775         Lt (_) icmp(UnsignedLessThan);
776         Le (_) icmp(UnsignedLessThanOrEqual);
777         Ne (_) icmp(NotEqual);
778         Ge (_) icmp(UnsignedGreaterThanOrEqual);
779         Gt (_) icmp(UnsignedGreaterThan);
780
781         Offset (_) bug;
782     };
783
784     res
785 }
786
787 pub fn trans_int_binop<'a, 'tcx: 'a>(
788     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
789     bin_op: BinOp,
790     lhs: CValue<'tcx>,
791     rhs: CValue<'tcx>,
792     out_ty: Ty<'tcx>,
793     signed: bool,
794 ) -> CValue<'tcx> {
795     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
796         assert_eq!(
797             lhs.layout().ty,
798             rhs.layout().ty,
799             "int binop requires lhs and rhs of same type"
800         );
801     }
802
803     match out_ty.sty {
804         ty::Bool | ty::Uint(_) | ty::Int(_) => {}
805         _ => unreachable!("Out ty {:?} is not an integer or bool", out_ty),
806     }
807
808     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, false, signed, lhs, rhs, out_ty) {
809         return res;
810     }
811
812     binop_match! {
813         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
814         Add (_) iadd;
815         Sub (_) isub;
816         Mul (_) imul;
817         Div (false) udiv;
818         Div (true) sdiv;
819         Rem (false) urem;
820         Rem (true) srem;
821         BitXor (_) bxor;
822         BitAnd (_) band;
823         BitOr (_) bor;
824         Shl (_) ishl;
825         Shr (false) ushr;
826         Shr (true) sshr;
827
828         Eq (_) icmp(Equal);
829         Lt (false) icmp(UnsignedLessThan);
830         Lt (true) icmp(SignedLessThan);
831         Le (false) icmp(UnsignedLessThanOrEqual);
832         Le (true) icmp(SignedLessThanOrEqual);
833         Ne (_) icmp(NotEqual);
834         Ge (false) icmp(UnsignedGreaterThanOrEqual);
835         Ge (true) icmp(SignedGreaterThanOrEqual);
836         Gt (false) icmp(UnsignedGreaterThan);
837         Gt (true) icmp(SignedGreaterThan);
838
839         Offset (_) bug;
840     }
841 }
842
843 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
844     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
845     bin_op: BinOp,
846     in_lhs: CValue<'tcx>,
847     in_rhs: CValue<'tcx>,
848     out_ty: Ty<'tcx>,
849     signed: bool,
850 ) -> CValue<'tcx> {
851     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
852         assert_eq!(
853             in_lhs.layout().ty,
854             in_rhs.layout().ty,
855             "checked int binop requires lhs and rhs of same type"
856         );
857     }
858
859     let lhs = in_lhs.load_scalar(fx);
860     let rhs = in_rhs.load_scalar(fx);
861
862     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, true, signed, in_lhs, in_rhs, out_ty) {
863         return res;
864     }
865
866     let (res, has_overflow) = match bin_op {
867         BinOp::Add => {
868             /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
869             (val, c_out)*/
870             // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
871             let val = fx.bcx.ins().iadd(lhs, rhs);
872             let has_overflow = if !signed {
873                 fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
874             } else {
875                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
876                 let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
877                 fx.bcx.ins().bxor(rhs_is_negative, slt)
878             };
879             (val, has_overflow)
880         }
881         BinOp::Sub => {
882             /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
883             (val, b_out)*/
884             // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
885             let val = fx.bcx.ins().isub(lhs, rhs);
886             let has_overflow = if !signed {
887                 fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
888             } else {
889                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
890                 let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
891                 fx.bcx.ins().bxor(rhs_is_negative, sgt)
892             };
893             (val, has_overflow)
894         }
895         BinOp::Mul => {
896             let val = fx.bcx.ins().imul(lhs, rhs);
897             /*let val_hi = if !signed {
898                 fx.bcx.ins().umulhi(lhs, rhs)
899             } else {
900                 fx.bcx.ins().smulhi(lhs, rhs)
901             };
902             let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
903             // TODO: check for overflow
904             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
905             (val, has_overflow)
906         }
907         BinOp::Shl => {
908             let val = fx.bcx.ins().ishl(lhs, rhs);
909             // TODO: check for overflow
910             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
911             (val, has_overflow)
912         }
913         BinOp::Shr => {
914             let val = if !signed {
915                 fx.bcx.ins().ushr(lhs, rhs)
916             } else {
917                 fx.bcx.ins().sshr(lhs, rhs)
918             };
919             // TODO: check for overflow
920             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
921             (val, has_overflow)
922         }
923         _ => bug!(
924             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
925             bin_op,
926             in_lhs,
927             in_rhs
928         ),
929     };
930
931     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
932     let out_place = CPlace::new_stack_slot(fx, out_ty);
933     let out_layout = out_place.layout();
934     out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
935
936     out_place.to_cvalue(fx)
937 }
938
939 fn trans_float_binop<'a, 'tcx: 'a>(
940     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
941     bin_op: BinOp,
942     lhs: CValue<'tcx>,
943     rhs: CValue<'tcx>,
944     ty: Ty<'tcx>,
945 ) -> CValue<'tcx> {
946     let res = binop_match! {
947         fx, bin_op, false, lhs, rhs, ty, "float";
948         Add (_) fadd;
949         Sub (_) fsub;
950         Mul (_) fmul;
951         Div (_) fdiv;
952         Rem (_) custom(|| {
953             assert_eq!(lhs.layout().ty, ty);
954             assert_eq!(rhs.layout().ty, ty);
955             match ty.sty {
956                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
957                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
958                 _ => bug!(),
959             }
960         });
961         BitXor (_) bxor;
962         BitAnd (_) band;
963         BitOr (_) bor;
964         Shl (_) bug;
965         Shr (_) bug;
966
967         Eq (_) fcmp(Equal);
968         Lt (_) fcmp(LessThan);
969         Le (_) fcmp(LessThanOrEqual);
970         Ne (_) fcmp(NotEqual);
971         Ge (_) fcmp(GreaterThanOrEqual);
972         Gt (_) fcmp(GreaterThan);
973
974         Offset (_) bug;
975     };
976
977     res
978 }
979
980 fn trans_char_binop<'a, 'tcx: 'a>(
981     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
982     bin_op: BinOp,
983     lhs: CValue<'tcx>,
984     rhs: CValue<'tcx>,
985     ty: Ty<'tcx>,
986 ) -> CValue<'tcx> {
987     let res = binop_match! {
988         fx, bin_op, false, lhs, rhs, ty, "char";
989         Add (_) bug;
990         Sub (_) bug;
991         Mul (_) bug;
992         Div (_) bug;
993         Rem (_) bug;
994         BitXor (_) bug;
995         BitAnd (_) bug;
996         BitOr (_) bug;
997         Shl (_) bug;
998         Shr (_) bug;
999
1000         Eq (_) icmp(Equal);
1001         Lt (_) icmp(UnsignedLessThan);
1002         Le (_) icmp(UnsignedLessThanOrEqual);
1003         Ne (_) icmp(NotEqual);
1004         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1005         Gt (_) icmp(UnsignedGreaterThan);
1006
1007         Offset (_) bug;
1008     };
1009
1010     res
1011 }
1012
1013 fn trans_ptr_binop<'a, 'tcx: 'a>(
1014     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1015     bin_op: BinOp,
1016     lhs: CValue<'tcx>,
1017     rhs: CValue<'tcx>,
1018     ret_ty: Ty<'tcx>,
1019 ) -> CValue<'tcx> {
1020     let not_fat = match lhs.layout().ty.sty {
1021         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1022             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1023         }
1024         ty::FnPtr(..) => true,
1025         _ => bug!("trans_ptr_binop on non ptr"),
1026     };
1027     if not_fat {
1028         if let BinOp::Offset = bin_op {
1029             let (base, offset) = (lhs, rhs.load_scalar(fx));
1030             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1031             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1032             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1033             let base_val = base.load_scalar(fx);
1034             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1035             return CValue::by_val(res, base.layout());
1036         }
1037
1038         binop_match! {
1039             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1040             Add (_) bug;
1041             Sub (_) bug;
1042             Mul (_) bug;
1043             Div (_) bug;
1044             Rem (_) bug;
1045             BitXor (_) bug;
1046             BitAnd (_) bug;
1047             BitOr (_) bug;
1048             Shl (_) bug;
1049             Shr (_) bug;
1050
1051             Eq (_) icmp(Equal);
1052             Lt (_) icmp(UnsignedLessThan);
1053             Le (_) icmp(UnsignedLessThanOrEqual);
1054             Ne (_) icmp(NotEqual);
1055             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1056             Gt (_) icmp(UnsignedGreaterThan);
1057
1058             Offset (_) bug; // Handled above
1059         }
1060     } else {
1061         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1062         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1063
1064         let res = match bin_op {
1065             BinOp::Eq => {
1066                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1067                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1068                 fx.bcx.ins().band(ptr_eq, extra_eq)
1069             }
1070             BinOp::Ne => {
1071                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1072                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1073                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1074             }
1075             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1076                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1077
1078                 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1079                     BinOp::Lt => IntCC::UnsignedLessThan,
1080                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1081                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1082                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1083                     _ => unreachable!(),
1084                 }, lhs_ptr, rhs_ptr);
1085
1086                 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1087                     BinOp::Lt => IntCC::UnsignedLessThan,
1088                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1089                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1090                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1091                     _ => unreachable!(),
1092                 }, lhs_extra, rhs_extra);
1093
1094                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1095             }
1096             _ => panic!("bin_op {:?} on ptr", bin_op),
1097         };
1098
1099         assert_eq!(fx.tcx.types.bool, ret_ty);
1100         let ret_layout = fx.layout_of(ret_ty);
1101         CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1102     }
1103 }
1104
1105 pub fn trans_place<'a, 'tcx: 'a>(
1106     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1107     place: &Place<'tcx>,
1108 ) -> CPlace<'tcx> {
1109     let base = match &place.base {
1110         PlaceBase::Local(local) => fx.get_local_place(*local),
1111         PlaceBase::Static(static_) => match static_.kind {
1112             StaticKind::Static(def_id) => {
1113                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1114             }
1115             StaticKind::Promoted(promoted) => {
1116                 crate::constant::trans_promoted(fx, promoted, static_.ty)
1117             }
1118         }
1119     };
1120
1121     trans_place_projection(fx, base, &place.projection)
1122 }
1123
1124 pub fn trans_place_projection<'a, 'tcx: 'a>(
1125     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1126     base: CPlace<'tcx>,
1127     projection: &Option<Box<Projection<'tcx>>>,
1128 ) -> CPlace<'tcx> {
1129     let projection = if let Some(projection) = projection {
1130         projection
1131     } else {
1132         return base;
1133     };
1134
1135     let base = trans_place_projection(fx, base, &projection.base);
1136
1137     match projection.elem {
1138         ProjectionElem::Deref => base.place_deref(fx),
1139         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1140         ProjectionElem::Index(local) => {
1141             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1142             base.place_index(fx, index)
1143         }
1144         ProjectionElem::ConstantIndex {
1145             offset,
1146             min_length: _,
1147             from_end,
1148         } => {
1149             let index = if !from_end {
1150                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1151             } else {
1152                 let len = codegen_array_len(fx, base);
1153                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1154             };
1155             base.place_index(fx, index)
1156         }
1157         ProjectionElem::Subslice { from, to } => {
1158             // These indices are generated by slice patterns.
1159             // slice[from:-to] in Python terms.
1160
1161             match base.layout().ty.sty {
1162                 ty::Array(elem_ty, len) => {
1163                     let elem_layout = fx.layout_of(elem_ty);
1164                     let ptr = base.to_addr(fx);
1165                     let len = crate::constant::force_eval_const(fx, len)
1166                         .eval_usize(fx.tcx, ParamEnv::reveal_all());
1167                     CPlace::for_addr(
1168                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1169                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1170                     )
1171                 }
1172                 ty::Slice(elem_ty) => {
1173                     let elem_layout = fx.layout_of(elem_ty);
1174                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
1175                     let len = len.unwrap();
1176                     CPlace::for_addr_with_extra(
1177                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1178                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1179                         base.layout(),
1180                     )
1181                 }
1182                 _ => unreachable!(),
1183             }
1184         }
1185         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1186     }
1187 }
1188
1189 pub fn trans_operand<'a, 'tcx>(
1190     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1191     operand: &Operand<'tcx>,
1192 ) -> CValue<'tcx> {
1193     match operand {
1194         Operand::Move(place) | Operand::Copy(place) => {
1195             let cplace = trans_place(fx, place);
1196             cplace.to_cvalue(fx)
1197         }
1198         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1199     }
1200 }