]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.38.0-nightly (6a91782b7 2019-08-06)
[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 res = match ty.sty {
338                         ty::Uint(_) => {
339                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
340                         }
341                         ty::Int(_) => {
342                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
343                         }
344                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
345                     };
346                     lval.write_cvalue(fx, res);
347                 }
348                 Rvalue::UnaryOp(un_op, operand) => {
349                     let operand = trans_operand(fx, operand);
350                     let layout = operand.layout();
351                     let val = operand.load_scalar(fx);
352                     let res = match un_op {
353                         UnOp::Not => {
354                             match layout.ty.sty {
355                                 ty::Bool => {
356                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
357                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
358                                     fx.bcx.ins().bint(types::I8, res)
359                                 }
360                                 ty::Uint(_) | ty::Int(_) => {
361                                     fx.bcx.ins().bnot(val)
362                                 }
363                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
364                             }
365                         }
366                         UnOp::Neg => match layout.ty.sty {
367                             ty::Int(_) => {
368                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
369                                 if clif_ty == types::I128 {
370                                     crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
371                                 } else {
372                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
373                                     fx.bcx.ins().isub(zero, val)
374                                 }
375                             }
376                             ty::Float(_) => fx.bcx.ins().fneg(val),
377                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
378                         },
379                     };
380                     lval.write_cvalue(fx, CValue::by_val(res, layout));
381                 }
382                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
383                     let layout = fx.layout_of(ty);
384                     match fx
385                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
386                         .sty
387                     {
388                         ty::FnDef(def_id, substs) => {
389                             let func_ref = fx.get_function_ref(
390                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
391                                     .unwrap(),
392                             );
393                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
394                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
395                         }
396                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
397                     }
398                 }
399                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
400                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
401                     let operand = trans_operand(fx, operand);
402                     let layout = fx.layout_of(ty);
403                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
404                 }
405                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
406                     let operand = trans_operand(fx, operand);
407                     let from_ty = operand.layout().ty;
408
409                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
410                         ty
411                             .builtin_deref(true)
412                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
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.sty {
426                         // enum -> discriminant value
427                         assert!(adt_def.is_enum());
428                         match to_ty.sty {
429                             ty::Uint(_) | ty::Int(_) => {},
430                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
431                         }
432
433                         // FIXME avoid forcing to stack
434                         let place =
435                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
436                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
437                         lval.write_cvalue(fx, discr);
438                     } else {
439                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
440                         let from = operand.load_scalar(fx);
441
442                         let signed = match from_ty.sty {
443                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
444                             ty::Int(..) => true,
445                             ty::Float(..) => false, // `signed` is unused for floats
446                             _ => panic!("{}", from_ty),
447                         };
448
449                         let res = clif_int_or_float_cast(fx, from, to_clif_ty, signed);
450                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
451                     }
452                 }
453                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
454                     let operand = trans_operand(fx, operand);
455                     match operand.layout().ty.sty {
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                         _ => {
468                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
469                         }
470                     }
471                 }
472                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
473                     let operand = trans_operand(fx, operand);
474                     operand.unsize_value(fx, lval);
475                 }
476                 Rvalue::Discriminant(place) => {
477                     let place = trans_place(fx, place);
478                     let discr = trans_get_discriminant(fx, place, 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 layout = fx.layout_of(content_ty);
500                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
501                     let llalign = fx
502                         .bcx
503                         .ins()
504                         .iconst(usize_type, layout.align.abi.bytes() as i64);
505                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
506
507                     // Allocate space:
508                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
509                         Ok(id) => id,
510                         Err(s) => {
511                             fx.tcx
512                                 .sess
513                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
514                         }
515                     };
516                     let instance = ty::Instance::mono(fx.tcx, def_id);
517                     let func_ref = fx.get_function_ref(instance);
518                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
519                     let ptr = fx.bcx.inst_results(call)[0];
520                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
521                 }
522                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
523                     assert!(lval
524                         .layout()
525                         .ty
526                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
527                     let ty_size = fx.layout_of(ty).size.bytes();
528                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
529                     lval.write_cvalue(fx, val);
530                 }
531                 Rvalue::Aggregate(kind, operands) => match **kind {
532                     AggregateKind::Array(_ty) => {
533                         for (i, operand) in operands.into_iter().enumerate() {
534                             let operand = trans_operand(fx, operand);
535                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
536                             let to = lval.place_index(fx, index);
537                             to.write_cvalue(fx, operand);
538                         }
539                     }
540                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
541                 },
542             }
543         }
544         StatementKind::StorageLive(_)
545         | StatementKind::StorageDead(_)
546         | StatementKind::Nop
547         | StatementKind::FakeRead(..)
548         | StatementKind::Retag { .. }
549         | StatementKind::AscribeUserType(..) => {}
550
551         StatementKind::InlineAsm(asm) => {
552             use syntax::ast::Name;
553             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
554             let rustc::hir::InlineAsm {
555                 asm: asm_code, // Name
556                 outputs, // Vec<Name>
557                 inputs, // Vec<Name>
558                 clobbers, // Vec<Name>
559                 volatile, // bool
560                 alignstack, // bool
561                 dialect: _, // syntax::ast::AsmDialect
562                 asm_str_style: _,
563                 ctxt: _,
564             } = asm;
565             match &*asm_code.as_str() {
566                 "cpuid" | "cpuid\n" => {
567                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
568
569                     assert_eq!(outputs.len(), 4);
570                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
571                         assert_eq!(&outputs[i].constraint.as_str(), c);
572                         assert!(!outputs[i].is_rw);
573                         assert!(!outputs[i].is_indirect);
574                     }
575
576                     assert_eq!(clobbers, &[Name::intern("rbx")]);
577
578                     assert!(!volatile);
579                     assert!(!alignstack);
580
581                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
582                 }
583                 "xgetbv" => {
584                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
585
586                     assert_eq!(outputs.len(), 2);
587                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
588                         assert_eq!(&outputs[i].constraint.as_str(), c);
589                         assert!(!outputs[i].is_rw);
590                         assert!(!outputs[i].is_indirect);
591                     }
592
593                     assert_eq!(clobbers, &[]);
594
595                     assert!(!volatile);
596                     assert!(!alignstack);
597
598                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
599                 }
600                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
601                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
602                 }
603                 _ => unimpl!("Inline assembly is not supported"),
604             }
605         }
606     }
607 }
608
609 fn codegen_array_len<'a, 'tcx: 'a>(
610     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
611     place: CPlace<'tcx>,
612 ) -> Value {
613     match place.layout().ty.sty {
614         ty::Array(_elem_ty, len) => {
615             let len = crate::constant::force_eval_const(fx, len)
616                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
617             fx.bcx.ins().iconst(fx.pointer_type, len)
618         }
619         ty::Slice(_elem_ty) => place
620             .to_addr_maybe_unsized(fx)
621             .1
622             .expect("Length metadata for slice place"),
623         _ => bug!("Rvalue::Len({:?})", place),
624     }
625 }
626
627 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
628     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
629     place: CPlace<'tcx>,
630     dest_layout: TyLayout<'tcx>,
631 ) -> CValue<'tcx> {
632     let layout = place.layout();
633
634     if layout.abi == layout::Abi::Uninhabited {
635         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
636     }
637
638     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
639         layout::Variants::Single { index } => {
640             let discr_val = layout
641                 .ty
642                 .ty_adt_def()
643                 .map_or(index.as_u32() as u128, |def| {
644                     def.discriminant_for_variant(fx.tcx, *index).val
645                 });
646             return CValue::const_val(fx, dest_layout.ty, discr_val);
647         }
648         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
649             (discr, *discr_index, discr_kind)
650         }
651     };
652
653     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
654     let discr_ty = discr.layout().ty;
655     let lldiscr = discr.load_scalar(fx);
656     match discr_kind {
657         layout::DiscriminantKind::Tag => {
658             let signed = match discr_scalar.value {
659                 layout::Int(_, signed) => signed,
660                 _ => false,
661             };
662             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
663             return CValue::by_val(val, dest_layout);
664         }
665         layout::DiscriminantKind::Niche {
666             dataful_variant,
667             ref niche_variants,
668             niche_start,
669         } => {
670             let niche_llty = fx.clif_type(discr_ty).unwrap();
671             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
672             if niche_variants.start() == niche_variants.end() {
673                 let b = fx
674                     .bcx
675                     .ins()
676                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
677                 let if_true = fx
678                     .bcx
679                     .ins()
680                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
681                 let if_false = fx
682                     .bcx
683                     .ins()
684                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
685                 let val = fx.bcx.ins().select(b, if_true, if_false);
686                 return CValue::by_val(val, dest_layout);
687             } else {
688                 // Rebase from niche values to discriminant values.
689                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
690                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
691                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
692                 let b = fx.bcx.ins().icmp_imm(
693                     IntCC::UnsignedLessThanOrEqual,
694                     lldiscr,
695                     niche_variants.end().as_u32() as i64,
696                 );
697                 let if_true =
698                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
699                 let if_false = fx
700                     .bcx
701                     .ins()
702                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
703                 let val = fx.bcx.ins().select(b, if_true, if_false);
704                 return CValue::by_val(val, dest_layout);
705             }
706         }
707     }
708 }
709
710 macro_rules! binop_match {
711     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
712         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
713     };
714     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
715         assert_eq!($fx.tcx.types.bool, $ret_ty);
716         let ret_layout = $fx.layout_of($ret_ty);
717
718         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
719         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
720     }};
721     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
722         assert_eq!($fx.tcx.types.bool, $ret_ty);
723         let ret_layout = $fx.layout_of($ret_ty);
724         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
725         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
726     }};
727     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
728         $body
729     }};
730     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
731         let ret_layout = $fx.layout_of($ret_ty);
732         CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
733     }};
734     (
735         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
736         $(
737             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
738         )*
739     ) => {{
740         let lhs = $lhs.load_scalar($fx);
741         let rhs = $rhs.load_scalar($fx);
742         match ($bin_op, $signed) {
743             $(
744                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
745             )*
746         }
747     }}
748 }
749
750 fn trans_bool_binop<'a, 'tcx: 'a>(
751     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
752     bin_op: BinOp,
753     lhs: CValue<'tcx>,
754     rhs: CValue<'tcx>,
755 ) -> CValue<'tcx> {
756     let res = binop_match! {
757         fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "bool";
758         Add (_) bug;
759         Sub (_) bug;
760         Mul (_) bug;
761         Div (_) bug;
762         Rem (_) bug;
763         BitXor (_) bxor;
764         BitAnd (_) band;
765         BitOr (_) bor;
766         Shl (_) bug;
767         Shr (_) bug;
768
769         Eq (_) icmp(Equal);
770         Lt (_) icmp(UnsignedLessThan);
771         Le (_) icmp(UnsignedLessThanOrEqual);
772         Ne (_) icmp(NotEqual);
773         Ge (_) icmp(UnsignedGreaterThanOrEqual);
774         Gt (_) icmp(UnsignedGreaterThan);
775
776         Offset (_) bug;
777     };
778
779     res
780 }
781
782 pub fn trans_int_binop<'a, 'tcx: 'a>(
783     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
784     bin_op: BinOp,
785     lhs: CValue<'tcx>,
786     rhs: CValue<'tcx>,
787     out_ty: Ty<'tcx>,
788     signed: bool,
789 ) -> CValue<'tcx> {
790     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
791         assert_eq!(
792             lhs.layout().ty,
793             rhs.layout().ty,
794             "int binop requires lhs and rhs of same type"
795         );
796     }
797
798     match out_ty.sty {
799         ty::Bool | ty::Uint(_) | ty::Int(_) => {}
800         _ => unreachable!("Out ty {:?} is not an integer or bool", out_ty),
801     }
802
803     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, false, signed, lhs, rhs, out_ty) {
804         return res;
805     }
806
807     binop_match! {
808         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
809         Add (_) iadd;
810         Sub (_) isub;
811         Mul (_) imul;
812         Div (false) udiv;
813         Div (true) sdiv;
814         Rem (false) urem;
815         Rem (true) srem;
816         BitXor (_) bxor;
817         BitAnd (_) band;
818         BitOr (_) bor;
819         Shl (_) ishl;
820         Shr (false) ushr;
821         Shr (true) sshr;
822
823         Eq (_) icmp(Equal);
824         Lt (false) icmp(UnsignedLessThan);
825         Lt (true) icmp(SignedLessThan);
826         Le (false) icmp(UnsignedLessThanOrEqual);
827         Le (true) icmp(SignedLessThanOrEqual);
828         Ne (_) icmp(NotEqual);
829         Ge (false) icmp(UnsignedGreaterThanOrEqual);
830         Ge (true) icmp(SignedGreaterThanOrEqual);
831         Gt (false) icmp(UnsignedGreaterThan);
832         Gt (true) icmp(SignedGreaterThan);
833
834         Offset (_) bug;
835     }
836 }
837
838 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
839     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
840     bin_op: BinOp,
841     in_lhs: CValue<'tcx>,
842     in_rhs: CValue<'tcx>,
843     out_ty: Ty<'tcx>,
844     signed: bool,
845 ) -> CValue<'tcx> {
846     if !fx.tcx.sess.overflow_checks() {
847         let val = trans_int_binop(fx, bin_op, in_lhs, in_rhs, in_lhs.layout().ty, signed).load_scalar(fx);
848         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
849         return CValue::by_val_pair(val, is_overflow, fx.layout_of(out_ty));
850     }
851
852     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
853         assert_eq!(
854             in_lhs.layout().ty,
855             in_rhs.layout().ty,
856             "checked int binop requires lhs and rhs of same type"
857         );
858     }
859
860     let lhs = in_lhs.load_scalar(fx);
861     let rhs = in_rhs.load_scalar(fx);
862
863     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, true, signed, in_lhs, in_rhs, out_ty) {
864         return res;
865     }
866
867     let (res, has_overflow) = match bin_op {
868         BinOp::Add => {
869             /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
870             (val, c_out)*/
871             // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
872             let val = fx.bcx.ins().iadd(lhs, rhs);
873             let has_overflow = if !signed {
874                 fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
875             } else {
876                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
877                 let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
878                 fx.bcx.ins().bxor(rhs_is_negative, slt)
879             };
880             (val, has_overflow)
881         }
882         BinOp::Sub => {
883             /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
884             (val, b_out)*/
885             // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
886             let val = fx.bcx.ins().isub(lhs, rhs);
887             let has_overflow = if !signed {
888                 fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
889             } else {
890                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
891                 let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
892                 fx.bcx.ins().bxor(rhs_is_negative, sgt)
893             };
894             (val, has_overflow)
895         }
896         BinOp::Mul => {
897             let val = fx.bcx.ins().imul(lhs, rhs);
898             /*let val_hi = if !signed {
899                 fx.bcx.ins().umulhi(lhs, rhs)
900             } else {
901                 fx.bcx.ins().smulhi(lhs, rhs)
902             };
903             let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
904             // TODO: check for overflow
905             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
906             (val, has_overflow)
907         }
908         BinOp::Shl => {
909             let val = fx.bcx.ins().ishl(lhs, rhs);
910             // TODO: check for overflow
911             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
912             (val, has_overflow)
913         }
914         BinOp::Shr => {
915             let val = if !signed {
916                 fx.bcx.ins().ushr(lhs, rhs)
917             } else {
918                 fx.bcx.ins().sshr(lhs, rhs)
919             };
920             // TODO: check for overflow
921             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
922             (val, has_overflow)
923         }
924         _ => bug!(
925             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
926             bin_op,
927             in_lhs,
928             in_rhs
929         ),
930     };
931
932     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
933     let out_place = CPlace::new_stack_slot(fx, out_ty);
934     let out_layout = out_place.layout();
935     out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
936
937     out_place.to_cvalue(fx)
938 }
939
940 fn trans_float_binop<'a, 'tcx: 'a>(
941     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
942     bin_op: BinOp,
943     lhs: CValue<'tcx>,
944     rhs: CValue<'tcx>,
945     ty: Ty<'tcx>,
946 ) -> CValue<'tcx> {
947     let res = binop_match! {
948         fx, bin_op, false, lhs, rhs, ty, "float";
949         Add (_) fadd;
950         Sub (_) fsub;
951         Mul (_) fmul;
952         Div (_) fdiv;
953         Rem (_) custom(|| {
954             assert_eq!(lhs.layout().ty, ty);
955             assert_eq!(rhs.layout().ty, ty);
956             match ty.sty {
957                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
958                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
959                 _ => bug!(),
960             }
961         });
962         BitXor (_) bxor;
963         BitAnd (_) band;
964         BitOr (_) bor;
965         Shl (_) bug;
966         Shr (_) bug;
967
968         Eq (_) fcmp(Equal);
969         Lt (_) fcmp(LessThan);
970         Le (_) fcmp(LessThanOrEqual);
971         Ne (_) fcmp(NotEqual);
972         Ge (_) fcmp(GreaterThanOrEqual);
973         Gt (_) fcmp(GreaterThan);
974
975         Offset (_) bug;
976     };
977
978     res
979 }
980
981 fn trans_char_binop<'a, 'tcx: 'a>(
982     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
983     bin_op: BinOp,
984     lhs: CValue<'tcx>,
985     rhs: CValue<'tcx>,
986     ty: Ty<'tcx>,
987 ) -> CValue<'tcx> {
988     let res = binop_match! {
989         fx, bin_op, false, lhs, rhs, ty, "char";
990         Add (_) bug;
991         Sub (_) bug;
992         Mul (_) bug;
993         Div (_) bug;
994         Rem (_) bug;
995         BitXor (_) bug;
996         BitAnd (_) bug;
997         BitOr (_) bug;
998         Shl (_) bug;
999         Shr (_) bug;
1000
1001         Eq (_) icmp(Equal);
1002         Lt (_) icmp(UnsignedLessThan);
1003         Le (_) icmp(UnsignedLessThanOrEqual);
1004         Ne (_) icmp(NotEqual);
1005         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1006         Gt (_) icmp(UnsignedGreaterThan);
1007
1008         Offset (_) bug;
1009     };
1010
1011     res
1012 }
1013
1014 fn trans_ptr_binop<'a, 'tcx: 'a>(
1015     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1016     bin_op: BinOp,
1017     lhs: CValue<'tcx>,
1018     rhs: CValue<'tcx>,
1019     ret_ty: Ty<'tcx>,
1020 ) -> CValue<'tcx> {
1021     let not_fat = match lhs.layout().ty.sty {
1022         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1023             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1024         }
1025         ty::FnPtr(..) => true,
1026         _ => bug!("trans_ptr_binop on non ptr"),
1027     };
1028     if not_fat {
1029         if let BinOp::Offset = bin_op {
1030             let (base, offset) = (lhs, rhs.load_scalar(fx));
1031             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1032             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1033             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1034             let base_val = base.load_scalar(fx);
1035             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1036             return CValue::by_val(res, base.layout());
1037         }
1038
1039         binop_match! {
1040             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1041             Add (_) bug;
1042             Sub (_) bug;
1043             Mul (_) bug;
1044             Div (_) bug;
1045             Rem (_) bug;
1046             BitXor (_) bug;
1047             BitAnd (_) bug;
1048             BitOr (_) bug;
1049             Shl (_) bug;
1050             Shr (_) bug;
1051
1052             Eq (_) icmp(Equal);
1053             Lt (_) icmp(UnsignedLessThan);
1054             Le (_) icmp(UnsignedLessThanOrEqual);
1055             Ne (_) icmp(NotEqual);
1056             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1057             Gt (_) icmp(UnsignedGreaterThan);
1058
1059             Offset (_) bug; // Handled above
1060         }
1061     } else {
1062         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1063         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1064
1065         let res = match bin_op {
1066             BinOp::Eq => {
1067                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1068                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1069                 fx.bcx.ins().band(ptr_eq, extra_eq)
1070             }
1071             BinOp::Ne => {
1072                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1073                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1074                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1075             }
1076             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1077                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1078
1079                 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1080                     BinOp::Lt => IntCC::UnsignedLessThan,
1081                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1082                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1083                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1084                     _ => unreachable!(),
1085                 }, lhs_ptr, rhs_ptr);
1086
1087                 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1088                     BinOp::Lt => IntCC::UnsignedLessThan,
1089                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1090                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1091                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1092                     _ => unreachable!(),
1093                 }, lhs_extra, rhs_extra);
1094
1095                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1096             }
1097             _ => panic!("bin_op {:?} on ptr", bin_op),
1098         };
1099
1100         assert_eq!(fx.tcx.types.bool, ret_ty);
1101         let ret_layout = fx.layout_of(ret_ty);
1102         CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1103     }
1104 }
1105
1106 pub fn trans_place<'a, 'tcx: 'a>(
1107     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1108     place: &Place<'tcx>,
1109 ) -> CPlace<'tcx> {
1110     let base = match &place.base {
1111         PlaceBase::Local(local) => fx.get_local_place(*local),
1112         PlaceBase::Static(static_) => match static_.kind {
1113             StaticKind::Static(def_id) => {
1114                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1115             }
1116             StaticKind::Promoted(promoted) => {
1117                 crate::constant::trans_promoted(fx, promoted, static_.ty)
1118             }
1119         }
1120     };
1121
1122     trans_place_projection(fx, base, &place.projection)
1123 }
1124
1125 pub fn trans_place_projection<'a, 'tcx: 'a>(
1126     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1127     base: CPlace<'tcx>,
1128     projection: &Option<Box<Projection<'tcx>>>,
1129 ) -> CPlace<'tcx> {
1130     let projection = if let Some(projection) = projection {
1131         projection
1132     } else {
1133         return base;
1134     };
1135
1136     let base = trans_place_projection(fx, base, &projection.base);
1137
1138     match projection.elem {
1139         ProjectionElem::Deref => base.place_deref(fx),
1140         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1141         ProjectionElem::Index(local) => {
1142             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1143             base.place_index(fx, index)
1144         }
1145         ProjectionElem::ConstantIndex {
1146             offset,
1147             min_length: _,
1148             from_end,
1149         } => {
1150             let index = if !from_end {
1151                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1152             } else {
1153                 let len = codegen_array_len(fx, base);
1154                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1155             };
1156             base.place_index(fx, index)
1157         }
1158         ProjectionElem::Subslice { from, to } => {
1159             // These indices are generated by slice patterns.
1160             // slice[from:-to] in Python terms.
1161
1162             match base.layout().ty.sty {
1163                 ty::Array(elem_ty, len) => {
1164                     let elem_layout = fx.layout_of(elem_ty);
1165                     let ptr = base.to_addr(fx);
1166                     let len = crate::constant::force_eval_const(fx, len)
1167                         .eval_usize(fx.tcx, ParamEnv::reveal_all());
1168                     CPlace::for_addr(
1169                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1170                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1171                     )
1172                 }
1173                 ty::Slice(elem_ty) => {
1174                     let elem_layout = fx.layout_of(elem_ty);
1175                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
1176                     let len = len.unwrap();
1177                     CPlace::for_addr_with_extra(
1178                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1179                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1180                         base.layout(),
1181                     )
1182                 }
1183                 _ => unreachable!(),
1184             }
1185         }
1186         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1187     }
1188 }
1189
1190 pub fn trans_operand<'a, 'tcx>(
1191     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1192     operand: &Operand<'tcx>,
1193 ) -> CValue<'tcx> {
1194     match operand {
1195         Operand::Move(place) | Operand::Copy(place) => {
1196             let cplace = trans_place(fx, place);
1197             cplace.to_cvalue(fx)
1198         }
1199         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1200     }
1201 }