1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use llvm::{self, BasicBlock};
12 use rustc::middle::lang_items;
13 use rustc::ty::{self, Ty, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
16 use rustc::mir::interpret::EvalErrorKind;
17 use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
20 use builder::{Builder, MemFlags};
21 use common::{self, IntPredicate};
22 use context::CodegenCx;
26 use type_of::LayoutLlvmExt;
30 use interfaces::{BuilderMethods, CommonMethods};
32 use syntax::symbol::Symbol;
35 use super::{FunctionCx, LocalRef};
36 use super::place::PlaceRef;
37 use super::operand::OperandRef;
38 use super::operand::OperandValue::{Pair, Ref, Immediate};
40 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
41 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
42 let mut bx = self.build_block(bb);
43 let data = &self.mir[bb];
45 debug!("codegen_block({:?}={:?})", bb, data);
47 for statement in &data.statements {
48 bx = self.codegen_statement(bx, statement);
51 self.codegen_terminator(bx, bb, data.terminator());
54 fn codegen_terminator(&mut self,
55 mut bx: Builder<'a, 'll, 'tcx>,
57 terminator: &mir::Terminator<'tcx>)
59 debug!("codegen_terminator: {:?}", terminator);
61 // Create the cleanup bundle, if needed.
63 let span = terminator.source_info.span;
64 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
65 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
67 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
68 let cleanup_bundle = funclet.map(|l| l.bundle());
70 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
71 let lltarget = this.blocks[target];
72 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
73 match (funclet_bb, target_funclet) {
74 (None, None) => (lltarget, false),
76 if f == t_f || !base::wants_msvc_seh(tcx.sess)
79 // jump *into* cleanup - need a landing pad if GNU
80 (this.landing_pad_to(target), false)
82 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
83 (Some(_), Some(_)) => {
84 (this.landing_pad_to(target), true)
89 let llblock = |this: &mut Self, target: mir::BasicBlock| {
90 let (lltarget, is_cleanupret) = lltarget(this, target);
92 // MSVC cross-funclet jump - need a trampoline
94 debug!("llblock: creating cleanup trampoline for {:?}", target);
95 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
96 let trampoline = this.new_block(name);
97 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
105 |this: &mut Self, bx: Builder<'_, 'll, '_>, target: mir::BasicBlock| {
106 let (lltarget, is_cleanupret) = lltarget(this, target);
108 // micro-optimization: generate a `ret` rather than a jump
110 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
118 bx: Builder<'a, 'll, 'tcx>,
119 fn_ty: FnType<'tcx, Ty<'tcx>>,
121 llargs: &[&'ll Value],
122 destination: Option<(ReturnDest<'tcx, &'ll Value>, mir::BasicBlock)>,
123 cleanup: Option<mir::BasicBlock>
125 if let Some(cleanup) = cleanup {
126 let ret_bx = if let Some((_, target)) = destination {
129 this.unreachable_block()
131 let invokeret = bx.invoke(fn_ptr,
134 llblock(this, cleanup),
136 fn_ty.apply_attrs_callsite(&bx, invokeret);
138 if let Some((ret_dest, target)) = destination {
139 let ret_bx = this.build_block(target);
140 this.set_debug_loc(&ret_bx, terminator.source_info);
141 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
144 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
145 fn_ty.apply_attrs_callsite(&bx, llret);
146 if this.mir[bb].is_cleanup {
147 // Cleanup is always the cold path. Don't inline
148 // drop glue. Also, when there is a deeply-nested
149 // struct, there are "symmetry" issues that cause
150 // exponential inlining - see issue #41696.
151 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
154 if let Some((ret_dest, target)) = destination {
155 this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
156 funclet_br(this, bx, target);
163 self.set_debug_loc(&bx, terminator.source_info);
164 match terminator.kind {
165 mir::TerminatorKind::Resume => {
166 if let Some(cleanup_pad) = cleanup_pad {
167 bx.cleanup_ret(cleanup_pad, None);
169 let slot = self.get_personality_slot(&bx);
170 let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
171 let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
172 slot.storage_dead(&bx);
174 if !bx.sess().target.target.options.custom_unwind_resume {
175 let mut lp = bx.cx().c_undef(self.landing_pad_type());
176 lp = bx.insert_value(lp, lp0, 0);
177 lp = bx.insert_value(lp, lp1, 1);
180 bx.call(bx.cx().eh_unwind_resume(), &[lp0], cleanup_bundle);
186 mir::TerminatorKind::Abort => {
187 // Call core::intrinsics::abort()
188 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
189 bx.call(fnname, &[], None);
193 mir::TerminatorKind::Goto { target } => {
194 funclet_br(self, bx, target);
197 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
198 let discr = self.codegen_operand(&bx, discr);
199 if targets.len() == 2 {
200 // If there are two targets, emit br instead of switch
201 let lltrue = llblock(self, targets[0]);
202 let llfalse = llblock(self, targets[1]);
203 if switch_ty == bx.tcx().types.bool {
204 // Don't generate trivial icmps when switching on bool
205 if let [0] = values[..] {
206 bx.cond_br(discr.immediate(), llfalse, lltrue);
208 assert_eq!(&values[..], &[1]);
209 bx.cond_br(discr.immediate(), lltrue, llfalse);
212 let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
213 let llval = bx.cx().c_uint_big(switch_llty, values[0]);
214 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
215 bx.cond_br(cmp, lltrue, llfalse);
218 let (otherwise, targets) = targets.split_last().unwrap();
219 let switch = bx.switch(discr.immediate(),
220 llblock(self, *otherwise),
222 let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
223 for (&value, target) in values.iter().zip(targets) {
224 let llval =bx.cx().c_uint_big(switch_llty, value);
225 let llbb = llblock(self, *target);
226 bx.add_case(switch, llval, llbb)
231 mir::TerminatorKind::Return => {
232 let llval = match self.fn_ty.ret.mode {
233 PassMode::Ignore | PassMode::Indirect(..) => {
238 PassMode::Direct(_) | PassMode::Pair(..) => {
239 let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
240 if let Ref(llval, _, align) = op.val {
241 bx.load(llval, align)
243 op.immediate_or_packed_pair(&bx)
247 PassMode::Cast(cast_ty) => {
248 let op = match self.locals[mir::RETURN_PLACE] {
249 LocalRef::Operand(Some(op)) => op,
250 LocalRef::Operand(None) => bug!("use of return before def"),
251 LocalRef::Place(cg_place) => {
253 val: Ref(cg_place.llval, None, cg_place.align),
254 layout: cg_place.layout
257 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
259 let llslot = match op.val {
260 Immediate(_) | Pair(..) => {
261 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
262 op.val.store(&bx, scratch);
265 Ref(llval, _, align) => {
266 assert_eq!(align.abi(), op.layout.align.abi(),
267 "return place is unaligned!");
272 bx.pointercast(llslot, cast_ty.llvm_type(bx.cx()).ptr_to()),
273 self.fn_ty.ret.layout.align)
279 mir::TerminatorKind::Unreachable => {
283 mir::TerminatorKind::Drop { ref location, target, unwind } => {
284 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
285 let ty = self.monomorphize(&ty);
286 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx().tcx, ty);
288 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
289 // we don't actually need to drop anything.
290 funclet_br(self, bx, target);
294 let place = self.codegen_place(&bx, location);
296 let mut args = if let Some(llextra) = place.llextra {
297 args2 = [place.llval, llextra];
300 args1 = [place.llval];
303 let (drop_fn, fn_ty) = match ty.sty {
305 let sig = drop_fn.fn_sig(bx.tcx());
306 let sig = bx.tcx().normalize_erasing_late_bound_regions(
307 ty::ParamEnv::reveal_all(),
310 let fn_ty = FnType::new_vtable(bx.cx(), sig, &[]);
311 let vtable = args[1];
313 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
316 (callee::get_fn(bx.cx(), drop_fn),
317 FnType::of_instance(bx.cx(), &drop_fn))
320 do_call(self, bx, fn_ty, drop_fn, args,
321 Some((ReturnDest::Nothing, target)),
325 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
326 let cond = self.codegen_operand(&bx, cond).immediate();
327 let mut const_cond = CodegenCx::const_to_opt_u128(cond, false).map(|c| c == 1);
329 // This case can currently arise only from functions marked
330 // with #[rustc_inherit_overflow_checks] and inlined from
331 // another crate (mostly core::num generic/#[inline] fns),
332 // while the current crate doesn't use overflow checks.
333 // NOTE: Unlike binops, negation doesn't have its own
334 // checked operation, just a comparison with the minimum
335 // value, so we have to check for the assert message.
336 if !bx.cx().check_overflow {
337 if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
338 const_cond = Some(expected);
342 // Don't codegen the panic block if success if known.
343 if const_cond == Some(expected) {
344 funclet_br(self, bx, target);
348 // Pass the condition through llvm.expect for branch hinting.
349 let expect = bx.cx().get_intrinsic(&"llvm.expect.i1");
350 let cond = bx.call(expect, &[cond, CodegenCx::c_bool(bx.cx(), expected)], None);
352 // Create the failure block and the conditional branch to it.
353 let lltarget = llblock(self, target);
354 let panic_block = self.new_block("panic");
356 bx.cond_br(cond, lltarget, panic_block.llbb());
358 bx.cond_br(cond, panic_block.llbb(), lltarget);
361 // After this point, bx is the block for the call to panic.
363 self.set_debug_loc(&bx, terminator.source_info);
365 // Get the location information.
366 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
367 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
368 let filename = CodegenCx::c_str_slice(bx.cx(), filename);
369 let line = CodegenCx::c_u32(bx.cx(), loc.line as u32);
370 let col = CodegenCx::c_u32(bx.cx(), loc.col.to_usize() as u32 + 1);
371 let align = tcx.data_layout.aggregate_align
372 .max(tcx.data_layout.i32_align)
373 .max(tcx.data_layout.pointer_align);
375 // Put together the arguments to the panic entry point.
376 let (lang_item, args) = match *msg {
377 EvalErrorKind::BoundsCheck { ref len, ref index } => {
378 let len = self.codegen_operand(&mut bx, len).immediate();
379 let index = self.codegen_operand(&mut bx, index).immediate();
381 let file_line_col = CodegenCx::c_struct(bx.cx(),
382 &[filename, line, col], false);
383 let file_line_col = consts::addr_of(bx.cx(),
386 Some("panic_bounds_check_loc"));
387 (lang_items::PanicBoundsCheckFnLangItem,
388 vec![file_line_col, index, len])
391 let str = msg.description();
392 let msg_str = Symbol::intern(str).as_str();
393 let msg_str = CodegenCx::c_str_slice(bx.cx(), msg_str);
394 let msg_file_line_col = CodegenCx::c_struct(
396 &[msg_str, filename, line, col],
399 let msg_file_line_col = consts::addr_of(bx.cx(),
403 (lang_items::PanicFnLangItem,
404 vec![msg_file_line_col])
408 // Obtain the panic entry point.
409 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
410 let instance = ty::Instance::mono(bx.tcx(), def_id);
411 let fn_ty = FnType::of_instance(bx.cx(), &instance);
412 let llfn = callee::get_fn(bx.cx(), instance);
414 // Codegen the actual panic invoke/call.
415 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
418 mir::TerminatorKind::DropAndReplace { .. } => {
419 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
422 mir::TerminatorKind::Call {
429 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
430 let callee = self.codegen_operand(&bx, func);
432 let (instance, mut llfn) = match callee.layout.ty.sty {
433 ty::FnDef(def_id, substs) => {
434 (Some(ty::Instance::resolve(bx.cx().tcx,
435 ty::ParamEnv::reveal_all(),
441 (None, Some(callee.immediate()))
443 _ => bug!("{} is not callable", callee.layout.ty)
445 let def = instance.map(|i| i.def);
446 let sig = callee.layout.ty.fn_sig(bx.tcx());
447 let sig = bx.tcx().normalize_erasing_late_bound_regions(
448 ty::ParamEnv::reveal_all(),
453 // Handle intrinsics old codegen wants Expr's for, ourselves.
454 let intrinsic = match def {
455 Some(ty::InstanceDef::Intrinsic(def_id))
456 => Some(bx.tcx().item_name(def_id).as_str()),
459 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
461 if intrinsic == Some("transmute") {
462 if let Some(destination_ref) = destination.as_ref() {
463 let &(ref dest, target) = destination_ref;
464 self.codegen_transmute(&bx, &args[0], dest);
465 funclet_br(self, bx, target);
467 // If we are trying to transmute to an uninhabited type,
468 // it is likely there is no allotted destination. In fact,
469 // transmuting to an uninhabited type is UB, which means
470 // we can do what we like. Here, we declare that transmuting
471 // into an uninhabited type is impossible, so anything following
472 // it must be unreachable.
473 assert_eq!(bx.cx().layout_of(sig.output()).abi, layout::Abi::Uninhabited);
479 let extra_args = &args[sig.inputs().len()..];
480 let extra_args = extra_args.iter().map(|op_arg| {
481 let op_ty = op_arg.ty(self.mir, bx.tcx());
482 self.monomorphize(&op_ty)
483 }).collect::<Vec<_>>();
485 let fn_ty = match def {
486 Some(ty::InstanceDef::Virtual(..)) => {
487 FnType::new_vtable(bx.cx(), sig, &extra_args)
489 Some(ty::InstanceDef::DropGlue(_, None)) => {
490 // empty drop glue - a nop.
491 let &(_, target) = destination.as_ref().unwrap();
492 funclet_br(self, bx, target);
495 _ => FnType::new(bx.cx(), sig, &extra_args)
498 // emit a panic instead of instantiating an uninhabited type
499 if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
500 fn_ty.ret.layout.abi.is_uninhabited()
502 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
503 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
504 let filename = bx.cx.c_str_slice(filename);
505 let line = bx.cx.c_u32(loc.line as u32);
506 let col = bx.cx.c_u32(loc.col.to_usize() as u32 + 1);
507 let align = tcx.data_layout.aggregate_align
508 .max(tcx.data_layout.i32_align)
509 .max(tcx.data_layout.pointer_align);
512 "Attempted to instantiate uninhabited type {} using mem::{}",
514 if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
516 let msg_str = Symbol::intern(&str).as_str();
517 let msg_str = bx.cx.c_str_slice(msg_str);
518 let msg_file_line_col = bx.cx.c_struct(
519 &[msg_str, filename, line, col],
522 let msg_file_line_col = consts::addr_of(bx.cx,
527 // Obtain the panic entry point.
529 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
530 let instance = ty::Instance::mono(bx.tcx(), def_id);
531 let fn_ty = FnType::of_instance(bx.cx, &instance);
532 let llfn = callee::get_fn(bx.cx, instance);
534 // Codegen the actual panic invoke/call.
540 &[msg_file_line_col],
541 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
547 // The arguments we'll be passing. Plus one to account for outptr, if used.
548 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
549 let mut llargs = Vec::with_capacity(arg_count);
551 // Prepare the return value destination
552 let ret_dest = if let Some((ref dest, _)) = *destination {
553 let is_intrinsic = intrinsic.is_some();
554 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
560 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
561 use intrinsic::codegen_intrinsic_call;
563 let dest = match ret_dest {
564 _ if fn_ty.ret.is_indirect() => llargs[0],
565 ReturnDest::Nothing => {
566 bx.cx().c_undef(fn_ty.ret.memory_ty(bx.cx()).ptr_to())
568 ReturnDest::IndirectOperand(dst, _) |
569 ReturnDest::Store(dst) => dst.llval,
570 ReturnDest::DirectOperand(_) =>
571 bug!("Cannot use direct operand with an intrinsic call")
574 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
575 // The indices passed to simd_shuffle* in the
576 // third argument must be constant. This is
577 // checked by const-qualification, which also
578 // promotes any complex rvalues to constants.
579 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
581 // The shuffle array argument is usually not an explicit constant,
582 // but specified directly in the code. This means it gets promoted
583 // and we can then extract the value by evaluating the promoted.
584 mir::Operand::Copy(mir::Place::Promoted(box(index, ty))) |
585 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
586 let param_env = ty::ParamEnv::reveal_all();
587 let cid = mir::interpret::GlobalId {
588 instance: self.instance,
589 promoted: Some(index),
591 let c = bx.tcx().const_eval(param_env.and(cid));
592 let (llval, ty) = self.simd_shuffle_indices(
594 terminator.source_info.span,
599 val: Immediate(llval),
600 layout: bx.cx().layout_of(ty),
604 mir::Operand::Copy(_) |
605 mir::Operand::Move(_) => {
606 span_bug!(span, "shuffle indices must be constant");
608 mir::Operand::Constant(ref constant) => {
609 let c = self.eval_mir_constant(&bx, constant);
610 let (llval, ty) = self.simd_shuffle_indices(
617 val: Immediate(llval),
618 layout: bx.cx().layout_of(ty)
624 self.codegen_operand(&bx, arg)
628 let callee_ty = instance.as_ref().unwrap().ty(bx.cx().tcx);
629 codegen_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
630 terminator.source_info.span);
632 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
633 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
636 if let Some((_, target)) = *destination {
637 funclet_br(self, bx, target);
645 // Split the rust-call tupled arguments off.
646 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
647 let (tup, args) = args.split_last().unwrap();
653 'make_args: for (i, arg) in first_args.iter().enumerate() {
654 let mut op = self.codegen_operand(&bx, arg);
656 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
657 if let Pair(..) = op.val {
658 // In the case of Rc<Self>, we need to explicitly pass a
659 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
660 // that is understood elsewhere in the compiler as a method on
662 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
663 // we get a value of a built-in pointer type
664 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
665 && !op.layout.ty.is_region_ptr()
667 'iter_fields: for i in 0..op.layout.fields.count() {
668 let field = op.extract_field(&bx, i);
669 if !field.layout.is_zst() {
670 // we found the one non-zero-sized field that is allowed
671 // now find *its* non-zero-sized field, or stop if it's a
674 continue 'descend_newtypes
678 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
681 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
682 // data pointer and vtable. Look up the method in the vtable, and pass
683 // the data pointer as the first argument
685 Pair(data_ptr, meta) => {
686 llfn = Some(meth::VirtualIndex::from_index(idx)
687 .get_fn(&bx, meta, &fn_ty));
688 llargs.push(data_ptr);
691 other => bug!("expected a Pair, got {:?}", other)
693 } else if let Ref(data_ptr, Some(meta), _) = op.val {
694 // by-value dynamic dispatch
695 llfn = Some(meth::VirtualIndex::from_index(idx)
696 .get_fn(&bx, meta, &fn_ty));
697 llargs.push(data_ptr);
700 span_bug!(span, "can't codegen a virtual call on {:?}", op);
704 // The callee needs to own the argument memory if we pass it
705 // by-ref, so make a local copy of non-immediate constants.
706 match (arg, op.val) {
707 (&mir::Operand::Copy(_), Ref(_, None, _)) |
708 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
709 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
710 op.val.store(&bx, tmp);
711 op.val = Ref(tmp.llval, None, tmp.align);
716 self.codegen_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
718 if let Some(tup) = untuple {
719 self.codegen_arguments_untupled(&bx, tup, &mut llargs,
720 &fn_ty.args[first_args.len()..])
723 let fn_ptr = match (llfn, instance) {
724 (Some(llfn), _) => llfn,
725 (None, Some(instance)) => callee::get_fn(bx.cx(), instance),
726 _ => span_bug!(span, "no llfn for call"),
729 do_call(self, bx, fn_ty, fn_ptr, &llargs,
730 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
733 mir::TerminatorKind::GeneratorDrop |
734 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
735 mir::TerminatorKind::FalseEdges { .. } |
736 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
740 fn codegen_argument(&mut self,
741 bx: &Builder<'a, 'll, 'tcx>,
742 op: OperandRef<'tcx, &'ll Value>,
743 llargs: &mut Vec<&'ll Value>,
744 arg: &ArgType<'tcx, Ty<'tcx>>) {
745 // Fill padding with undef value, where applicable.
746 if let Some(ty) = arg.pad {
747 llargs.push(bx.cx().c_undef(ty.llvm_type(bx.cx())));
754 if let PassMode::Pair(..) = arg.mode {
761 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
763 } else if arg.is_unsized_indirect() {
765 Ref(a, Some(b), _) => {
770 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
774 // Force by-ref if we have to load through a cast pointer.
775 let (mut llval, align, by_ref) = match op.val {
776 Immediate(_) | Pair(..) => {
778 PassMode::Indirect(..) | PassMode::Cast(_) => {
779 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
780 op.val.store(bx, scratch);
781 (scratch.llval, scratch.align, true)
784 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
788 Ref(llval, _, align) => {
789 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
790 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
791 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
792 // have scary latent bugs around.
794 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
795 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
796 op.layout, MemFlags::empty());
797 (scratch.llval, scratch.align, true)
804 if by_ref && !arg.is_indirect() {
805 // Have to load the argument, maybe while casting it.
806 if let PassMode::Cast(ty) = arg.mode {
807 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx()).ptr_to()),
808 align.min(arg.layout.align));
810 // We can't use `PlaceRef::load` here because the argument
811 // may have a type we don't treat as immediate, but the ABI
812 // used for this call is passing it by-value. In that case,
813 // the load would just produce `OperandValue::Ref` instead
814 // of the `OperandValue::Immediate` we need for the call.
815 llval = bx.load(llval, align);
816 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
817 if scalar.is_bool() {
818 bx.range_metadata(llval, 0..2);
821 // We store bools as i8 so we need to truncate to i1.
822 llval = base::to_immediate(bx, llval, arg.layout);
829 fn codegen_arguments_untupled(&mut self,
830 bx: &Builder<'a, 'll, 'tcx>,
831 operand: &mir::Operand<'tcx>,
832 llargs: &mut Vec<&'ll Value>,
833 args: &[ArgType<'tcx, Ty<'tcx>>]) {
834 let tuple = self.codegen_operand(bx, operand);
836 // Handle both by-ref and immediate tuples.
837 if let Ref(llval, None, align) = tuple.val {
838 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
839 for i in 0..tuple.layout.fields.count() {
840 let field_ptr = tuple_ptr.project_field(bx, i);
841 self.codegen_argument(bx, field_ptr.load(bx), llargs, &args[i]);
843 } else if let Ref(_, Some(_), _) = tuple.val {
844 bug!("closure arguments must be sized")
846 // If the tuple is immediate, the elements are as well.
847 for i in 0..tuple.layout.fields.count() {
848 let op = tuple.extract_field(bx, i);
849 self.codegen_argument(bx, op, llargs, &args[i]);
854 fn get_personality_slot(
856 bx: &Builder<'a, 'll, 'tcx>
857 ) -> PlaceRef<'tcx, &'ll Value> {
859 if let Some(slot) = self.personality_slot {
862 let layout = cx.layout_of(cx.tcx.intern_tup(&[
863 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
866 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
867 self.personality_slot = Some(slot);
872 /// Return the landingpad wrapper around the given basic block
874 /// No-op in MSVC SEH scheme.
875 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> &'ll BasicBlock {
876 if let Some(block) = self.landing_pads[target_bb] {
880 let block = self.blocks[target_bb];
881 let landing_pad = self.landing_pad_uncached(block);
882 self.landing_pads[target_bb] = Some(landing_pad);
886 fn landing_pad_uncached(&mut self, target_bb: &'ll BasicBlock) -> &'ll BasicBlock {
887 if base::wants_msvc_seh(self.cx.sess()) {
888 span_bug!(self.mir.span, "landing pad was not inserted?")
891 let bx = self.new_block("cleanup");
893 let llpersonality = self.cx.eh_personality();
894 let llretty = self.landing_pad_type();
895 let lp = bx.landing_pad(llretty, llpersonality, 1);
898 let slot = self.get_personality_slot(&bx);
899 slot.storage_live(&bx);
900 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
906 fn landing_pad_type(&self) -> &'ll Type {
908 Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
911 fn unreachable_block(&mut self) -> &'ll BasicBlock {
912 self.unreachable_block.unwrap_or_else(|| {
913 let bl = self.new_block("unreachable");
915 self.unreachable_block = Some(bl.llbb());
920 pub fn new_block(&self, name: &str) -> Builder<'a, 'll, 'tcx> {
921 Builder::new_block(self.cx, self.llfn, name)
924 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'll, 'tcx> {
925 let bx = Builder::with_cx(self.cx);
926 bx.position_at_end(self.blocks[bb]);
930 fn make_return_dest(&mut self, bx: &Builder<'a, 'll, 'tcx>,
931 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
932 llargs: &mut Vec<&'ll Value>, is_intrinsic: bool)
933 -> ReturnDest<'tcx, &'ll Value> {
934 // If the return is ignored, we can just return a do-nothing ReturnDest
935 if fn_ret.is_ignore() {
936 return ReturnDest::Nothing;
938 let dest = if let mir::Place::Local(index) = *dest {
939 match self.locals[index] {
940 LocalRef::Place(dest) => dest,
941 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
942 LocalRef::Operand(None) => {
943 // Handle temporary places, specifically Operand ones, as
944 // they don't have allocas
945 return if fn_ret.is_indirect() {
946 // Odd, but possible, case, we have an operand temporary,
947 // but the calling convention has an indirect return.
948 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
949 tmp.storage_live(bx);
950 llargs.push(tmp.llval);
951 ReturnDest::IndirectOperand(tmp, index)
952 } else if is_intrinsic {
953 // Currently, intrinsics always need a location to store
954 // the result. so we create a temporary alloca for the
956 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
957 tmp.storage_live(bx);
958 ReturnDest::IndirectOperand(tmp, index)
960 ReturnDest::DirectOperand(index)
963 LocalRef::Operand(Some(_)) => {
964 bug!("place local already assigned to");
968 self.codegen_place(bx, dest)
970 if fn_ret.is_indirect() {
971 if dest.align.abi() < dest.layout.align.abi() {
972 // Currently, MIR code generation does not create calls
973 // that store directly to fields of packed structs (in
974 // fact, the calls it creates write only to temps),
976 // If someone changes that, please update this code path
977 // to create a temporary.
978 span_bug!(self.mir.span, "can't directly store to unaligned value");
980 llargs.push(dest.llval);
983 ReturnDest::Store(dest)
987 fn codegen_transmute(&mut self, bx: &Builder<'a, 'll, 'tcx>,
988 src: &mir::Operand<'tcx>,
989 dst: &mir::Place<'tcx>) {
990 if let mir::Place::Local(index) = *dst {
991 match self.locals[index] {
992 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
993 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
994 LocalRef::Operand(None) => {
995 let dst_layout = bx.cx().layout_of(self.monomorphized_place_ty(dst));
996 assert!(!dst_layout.ty.has_erasable_regions());
997 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
998 place.storage_live(bx);
999 self.codegen_transmute_into(bx, src, place);
1000 let op = place.load(bx);
1001 place.storage_dead(bx);
1002 self.locals[index] = LocalRef::Operand(Some(op));
1004 LocalRef::Operand(Some(op)) => {
1005 assert!(op.layout.is_zst(),
1006 "assigning to initialized SSAtemp");
1010 let dst = self.codegen_place(bx, dst);
1011 self.codegen_transmute_into(bx, src, dst);
1015 fn codegen_transmute_into(&mut self, bx: &Builder<'a, 'll, 'tcx>,
1016 src: &mir::Operand<'tcx>,
1017 dst: PlaceRef<'tcx, &'ll Value>) {
1018 let src = self.codegen_operand(bx, src);
1019 let llty = src.layout.llvm_type(bx.cx());
1020 let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
1021 let align = src.layout.align.min(dst.layout.align);
1022 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1026 // Stores the return value of a function call into it's final location.
1027 fn store_return(&mut self,
1028 bx: &Builder<'a, 'll, 'tcx>,
1029 dest: ReturnDest<'tcx, &'ll Value>,
1030 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1031 llval: &'ll Value) {
1032 use self::ReturnDest::*;
1036 Store(dst) => ret_ty.store(bx, llval, dst),
1037 IndirectOperand(tmp, index) => {
1038 let op = tmp.load(bx);
1039 tmp.storage_dead(bx);
1040 self.locals[index] = LocalRef::Operand(Some(op));
1042 DirectOperand(index) => {
1043 // If there is a cast, we have to store and reload.
1044 let op = if let PassMode::Cast(_) = ret_ty.mode {
1045 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1046 tmp.storage_live(bx);
1047 ret_ty.store(bx, llval, tmp);
1048 let op = tmp.load(bx);
1049 tmp.storage_dead(bx);
1052 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1054 self.locals[index] = LocalRef::Operand(Some(op));
1060 enum ReturnDest<'tcx, V> {
1061 // Do nothing, the return value is indirect or ignored
1063 // Store the return value to the pointer
1064 Store(PlaceRef<'tcx, V>),
1065 // Stores an indirect return value to an operand local place
1066 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1067 // Stores a direct return value to an operand local place
1068 DirectOperand(mir::Local)