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