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, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
25 use type_of::LayoutLlvmExt;
29 use traits::{IntPredicate,BuilderMethods};
31 use syntax::symbol::Symbol;
34 use super::{FunctionCx, LocalRef};
35 use super::place::PlaceRef;
36 use super::operand::OperandRef;
37 use super::operand::OperandValue::{Pair, Ref, Immediate};
39 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
40 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
41 let mut bx = self.build_block(bb);
42 let data = &self.mir[bb];
44 debug!("codegen_block({:?}={:?})", bb, data);
46 for statement in &data.statements {
47 bx = self.codegen_statement(bx, statement);
50 self.codegen_terminator(bx, bb, data.terminator());
53 fn codegen_terminator(&mut self,
54 mut bx: Builder<'a, 'll, 'tcx>,
56 terminator: &mir::Terminator<'tcx>)
58 debug!("codegen_terminator: {:?}", terminator);
60 // Create the cleanup bundle, if needed.
62 let span = terminator.source_info.span;
63 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
64 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
66 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
67 let cleanup_bundle = funclet.map(|l| l.bundle());
69 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
70 let lltarget = this.blocks[target];
71 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
72 match (funclet_bb, target_funclet) {
73 (None, None) => (lltarget, false),
75 if f == t_f || !base::wants_msvc_seh(tcx.sess)
78 // jump *into* cleanup - need a landing pad if GNU
79 (this.landing_pad_to(target), false)
81 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
82 (Some(_), Some(_)) => {
83 (this.landing_pad_to(target), true)
88 let llblock = |this: &mut Self, target: mir::BasicBlock| {
89 let (lltarget, is_cleanupret) = lltarget(this, target);
91 // MSVC cross-funclet jump - need a trampoline
93 debug!("llblock: creating cleanup trampoline for {:?}", target);
94 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
95 let trampoline = this.new_block(name);
96 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
104 |this: &mut Self, bx: Builder<'_, 'll, '_, &'ll Value>, target: mir::BasicBlock| {
105 let (lltarget, is_cleanupret) = lltarget(this, target);
107 // micro-optimization: generate a `ret` rather than a jump
109 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
117 bx: Builder<'a, 'll, 'tcx>,
118 fn_ty: FnType<'tcx, Ty<'tcx>>,
120 llargs: &[&'ll Value],
121 destination: Option<(ReturnDest<'tcx, &'ll Value>, mir::BasicBlock)>,
122 cleanup: Option<mir::BasicBlock>
124 if let Some(cleanup) = cleanup {
125 let ret_bx = if let Some((_, target)) = destination {
128 this.unreachable_block()
130 let invokeret = bx.invoke(fn_ptr,
133 llblock(this, cleanup),
135 fn_ty.apply_attrs_callsite(&bx, invokeret);
137 if let Some((ret_dest, target)) = destination {
138 let ret_bx = this.build_block(target);
139 this.set_debug_loc(&ret_bx, terminator.source_info);
140 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
143 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
144 fn_ty.apply_attrs_callsite(&bx, llret);
145 if this.mir[bb].is_cleanup {
146 // Cleanup is always the cold path. Don't inline
147 // drop glue. Also, when there is a deeply-nested
148 // struct, there are "symmetry" issues that cause
149 // exponential inlining - see issue #41696.
150 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
153 if let Some((ret_dest, target)) = destination {
154 this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
155 funclet_br(this, bx, target);
162 self.set_debug_loc(&bx, terminator.source_info);
163 match terminator.kind {
164 mir::TerminatorKind::Resume => {
165 if let Some(cleanup_pad) = cleanup_pad {
166 bx.cleanup_ret(cleanup_pad, None);
168 let slot = self.get_personality_slot(&bx);
169 let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
170 let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
171 slot.storage_dead(&bx);
173 if !bx.sess().target.target.options.custom_unwind_resume {
174 let mut lp = C_undef(self.landing_pad_type());
175 lp = bx.insert_value(lp, lp0, 0);
176 lp = bx.insert_value(lp, lp1, 1);
179 bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
185 mir::TerminatorKind::Abort => {
186 // Call core::intrinsics::abort()
187 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
188 bx.call(fnname, &[], None);
192 mir::TerminatorKind::Goto { target } => {
193 funclet_br(self, bx, target);
196 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
197 let discr = self.codegen_operand(&bx, discr);
198 if targets.len() == 2 {
199 // If there are two targets, emit br instead of switch
200 let lltrue = llblock(self, targets[0]);
201 let llfalse = llblock(self, targets[1]);
202 if switch_ty == bx.tcx().types.bool {
203 // Don't generate trivial icmps when switching on bool
204 if let [0] = values[..] {
205 bx.cond_br(discr.immediate(), llfalse, lltrue);
207 assert_eq!(&values[..], &[1]);
208 bx.cond_br(discr.immediate(), lltrue, llfalse);
211 let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
212 let llval = C_uint_big(switch_llty, values[0]);
213 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
214 bx.cond_br(cmp, lltrue, llfalse);
217 let (otherwise, targets) = targets.split_last().unwrap();
218 let switch = bx.switch(discr.immediate(),
219 llblock(self, *otherwise),
221 let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
222 for (&value, target) in values.iter().zip(targets) {
223 let llval = C_uint_big(switch_llty, value);
224 let llbb = llblock(self, *target);
225 bx.add_case(switch, llval, llbb)
230 mir::TerminatorKind::Return => {
231 let llval = match self.fn_ty.ret.mode {
232 PassMode::Ignore | PassMode::Indirect(..) => {
237 PassMode::Direct(_) | PassMode::Pair(..) => {
238 let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
239 if let Ref(llval, _, align) = op.val {
240 bx.load(llval, align)
242 op.immediate_or_packed_pair(&bx)
246 PassMode::Cast(cast_ty) => {
247 let op = match self.locals[mir::RETURN_PLACE] {
248 LocalRef::Operand(Some(op)) => op,
249 LocalRef::Operand(None) => bug!("use of return before def"),
250 LocalRef::Place(cg_place) => {
252 val: Ref(cg_place.llval, None, cg_place.align),
253 layout: cg_place.layout
256 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
258 let llslot = match op.val {
259 Immediate(_) | Pair(..) => {
260 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
261 op.val.store(&bx, scratch);
264 Ref(llval, _, align) => {
265 assert_eq!(align.abi(), op.layout.align.abi(),
266 "return place is unaligned!");
271 bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
272 self.fn_ty.ret.layout.align)
278 mir::TerminatorKind::Unreachable => {
282 mir::TerminatorKind::Drop { ref location, target, unwind } => {
283 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
284 let ty = self.monomorphize(&ty);
285 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);
287 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
288 // we don't actually need to drop anything.
289 funclet_br(self, bx, target);
293 let place = self.codegen_place(&bx, location);
295 let mut args = if let Some(llextra) = place.llextra {
296 args2 = [place.llval, llextra];
299 args1 = [place.llval];
302 let (drop_fn, fn_ty) = match ty.sty {
304 let sig = drop_fn.fn_sig(bx.cx.tcx);
305 let sig = bx.tcx().normalize_erasing_late_bound_regions(
306 ty::ParamEnv::reveal_all(),
309 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
310 let vtable = args[1];
312 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
315 (callee::get_fn(bx.cx, drop_fn),
316 FnType::of_instance(bx.cx, &drop_fn))
319 do_call(self, bx, fn_ty, drop_fn, args,
320 Some((ReturnDest::Nothing, target)),
324 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
325 let cond = self.codegen_operand(&bx, cond).immediate();
326 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
328 // This case can currently arise only from functions marked
329 // with #[rustc_inherit_overflow_checks] and inlined from
330 // another crate (mostly core::num generic/#[inline] fns),
331 // while the current crate doesn't use overflow checks.
332 // NOTE: Unlike binops, negation doesn't have its own
333 // checked operation, just a comparison with the minimum
334 // value, so we have to check for the assert message.
335 if !bx.cx.check_overflow {
336 if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
337 const_cond = Some(expected);
341 // Don't codegen the panic block if success if known.
342 if const_cond == Some(expected) {
343 funclet_br(self, bx, target);
347 // Pass the condition through llvm.expect for branch hinting.
348 let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
349 let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);
351 // Create the failure block and the conditional branch to it.
352 let lltarget = llblock(self, target);
353 let panic_block = self.new_block("panic");
355 bx.cond_br(cond, lltarget, panic_block.llbb());
357 bx.cond_br(cond, panic_block.llbb(), lltarget);
360 // After this point, bx is the block for the call to panic.
362 self.set_debug_loc(&bx, terminator.source_info);
364 // Get the location information.
365 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
366 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
367 let filename = C_str_slice(bx.cx, filename);
368 let line = C_u32(bx.cx, loc.line as u32);
369 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
370 let align = tcx.data_layout.aggregate_align
371 .max(tcx.data_layout.i32_align)
372 .max(tcx.data_layout.pointer_align);
374 // Put together the arguments to the panic entry point.
375 let (lang_item, args) = match *msg {
376 EvalErrorKind::BoundsCheck { ref len, ref index } => {
377 let len = self.codegen_operand(&mut bx, len).immediate();
378 let index = self.codegen_operand(&mut bx, index).immediate();
380 let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
381 let file_line_col = consts::addr_of(bx.cx,
384 Some("panic_bounds_check_loc"));
385 (lang_items::PanicBoundsCheckFnLangItem,
386 vec![file_line_col, index, len])
389 let str = msg.description();
390 let msg_str = Symbol::intern(str).as_str();
391 let msg_str = C_str_slice(bx.cx, msg_str);
392 let msg_file_line_col = C_struct(bx.cx,
393 &[msg_str, filename, line, col],
395 let msg_file_line_col = consts::addr_of(bx.cx,
399 (lang_items::PanicFnLangItem,
400 vec![msg_file_line_col])
404 // Obtain the panic entry point.
405 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
406 let instance = ty::Instance::mono(bx.tcx(), def_id);
407 let fn_ty = FnType::of_instance(bx.cx, &instance);
408 let llfn = callee::get_fn(bx.cx, instance);
410 // Codegen the actual panic invoke/call.
411 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
414 mir::TerminatorKind::DropAndReplace { .. } => {
415 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
418 mir::TerminatorKind::Call {
425 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
426 let callee = self.codegen_operand(&bx, func);
428 let (instance, mut llfn) = match callee.layout.ty.sty {
429 ty::FnDef(def_id, substs) => {
430 (Some(ty::Instance::resolve(bx.cx.tcx,
431 ty::ParamEnv::reveal_all(),
437 (None, Some(callee.immediate()))
439 _ => bug!("{} is not callable", callee.layout.ty)
441 let def = instance.map(|i| i.def);
442 let sig = callee.layout.ty.fn_sig(bx.tcx());
443 let sig = bx.tcx().normalize_erasing_late_bound_regions(
444 ty::ParamEnv::reveal_all(),
449 // Handle intrinsics old codegen wants Expr's for, ourselves.
450 let intrinsic = match def {
451 Some(ty::InstanceDef::Intrinsic(def_id))
452 => Some(bx.tcx().item_name(def_id).as_str()),
455 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
457 if intrinsic == Some("transmute") {
458 if let Some(destination_ref) = destination.as_ref() {
459 let &(ref dest, target) = destination_ref;
460 self.codegen_transmute(&bx, &args[0], dest);
461 funclet_br(self, bx, target);
463 // If we are trying to transmute to an uninhabited type,
464 // it is likely there is no allotted destination. In fact,
465 // transmuting to an uninhabited type is UB, which means
466 // we can do what we like. Here, we declare that transmuting
467 // into an uninhabited type is impossible, so anything following
468 // it must be unreachable.
469 assert_eq!(bx.cx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
475 let extra_args = &args[sig.inputs().len()..];
476 let extra_args = extra_args.iter().map(|op_arg| {
477 let op_ty = op_arg.ty(self.mir, bx.tcx());
478 self.monomorphize(&op_ty)
479 }).collect::<Vec<_>>();
481 let fn_ty = match def {
482 Some(ty::InstanceDef::Virtual(..)) => {
483 FnType::new_vtable(bx.cx, sig, &extra_args)
485 Some(ty::InstanceDef::DropGlue(_, None)) => {
486 // empty drop glue - a nop.
487 let &(_, target) = destination.as_ref().unwrap();
488 funclet_br(self, bx, target);
491 _ => FnType::new(bx.cx, sig, &extra_args)
494 // emit a panic instead of instantiating an uninhabited type
495 if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
496 fn_ty.ret.layout.abi.is_uninhabited()
498 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
499 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
500 let filename = C_str_slice(bx.cx, filename);
501 let line = C_u32(bx.cx, loc.line as u32);
502 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
503 let align = tcx.data_layout.aggregate_align
504 .max(tcx.data_layout.i32_align)
505 .max(tcx.data_layout.pointer_align);
508 "Attempted to instantiate uninhabited type {} using mem::{}",
510 if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
512 let msg_str = Symbol::intern(&str).as_str();
513 let msg_str = C_str_slice(bx.cx, msg_str);
514 let msg_file_line_col = C_struct(bx.cx,
515 &[msg_str, filename, line, col],
517 let msg_file_line_col = consts::addr_of(bx.cx,
522 // Obtain the panic entry point.
524 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
525 let instance = ty::Instance::mono(bx.tcx(), def_id);
526 let fn_ty = FnType::of_instance(bx.cx, &instance);
527 let llfn = callee::get_fn(bx.cx, instance);
529 // Codegen the actual panic invoke/call.
535 &[msg_file_line_col],
536 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
542 // The arguments we'll be passing. Plus one to account for outptr, if used.
543 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
544 let mut llargs = Vec::with_capacity(arg_count);
546 // Prepare the return value destination
547 let ret_dest = if let Some((ref dest, _)) = *destination {
548 let is_intrinsic = intrinsic.is_some();
549 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
555 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
556 use intrinsic::codegen_intrinsic_call;
558 let dest = match ret_dest {
559 _ if fn_ty.ret.is_indirect() => llargs[0],
560 ReturnDest::Nothing => {
561 C_undef(fn_ty.ret.memory_ty(bx.cx).ptr_to())
563 ReturnDest::IndirectOperand(dst, _) |
564 ReturnDest::Store(dst) => dst.llval,
565 ReturnDest::DirectOperand(_) =>
566 bug!("Cannot use direct operand with an intrinsic call")
569 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
570 // The indices passed to simd_shuffle* in the
571 // third argument must be constant. This is
572 // checked by const-qualification, which also
573 // promotes any complex rvalues to constants.
574 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
576 // The shuffle array argument is usually not an explicit constant,
577 // but specified directly in the code. This means it gets promoted
578 // and we can then extract the value by evaluating the promoted.
579 mir::Operand::Copy(mir::Place::Promoted(box(index, ty))) |
580 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
581 let param_env = ty::ParamEnv::reveal_all();
582 let cid = mir::interpret::GlobalId {
583 instance: self.instance,
584 promoted: Some(index),
586 let c = bx.tcx().const_eval(param_env.and(cid));
587 let (llval, ty) = self.simd_shuffle_indices(
589 terminator.source_info.span,
594 val: Immediate(llval),
595 layout: bx.cx.layout_of(ty),
599 mir::Operand::Copy(_) |
600 mir::Operand::Move(_) => {
601 span_bug!(span, "shuffle indices must be constant");
603 mir::Operand::Constant(ref constant) => {
604 let c = self.eval_mir_constant(&bx, constant);
605 let (llval, ty) = self.simd_shuffle_indices(
612 val: Immediate(llval),
613 layout: bx.cx.layout_of(ty)
619 self.codegen_operand(&bx, arg)
623 let callee_ty = instance.as_ref().unwrap().ty(bx.cx.tcx);
624 codegen_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
625 terminator.source_info.span);
627 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
628 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
631 if let Some((_, target)) = *destination {
632 funclet_br(self, bx, target);
640 // Split the rust-call tupled arguments off.
641 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
642 let (tup, args) = args.split_last().unwrap();
648 'make_args: for (i, arg) in first_args.iter().enumerate() {
649 let mut op = self.codegen_operand(&bx, arg);
651 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
652 if let Pair(..) = op.val {
653 // In the case of Rc<Self>, we need to explicitly pass a
654 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
655 // that is understood elsewhere in the compiler as a method on
657 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
658 // we get a value of a built-in pointer type
659 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
660 && !op.layout.ty.is_region_ptr()
662 'iter_fields: for i in 0..op.layout.fields.count() {
663 let field = op.extract_field(&bx, i);
664 if !field.layout.is_zst() {
665 // we found the one non-zero-sized field that is allowed
666 // now find *its* non-zero-sized field, or stop if it's a
669 continue 'descend_newtypes
673 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
676 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
677 // data pointer and vtable. Look up the method in the vtable, and pass
678 // the data pointer as the first argument
680 Pair(data_ptr, meta) => {
681 llfn = Some(meth::VirtualIndex::from_index(idx)
682 .get_fn(&bx, meta, &fn_ty));
683 llargs.push(data_ptr);
686 other => bug!("expected a Pair, got {:?}", other)
688 } else if let Ref(data_ptr, Some(meta), _) = op.val {
689 // by-value dynamic dispatch
690 llfn = Some(meth::VirtualIndex::from_index(idx)
691 .get_fn(&bx, meta, &fn_ty));
692 llargs.push(data_ptr);
695 span_bug!(span, "can't codegen a virtual call on {:?}", op);
699 // The callee needs to own the argument memory if we pass it
700 // by-ref, so make a local copy of non-immediate constants.
701 match (arg, op.val) {
702 (&mir::Operand::Copy(_), Ref(_, None, _)) |
703 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
704 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
705 op.val.store(&bx, tmp);
706 op.val = Ref(tmp.llval, None, tmp.align);
711 self.codegen_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
713 if let Some(tup) = untuple {
714 self.codegen_arguments_untupled(&bx, tup, &mut llargs,
715 &fn_ty.args[first_args.len()..])
718 let fn_ptr = match (llfn, instance) {
719 (Some(llfn), _) => llfn,
720 (None, Some(instance)) => callee::get_fn(bx.cx, instance),
721 _ => span_bug!(span, "no llfn for call"),
724 do_call(self, bx, fn_ty, fn_ptr, &llargs,
725 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
728 mir::TerminatorKind::GeneratorDrop |
729 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
730 mir::TerminatorKind::FalseEdges { .. } |
731 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
735 fn codegen_argument(&mut self,
736 bx: &Builder<'a, 'll, 'tcx>,
737 op: OperandRef<'tcx, &'ll Value>,
738 llargs: &mut Vec<&'ll Value>,
739 arg: &ArgType<'tcx, Ty<'tcx>>) {
740 // Fill padding with undef value, where applicable.
741 if let Some(ty) = arg.pad {
742 llargs.push(C_undef(ty.llvm_type(bx.cx)));
749 if let PassMode::Pair(..) = arg.mode {
756 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
758 } else if arg.is_unsized_indirect() {
760 Ref(a, Some(b), _) => {
765 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
769 // Force by-ref if we have to load through a cast pointer.
770 let (mut llval, align, by_ref) = match op.val {
771 Immediate(_) | Pair(..) => {
773 PassMode::Indirect(..) | PassMode::Cast(_) => {
774 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
775 op.val.store(bx, scratch);
776 (scratch.llval, scratch.align, true)
779 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
783 Ref(llval, _, align) => {
784 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
785 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
786 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
787 // have scary latent bugs around.
789 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
790 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
791 op.layout, MemFlags::empty());
792 (scratch.llval, scratch.align, true)
799 if by_ref && !arg.is_indirect() {
800 // Have to load the argument, maybe while casting it.
801 if let PassMode::Cast(ty) = arg.mode {
802 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx).ptr_to()),
803 align.min(arg.layout.align));
805 // We can't use `PlaceRef::load` here because the argument
806 // may have a type we don't treat as immediate, but the ABI
807 // used for this call is passing it by-value. In that case,
808 // the load would just produce `OperandValue::Ref` instead
809 // of the `OperandValue::Immediate` we need for the call.
810 llval = bx.load(llval, align);
811 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
812 if scalar.is_bool() {
813 bx.range_metadata(llval, 0..2);
816 // We store bools as i8 so we need to truncate to i1.
817 llval = base::to_immediate(bx, llval, arg.layout);
824 fn codegen_arguments_untupled(&mut self,
825 bx: &Builder<'a, 'll, 'tcx>,
826 operand: &mir::Operand<'tcx>,
827 llargs: &mut Vec<&'ll Value>,
828 args: &[ArgType<'tcx, Ty<'tcx>>]) {
829 let tuple = self.codegen_operand(bx, operand);
831 // Handle both by-ref and immediate tuples.
832 if let Ref(llval, None, align) = tuple.val {
833 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
834 for i in 0..tuple.layout.fields.count() {
835 let field_ptr = tuple_ptr.project_field(bx, i);
836 self.codegen_argument(bx, field_ptr.load(bx), llargs, &args[i]);
838 } else if let Ref(_, Some(_), _) = tuple.val {
839 bug!("closure arguments must be sized")
841 // If the tuple is immediate, the elements are as well.
842 for i in 0..tuple.layout.fields.count() {
843 let op = tuple.extract_field(bx, i);
844 self.codegen_argument(bx, op, llargs, &args[i]);
849 fn get_personality_slot(
851 bx: &Builder<'a, 'll, 'tcx, &'ll Value>
852 ) -> PlaceRef<'tcx, &'ll Value> {
854 if let Some(slot) = self.personality_slot {
857 let layout = cx.layout_of(cx.tcx.intern_tup(&[
858 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
861 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
862 self.personality_slot = Some(slot);
867 /// Return the landingpad wrapper around the given basic block
869 /// No-op in MSVC SEH scheme.
870 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> &'ll BasicBlock {
871 if let Some(block) = self.landing_pads[target_bb] {
875 let block = self.blocks[target_bb];
876 let landing_pad = self.landing_pad_uncached(block);
877 self.landing_pads[target_bb] = Some(landing_pad);
881 fn landing_pad_uncached(&mut self, target_bb: &'ll BasicBlock) -> &'ll BasicBlock {
882 if base::wants_msvc_seh(self.cx.sess()) {
883 span_bug!(self.mir.span, "landing pad was not inserted?")
886 let bx = self.new_block("cleanup");
888 let llpersonality = self.cx.eh_personality();
889 let llretty = self.landing_pad_type();
890 let lp = bx.landing_pad(llretty, llpersonality, 1);
893 let slot = self.get_personality_slot(&bx);
894 slot.storage_live(&bx);
895 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
901 fn landing_pad_type(&self) -> &'ll Type {
903 Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
906 fn unreachable_block(&mut self) -> &'ll BasicBlock {
907 self.unreachable_block.unwrap_or_else(|| {
908 let bl = self.new_block("unreachable");
910 self.unreachable_block = Some(bl.llbb());
915 pub fn new_block(&self, name: &str) -> Builder<'a, 'll, 'tcx> {
916 Builder::new_block(self.cx, self.llfn, name)
919 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'll, 'tcx> {
920 let bx = Builder::with_cx(self.cx);
921 bx.position_at_end(self.blocks[bb]);
925 fn make_return_dest(&mut self, bx: &Builder<'a, 'll, 'tcx>,
926 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
927 llargs: &mut Vec<&'ll Value>, is_intrinsic: bool)
928 -> ReturnDest<'tcx, &'ll Value> {
929 // If the return is ignored, we can just return a do-nothing ReturnDest
930 if fn_ret.is_ignore() {
931 return ReturnDest::Nothing;
933 let dest = if let mir::Place::Local(index) = *dest {
934 match self.locals[index] {
935 LocalRef::Place(dest) => dest,
936 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
937 LocalRef::Operand(None) => {
938 // Handle temporary places, specifically Operand ones, as
939 // they don't have allocas
940 return if fn_ret.is_indirect() {
941 // Odd, but possible, case, we have an operand temporary,
942 // but the calling convention has an indirect return.
943 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
944 tmp.storage_live(bx);
945 llargs.push(tmp.llval);
946 ReturnDest::IndirectOperand(tmp, index)
947 } else if is_intrinsic {
948 // Currently, intrinsics always need a location to store
949 // the result. so we create a temporary alloca for the
951 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
952 tmp.storage_live(bx);
953 ReturnDest::IndirectOperand(tmp, index)
955 ReturnDest::DirectOperand(index)
958 LocalRef::Operand(Some(_)) => {
959 bug!("place local already assigned to");
963 self.codegen_place(bx, dest)
965 if fn_ret.is_indirect() {
966 if dest.align.abi() < dest.layout.align.abi() {
967 // Currently, MIR code generation does not create calls
968 // that store directly to fields of packed structs (in
969 // fact, the calls it creates write only to temps),
971 // If someone changes that, please update this code path
972 // to create a temporary.
973 span_bug!(self.mir.span, "can't directly store to unaligned value");
975 llargs.push(dest.llval);
978 ReturnDest::Store(dest)
982 fn codegen_transmute(&mut self, bx: &Builder<'a, 'll, 'tcx>,
983 src: &mir::Operand<'tcx>,
984 dst: &mir::Place<'tcx>) {
985 if let mir::Place::Local(index) = *dst {
986 match self.locals[index] {
987 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
988 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
989 LocalRef::Operand(None) => {
990 let dst_layout = bx.cx.layout_of(self.monomorphized_place_ty(dst));
991 assert!(!dst_layout.ty.has_erasable_regions());
992 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
993 place.storage_live(bx);
994 self.codegen_transmute_into(bx, src, place);
995 let op = place.load(bx);
996 place.storage_dead(bx);
997 self.locals[index] = LocalRef::Operand(Some(op));
999 LocalRef::Operand(Some(op)) => {
1000 assert!(op.layout.is_zst(),
1001 "assigning to initialized SSAtemp");
1005 let dst = self.codegen_place(bx, dst);
1006 self.codegen_transmute_into(bx, src, dst);
1010 fn codegen_transmute_into(&mut self, bx: &Builder<'a, 'll, 'tcx>,
1011 src: &mir::Operand<'tcx>,
1012 dst: PlaceRef<'tcx, &'ll Value>) {
1013 let src = self.codegen_operand(bx, src);
1014 let llty = src.layout.llvm_type(bx.cx);
1015 let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
1016 let align = src.layout.align.min(dst.layout.align);
1017 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1021 // Stores the return value of a function call into it's final location.
1022 fn store_return(&mut self,
1023 bx: &Builder<'a, 'll, 'tcx>,
1024 dest: ReturnDest<'tcx, &'ll Value>,
1025 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1026 llval: &'ll Value) {
1027 use self::ReturnDest::*;
1031 Store(dst) => ret_ty.store(bx, llval, dst),
1032 IndirectOperand(tmp, index) => {
1033 let op = tmp.load(bx);
1034 tmp.storage_dead(bx);
1035 self.locals[index] = LocalRef::Operand(Some(op));
1037 DirectOperand(index) => {
1038 // If there is a cast, we have to store and reload.
1039 let op = if let PassMode::Cast(_) = ret_ty.mode {
1040 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1041 tmp.storage_live(bx);
1042 ret_ty.store(bx, llval, tmp);
1043 let op = tmp.load(bx);
1044 tmp.storage_dead(bx);
1047 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1049 self.locals[index] = LocalRef::Operand(Some(op));
1055 enum ReturnDest<'tcx, V> {
1056 // Do nothing, the return value is indirect or ignored
1058 // Store the return value to the pointer
1059 Store(PlaceRef<'tcx, V>),
1060 // Stores an indirect return value to an operand local place
1061 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1062 // Stores a direct return value to an operand local place
1063 DirectOperand(mir::Local)