1 use rustc_index::vec::Idx;
2 use rustc::middle::lang_items;
3 use rustc::ty::{self, Ty, TypeFoldable, Instance};
4 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, FnAbiExt};
5 use rustc::mir::{self, PlaceBase, Static, StaticKind};
6 use rustc::mir::interpret::PanicInfo;
7 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
8 use rustc_target::spec::abi::Abi;
11 use crate::common::{self, IntPredicate};
18 use syntax::{source_map::Span, symbol::Symbol};
20 use super::{FunctionCx, LocalRef};
21 use super::place::PlaceRef;
22 use super::operand::OperandRef;
23 use super::operand::OperandValue::{Pair, Ref, Immediate};
25 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
26 /// e.g., creating a basic block, calling a function, etc.
27 struct TerminatorCodegenHelper<'a, 'tcx> {
28 bb: &'a mir::BasicBlock,
29 terminator: &'a mir::Terminator<'tcx>,
30 funclet_bb: Option<mir::BasicBlock>,
33 impl<'a, 'tcx> TerminatorCodegenHelper<'a, 'tcx> {
34 /// Returns the associated funclet from `FunctionCx::funclets` for the
35 /// `funclet_bb` member if it is not `None`.
36 fn funclet<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
38 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
39 ) -> Option<&'c Bx::Funclet> {
40 match self.funclet_bb {
41 Some(funcl) => fx.funclets[funcl].as_ref(),
46 fn lltarget<'b, 'c, Bx: BuilderMethods<'b, 'tcx>>(
48 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
49 target: mir::BasicBlock,
50 ) -> (Bx::BasicBlock, bool) {
51 let span = self.terminator.source_info.span;
52 let lltarget = fx.blocks[target];
53 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
54 match (self.funclet_bb, target_funclet) {
55 (None, None) => (lltarget, false),
56 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) =>
58 // jump *into* cleanup - need a landing pad if GNU
59 (None, Some(_)) => (fx.landing_pad_to(target), false),
60 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
61 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
65 /// Create a basic block.
66 fn llblock<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
68 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
69 target: mir::BasicBlock,
71 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
73 // MSVC cross-funclet jump - need a trampoline
75 debug!("llblock: creating cleanup trampoline for {:?}", target);
76 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
77 let mut trampoline = fx.new_block(name);
78 trampoline.cleanup_ret(self.funclet(fx).unwrap(),
86 fn funclet_br<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
88 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
90 target: mir::BasicBlock,
92 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
94 // micro-optimization: generate a `ret` rather than a jump
96 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
102 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
103 /// return destination `destination` and the cleanup function `cleanup`.
104 fn do_call<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
106 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
108 fn_abi: FnAbi<'tcx, Ty<'tcx>>,
110 llargs: &[Bx::Value],
111 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
112 cleanup: Option<mir::BasicBlock>,
114 if let Some(cleanup) = cleanup {
115 let ret_bx = if let Some((_, target)) = destination {
118 fx.unreachable_block()
120 let invokeret = bx.invoke(fn_ptr,
123 self.llblock(fx, cleanup),
125 bx.apply_attrs_callsite(&fn_abi, invokeret);
127 if let Some((ret_dest, target)) = destination {
128 let mut ret_bx = fx.build_block(target);
129 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
130 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
133 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
134 bx.apply_attrs_callsite(&fn_abi, llret);
135 if fx.mir[*self.bb].is_cleanup {
136 // Cleanup is always the cold path. Don't inline
137 // drop glue. Also, when there is a deeply-nested
138 // struct, there are "symmetry" issues that cause
139 // exponential inlining - see issue #41696.
140 bx.do_not_inline(llret);
143 if let Some((ret_dest, target)) = destination {
144 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
145 self.funclet_br(fx, bx, target);
152 // Generate sideeffect intrinsic if jumping to any of the targets can form
154 fn maybe_sideeffect<'b, 'tcx2: 'b, Bx: BuilderMethods<'b, 'tcx2>>(
156 mir: &'b mir::Body<'tcx>,
158 targets: &[mir::BasicBlock],
160 if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
161 if targets.iter().any(|target| {
165 .is_predecessor_of(self.bb.start_location(), mir)
173 /// Codegen implementations for some terminator variants.
174 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
175 /// Generates code for a `Resume` terminator.
176 fn codegen_resume_terminator<'b>(
178 helper: TerminatorCodegenHelper<'b, 'tcx>,
181 if let Some(funclet) = helper.funclet(self) {
182 bx.cleanup_ret(funclet, None);
184 let slot = self.get_personality_slot(&mut bx);
185 let lp0 = slot.project_field(&mut bx, 0);
186 let lp0 = bx.load_operand(lp0).immediate();
187 let lp1 = slot.project_field(&mut bx, 1);
188 let lp1 = bx.load_operand(lp1).immediate();
189 slot.storage_dead(&mut bx);
191 if !bx.sess().target.target.options.custom_unwind_resume {
192 let mut lp = bx.const_undef(self.landing_pad_type());
193 lp = bx.insert_value(lp, lp0, 0);
194 lp = bx.insert_value(lp, lp1, 1);
197 bx.call(bx.eh_unwind_resume(), &[lp0],
198 helper.funclet(self));
204 fn codegen_switchint_terminator<'b>(
206 helper: TerminatorCodegenHelper<'b, 'tcx>,
208 discr: &mir::Operand<'tcx>,
210 values: &Cow<'tcx, [u128]>,
211 targets: &Vec<mir::BasicBlock>,
213 let discr = self.codegen_operand(&mut bx, &discr);
214 if targets.len() == 2 {
215 // If there are two targets, emit br instead of switch
216 let lltrue = helper.llblock(self, targets[0]);
217 let llfalse = helper.llblock(self, targets[1]);
218 if switch_ty == bx.tcx().types.bool {
219 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
220 // Don't generate trivial icmps when switching on bool
221 if let [0] = values[..] {
222 bx.cond_br(discr.immediate(), llfalse, lltrue);
224 assert_eq!(&values[..], &[1]);
225 bx.cond_br(discr.immediate(), lltrue, llfalse);
228 let switch_llty = bx.immediate_backend_type(
229 bx.layout_of(switch_ty)
231 let llval = bx.const_uint_big(switch_llty, values[0]);
232 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
233 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
234 bx.cond_br(cmp, lltrue, llfalse);
237 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
238 let (otherwise, targets) = targets.split_last().unwrap();
241 helper.llblock(self, *otherwise),
242 values.iter().zip(targets).map(|(&value, target)| {
243 (value, helper.llblock(self, *target))
249 fn codegen_return_terminator(&mut self, mut bx: Bx) {
250 // Call `va_end` if this is the definition of a C-variadic function.
251 if self.fn_abi.c_variadic {
252 // The `VaList` "spoofed" argument is just after all the real arguments.
253 let va_list_arg_idx = self.fn_abi.args.len();
254 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
255 LocalRef::Place(va_list) => {
256 bx.va_end(va_list.llval);
258 _ => bug!("C-variadic function must have a `VaList` place"),
261 if self.fn_abi.ret.layout.abi.is_uninhabited() {
262 // Functions with uninhabited return values are marked `noreturn`,
263 // so we should make sure that we never actually do.
268 let llval = match self.fn_abi.ret.mode {
269 PassMode::Ignore | PassMode::Indirect(..) => {
274 PassMode::Direct(_) | PassMode::Pair(..) => {
276 self.codegen_consume(&mut bx, &mir::Place::return_place().as_ref());
277 if let Ref(llval, _, align) = op.val {
278 bx.load(llval, align)
280 op.immediate_or_packed_pair(&mut bx)
284 PassMode::Cast(cast_ty) => {
285 let op = match self.locals[mir::RETURN_PLACE] {
286 LocalRef::Operand(Some(op)) => op,
287 LocalRef::Operand(None) => bug!("use of return before def"),
288 LocalRef::Place(cg_place) => {
290 val: Ref(cg_place.llval, None, cg_place.align),
291 layout: cg_place.layout
294 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
296 let llslot = match op.val {
297 Immediate(_) | Pair(..) => {
299 PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
300 op.val.store(&mut bx, scratch);
303 Ref(llval, _, align) => {
304 assert_eq!(align, op.layout.align.abi,
305 "return place is unaligned!");
309 let addr = bx.pointercast(llslot, bx.type_ptr_to(
310 bx.cast_backend_type(&cast_ty)
312 bx.load(addr, self.fn_abi.ret.layout.align.abi)
319 fn codegen_drop_terminator<'b>(
321 helper: TerminatorCodegenHelper<'b, 'tcx>,
323 location: &mir::Place<'tcx>,
324 target: mir::BasicBlock,
325 unwind: Option<mir::BasicBlock>,
327 let ty = location.ty(self.mir, bx.tcx()).ty;
328 let ty = self.monomorphize(&ty);
329 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
331 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
332 // we don't actually need to drop anything.
333 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
334 helper.funclet_br(self, &mut bx, target);
338 let place = self.codegen_place(&mut bx, &location.as_ref());
340 let mut args = if let Some(llextra) = place.llextra {
341 args2 = [place.llval, llextra];
344 args1 = [place.llval];
347 let (drop_fn, fn_abi) = match ty.kind {
349 let sig = drop_fn.fn_sig(self.cx.tcx());
350 let sig = self.cx.tcx().normalize_erasing_late_bound_regions(
351 ty::ParamEnv::reveal_all(),
354 let fn_abi = FnAbi::new_vtable(&bx, sig, &[]);
355 let vtable = args[1];
357 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
360 (bx.get_fn_addr(drop_fn),
361 FnAbi::of_instance(&bx, drop_fn))
364 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
365 helper.do_call(self, &mut bx, fn_abi, drop_fn, args,
366 Some((ReturnDest::Nothing, target)),
370 fn codegen_assert_terminator<'b>(
372 helper: TerminatorCodegenHelper<'b, 'tcx>,
374 terminator: &mir::Terminator<'tcx>,
375 cond: &mir::Operand<'tcx>,
377 msg: &mir::AssertMessage<'tcx>,
378 target: mir::BasicBlock,
379 cleanup: Option<mir::BasicBlock>,
381 let span = terminator.source_info.span;
382 let cond = self.codegen_operand(&mut bx, cond).immediate();
383 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
385 // This case can currently arise only from functions marked
386 // with #[rustc_inherit_overflow_checks] and inlined from
387 // another crate (mostly core::num generic/#[inline] fns),
388 // while the current crate doesn't use overflow checks.
389 // NOTE: Unlike binops, negation doesn't have its own
390 // checked operation, just a comparison with the minimum
391 // value, so we have to check for the assert message.
392 if !bx.check_overflow() {
393 if let PanicInfo::OverflowNeg = *msg {
394 const_cond = Some(expected);
398 // Don't codegen the panic block if success if known.
399 if const_cond == Some(expected) {
400 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
401 helper.funclet_br(self, &mut bx, target);
405 // Pass the condition through llvm.expect for branch hinting.
406 let cond = bx.expect(cond, expected);
408 // Create the failure block and the conditional branch to it.
409 let lltarget = helper.llblock(self, target);
410 let panic_block = self.new_block("panic");
411 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
413 bx.cond_br(cond, lltarget, panic_block.llbb());
415 bx.cond_br(cond, panic_block.llbb(), lltarget);
418 // After this point, bx is the block for the call to panic.
420 self.set_debug_loc(&mut bx, terminator.source_info);
422 // Get the location information.
423 let location = self.get_caller_location(&mut bx, span).immediate();
425 // Put together the arguments to the panic entry point.
426 let (lang_item, args) = match msg {
427 PanicInfo::BoundsCheck { ref len, ref index } => {
428 let len = self.codegen_operand(&mut bx, len).immediate();
429 let index = self.codegen_operand(&mut bx, index).immediate();
430 (lang_items::PanicBoundsCheckFnLangItem, vec![location, index, len])
433 let msg_str = Symbol::intern(msg.description());
434 let msg = bx.const_str(msg_str);
435 (lang_items::PanicFnLangItem, vec![msg.0, msg.1, location])
439 // Obtain the panic entry point.
440 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
441 let instance = ty::Instance::mono(bx.tcx(), def_id);
442 let fn_abi = FnAbi::of_instance(&bx, instance);
443 let llfn = bx.get_fn_addr(instance);
445 // Codegen the actual panic invoke/call.
446 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
449 fn codegen_call_terminator<'b>(
451 helper: TerminatorCodegenHelper<'b, 'tcx>,
453 terminator: &mir::Terminator<'tcx>,
454 func: &mir::Operand<'tcx>,
455 args: &Vec<mir::Operand<'tcx>>,
456 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
457 cleanup: Option<mir::BasicBlock>,
459 let span = terminator.source_info.span;
460 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
461 let callee = self.codegen_operand(&mut bx, func);
463 let (instance, mut llfn) = match callee.layout.ty.kind {
464 ty::FnDef(def_id, substs) => {
465 (Some(ty::Instance::resolve(bx.tcx(),
466 ty::ParamEnv::reveal_all(),
472 (None, Some(callee.immediate()))
474 _ => bug!("{} is not callable", callee.layout.ty),
476 let def = instance.map(|i| i.def);
477 let sig = callee.layout.ty.fn_sig(bx.tcx());
478 let sig = bx.tcx().normalize_erasing_late_bound_regions(
479 ty::ParamEnv::reveal_all(),
484 // Handle intrinsics old codegen wants Expr's for, ourselves.
485 let intrinsic = match def {
486 Some(ty::InstanceDef::Intrinsic(def_id)) =>
487 Some(bx.tcx().item_name(def_id).as_str()),
490 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
492 if intrinsic == Some("transmute") {
493 if let Some(destination_ref) = destination.as_ref() {
494 let &(ref dest, target) = destination_ref;
495 self.codegen_transmute(&mut bx, &args[0], dest);
496 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
497 helper.funclet_br(self, &mut bx, target);
499 // If we are trying to transmute to an uninhabited type,
500 // it is likely there is no allotted destination. In fact,
501 // transmuting to an uninhabited type is UB, which means
502 // we can do what we like. Here, we declare that transmuting
503 // into an uninhabited type is impossible, so anything following
504 // it must be unreachable.
505 assert_eq!(bx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
511 let extra_args = &args[sig.inputs().len()..];
512 let extra_args = extra_args.iter().map(|op_arg| {
513 let op_ty = op_arg.ty(self.mir, bx.tcx());
514 self.monomorphize(&op_ty)
515 }).collect::<Vec<_>>();
517 let fn_abi = match def {
518 Some(ty::InstanceDef::Virtual(..)) => {
519 FnAbi::new_vtable(&bx, sig, &extra_args)
521 Some(ty::InstanceDef::DropGlue(_, None)) => {
522 // Empty drop glue; a no-op.
523 let &(_, target) = destination.as_ref().unwrap();
524 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
525 helper.funclet_br(self, &mut bx, target);
528 _ => FnAbi::new(&bx, sig, &extra_args)
531 // For normal codegen, this Miri-specific intrinsic is just a NOP.
532 if intrinsic == Some("miri_start_panic") {
533 let target = destination.as_ref().unwrap().1;
534 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
535 helper.funclet_br(self, &mut bx, target);
539 // Emit a panic or a no-op for `panic_if_uninhabited`.
540 if intrinsic == Some("panic_if_uninhabited") {
541 let ty = instance.unwrap().substs.type_at(0);
542 let layout = bx.layout_of(ty);
543 if layout.abi.is_uninhabited() {
544 let msg_str = format!("Attempted to instantiate uninhabited type {}", ty);
545 let msg = bx.const_str(Symbol::intern(&msg_str));
546 let location = self.get_caller_location(&mut bx, span).immediate();
548 // Obtain the panic entry point.
550 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
551 let instance = ty::Instance::mono(bx.tcx(), def_id);
552 let fn_abi = FnAbi::of_instance(&bx, instance);
553 let llfn = bx.get_fn_addr(instance);
555 if let Some((_, target)) = destination.as_ref() {
556 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
558 // Codegen the actual panic invoke/call.
564 &[msg.0, msg.1, location],
565 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
570 let target = destination.as_ref().unwrap().1;
571 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
572 helper.funclet_br(self, &mut bx, target);
577 // The arguments we'll be passing. Plus one to account for outptr, if used.
578 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
579 let mut llargs = Vec::with_capacity(arg_count);
581 // Prepare the return value destination
582 let ret_dest = if let Some((ref dest, _)) = *destination {
583 let is_intrinsic = intrinsic.is_some();
584 self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs,
590 if intrinsic == Some("caller_location") {
591 if let Some((_, target)) = destination.as_ref() {
592 let location = self.get_caller_location(&mut bx, span);
594 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
595 location.val.store(&mut bx, tmp);
597 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
599 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
600 helper.funclet_br(self, &mut bx, *target);
605 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
606 let dest = match ret_dest {
607 _ if fn_abi.ret.is_indirect() => llargs[0],
608 ReturnDest::Nothing =>
609 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret))),
610 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) =>
612 ReturnDest::DirectOperand(_) =>
613 bug!("Cannot use direct operand with an intrinsic call"),
616 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
617 // The indices passed to simd_shuffle* in the
618 // third argument must be constant. This is
619 // checked by const-qualification, which also
620 // promotes any complex rvalues to constants.
621 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
623 // The shuffle array argument is usually not an explicit constant,
624 // but specified directly in the code. This means it gets promoted
625 // and we can then extract the value by evaluating the promoted.
626 mir::Operand::Copy(place) | mir::Operand::Move(place) => {
627 if let mir::PlaceRef {
629 &PlaceBase::Static(box Static {
630 kind: StaticKind::Promoted(promoted, _),
637 let param_env = ty::ParamEnv::reveal_all();
638 let cid = mir::interpret::GlobalId {
639 instance: self.instance,
640 promoted: Some(promoted),
642 let c = bx.tcx().const_eval(param_env.and(cid));
643 let (llval, ty) = self.simd_shuffle_indices(
645 terminator.source_info.span,
650 val: Immediate(llval),
651 layout: bx.layout_of(ty),
654 span_bug!(span, "shuffle indices must be constant");
658 mir::Operand::Constant(constant) => {
659 let c = self.eval_mir_constant(constant);
660 let (llval, ty) = self.simd_shuffle_indices(
667 val: Immediate(llval),
668 layout: bx.layout_of(ty)
674 self.codegen_operand(&mut bx, arg)
678 bx.codegen_intrinsic_call(*instance.as_ref().unwrap(), &fn_abi, &args, dest,
679 terminator.source_info.span);
681 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
682 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
685 if let Some((_, target)) = *destination {
686 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
687 helper.funclet_br(self, &mut bx, target);
695 // Split the rust-call tupled arguments off.
696 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
697 let (tup, args) = args.split_last().unwrap();
703 'make_args: for (i, arg) in first_args.iter().enumerate() {
704 let mut op = self.codegen_operand(&mut bx, arg);
706 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
707 if let Pair(..) = op.val {
708 // In the case of Rc<Self>, we need to explicitly pass a
709 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
710 // that is understood elsewhere in the compiler as a method on
712 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
713 // we get a value of a built-in pointer type
714 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
715 && !op.layout.ty.is_region_ptr()
717 'iter_fields: for i in 0..op.layout.fields.count() {
718 let field = op.extract_field(&mut bx, i);
719 if !field.layout.is_zst() {
720 // we found the one non-zero-sized field that is allowed
721 // now find *its* non-zero-sized field, or stop if it's a
724 continue 'descend_newtypes
728 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
731 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
732 // data pointer and vtable. Look up the method in the vtable, and pass
733 // the data pointer as the first argument
735 Pair(data_ptr, meta) => {
736 llfn = Some(meth::VirtualIndex::from_index(idx)
737 .get_fn(&mut bx, meta, &fn_abi));
738 llargs.push(data_ptr);
741 other => bug!("expected a Pair, got {:?}", other),
743 } else if let Ref(data_ptr, Some(meta), _) = op.val {
744 // by-value dynamic dispatch
745 llfn = Some(meth::VirtualIndex::from_index(idx)
746 .get_fn(&mut bx, meta, &fn_abi));
747 llargs.push(data_ptr);
750 span_bug!(span, "can't codegen a virtual call on {:?}", op);
754 // The callee needs to own the argument memory if we pass it
755 // by-ref, so make a local copy of non-immediate constants.
756 match (arg, op.val) {
757 (&mir::Operand::Copy(_), Ref(_, None, _)) |
758 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
759 let tmp = PlaceRef::alloca(&mut bx, op.layout);
760 op.val.store(&mut bx, tmp);
761 op.val = Ref(tmp.llval, None, tmp.align);
766 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
768 if let Some(tup) = untuple {
769 self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
770 &fn_abi.args[first_args.len()..])
773 let fn_ptr = match (llfn, instance) {
774 (Some(llfn), _) => llfn,
775 (None, Some(instance)) => bx.get_fn_addr(instance),
776 _ => span_bug!(span, "no llfn for call"),
779 if let Some((_, target)) = destination.as_ref() {
780 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
782 helper.do_call(self, &mut bx, fn_abi, fn_ptr, &llargs,
783 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
788 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
789 pub fn codegen_block(
793 let mut bx = self.build_block(bb);
794 let data = &self.mir[bb];
796 debug!("codegen_block({:?}={:?})", bb, data);
798 for statement in &data.statements {
799 bx = self.codegen_statement(bx, statement);
802 self.codegen_terminator(bx, bb, data.terminator());
805 fn codegen_terminator(
809 terminator: &mir::Terminator<'tcx>
811 debug!("codegen_terminator: {:?}", terminator);
813 // Create the cleanup bundle, if needed.
814 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
815 let helper = TerminatorCodegenHelper {
816 bb: &bb, terminator, funclet_bb
819 self.set_debug_loc(&mut bx, terminator.source_info);
820 match terminator.kind {
821 mir::TerminatorKind::Resume => {
822 self.codegen_resume_terminator(helper, bx)
825 mir::TerminatorKind::Abort => {
830 mir::TerminatorKind::Goto { target } => {
831 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
832 helper.funclet_br(self, &mut bx, target);
835 mir::TerminatorKind::SwitchInt {
836 ref discr, switch_ty, ref values, ref targets
838 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
842 mir::TerminatorKind::Return => {
843 self.codegen_return_terminator(bx);
846 mir::TerminatorKind::Unreachable => {
850 mir::TerminatorKind::Drop { ref location, target, unwind } => {
851 self.codegen_drop_terminator(helper, bx, location, target, unwind);
854 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
855 self.codegen_assert_terminator(helper, bx, terminator, cond,
856 expected, msg, target, cleanup);
859 mir::TerminatorKind::DropAndReplace { .. } => {
860 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
863 mir::TerminatorKind::Call {
870 self.codegen_call_terminator(helper, bx, terminator, func,
871 args, destination, cleanup);
873 mir::TerminatorKind::GeneratorDrop |
874 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
875 mir::TerminatorKind::FalseEdges { .. } |
876 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
883 op: OperandRef<'tcx, Bx::Value>,
884 llargs: &mut Vec<Bx::Value>,
885 arg: &ArgAbi<'tcx, Ty<'tcx>>
887 // Fill padding with undef value, where applicable.
888 if let Some(ty) = arg.pad {
889 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
896 if let PassMode::Pair(..) = arg.mode {
903 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
905 } else if arg.is_unsized_indirect() {
907 Ref(a, Some(b), _) => {
912 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
916 // Force by-ref if we have to load through a cast pointer.
917 let (mut llval, align, by_ref) = match op.val {
918 Immediate(_) | Pair(..) => {
920 PassMode::Indirect(..) | PassMode::Cast(_) => {
921 let scratch = PlaceRef::alloca(bx, arg.layout);
922 op.val.store(bx, scratch);
923 (scratch.llval, scratch.align, true)
926 (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
930 Ref(llval, _, align) => {
931 if arg.is_indirect() && align < arg.layout.align.abi {
932 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
933 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
934 // have scary latent bugs around.
936 let scratch = PlaceRef::alloca(bx, arg.layout);
937 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
938 op.layout, MemFlags::empty());
939 (scratch.llval, scratch.align, true)
946 if by_ref && !arg.is_indirect() {
947 // Have to load the argument, maybe while casting it.
948 if let PassMode::Cast(ty) = arg.mode {
949 let addr = bx.pointercast(llval, bx.type_ptr_to(
950 bx.cast_backend_type(&ty))
952 llval = bx.load(addr, align.min(arg.layout.align.abi));
954 // We can't use `PlaceRef::load` here because the argument
955 // may have a type we don't treat as immediate, but the ABI
956 // used for this call is passing it by-value. In that case,
957 // the load would just produce `OperandValue::Ref` instead
958 // of the `OperandValue::Immediate` we need for the call.
959 llval = bx.load(llval, align);
960 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
961 if scalar.is_bool() {
962 bx.range_metadata(llval, 0..2);
965 // We store bools as `i8` so we need to truncate to `i1`.
966 llval = base::to_immediate(bx, llval, arg.layout);
973 fn codegen_arguments_untupled(
976 operand: &mir::Operand<'tcx>,
977 llargs: &mut Vec<Bx::Value>,
978 args: &[ArgAbi<'tcx, Ty<'tcx>>]
980 let tuple = self.codegen_operand(bx, operand);
982 // Handle both by-ref and immediate tuples.
983 if let Ref(llval, None, align) = tuple.val {
984 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
985 for i in 0..tuple.layout.fields.count() {
986 let field_ptr = tuple_ptr.project_field(bx, i);
987 let field = bx.load_operand(field_ptr);
988 self.codegen_argument(bx, field, llargs, &args[i]);
990 } else if let Ref(_, Some(_), _) = tuple.val {
991 bug!("closure arguments must be sized")
993 // If the tuple is immediate, the elements are as well.
994 for i in 0..tuple.layout.fields.count() {
995 let op = tuple.extract_field(bx, i);
996 self.codegen_argument(bx, op, llargs, &args[i]);
1001 fn get_caller_location(
1005 ) -> OperandRef<'tcx, Bx::Value> {
1006 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1007 let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1008 let const_loc = bx.tcx().const_caller_location((
1009 Symbol::intern(&caller.file.name.to_string()),
1011 caller.col_display as u32 + 1,
1013 OperandRef::from_const(bx, const_loc)
1016 fn get_personality_slot(
1019 ) -> PlaceRef<'tcx, Bx::Value> {
1021 if let Some(slot) = self.personality_slot {
1024 let layout = cx.layout_of(cx.tcx().intern_tup(&[
1025 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
1028 let slot = PlaceRef::alloca(bx, layout);
1029 self.personality_slot = Some(slot);
1034 /// Returns the landing-pad wrapper around the given basic block.
1036 /// No-op in MSVC SEH scheme.
1039 target_bb: mir::BasicBlock
1040 ) -> Bx::BasicBlock {
1041 if let Some(block) = self.landing_pads[target_bb] {
1045 let block = self.blocks[target_bb];
1046 let landing_pad = self.landing_pad_uncached(block);
1047 self.landing_pads[target_bb] = Some(landing_pad);
1051 fn landing_pad_uncached(
1053 target_bb: Bx::BasicBlock
1054 ) -> Bx::BasicBlock {
1055 if base::wants_msvc_seh(self.cx.sess()) {
1056 span_bug!(self.mir.span, "landing pad was not inserted?")
1059 let mut bx = self.new_block("cleanup");
1061 let llpersonality = self.cx.eh_personality();
1062 let llretty = self.landing_pad_type();
1063 let lp = bx.landing_pad(llretty, llpersonality, 1);
1066 let slot = self.get_personality_slot(&mut bx);
1067 slot.storage_live(&mut bx);
1068 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1074 fn landing_pad_type(&self) -> Bx::Type {
1076 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1079 fn unreachable_block(
1081 ) -> Bx::BasicBlock {
1082 self.unreachable_block.unwrap_or_else(|| {
1083 let mut bx = self.new_block("unreachable");
1085 self.unreachable_block = Some(bx.llbb());
1090 pub fn new_block(&self, name: &str) -> Bx {
1091 Bx::new_block(self.cx, self.llfn, name)
1098 let mut bx = Bx::with_cx(self.cx);
1099 bx.position_at_end(self.blocks[bb]);
1103 fn make_return_dest(
1106 dest: &mir::Place<'tcx>,
1107 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1108 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1109 ) -> ReturnDest<'tcx, Bx::Value> {
1110 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1111 if fn_ret.is_ignore() {
1112 return ReturnDest::Nothing;
1114 let dest = if let Some(index) = dest.as_local() {
1115 match self.locals[index] {
1116 LocalRef::Place(dest) => dest,
1117 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1118 LocalRef::Operand(None) => {
1119 // Handle temporary places, specifically `Operand` ones, as
1120 // they don't have `alloca`s.
1121 return if fn_ret.is_indirect() {
1122 // Odd, but possible, case, we have an operand temporary,
1123 // but the calling convention has an indirect return.
1124 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1125 tmp.storage_live(bx);
1126 llargs.push(tmp.llval);
1127 ReturnDest::IndirectOperand(tmp, index)
1128 } else if is_intrinsic {
1129 // Currently, intrinsics always need a location to store
1130 // the result, so we create a temporary `alloca` for the
1132 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1133 tmp.storage_live(bx);
1134 ReturnDest::IndirectOperand(tmp, index)
1136 ReturnDest::DirectOperand(index)
1139 LocalRef::Operand(Some(_)) => {
1140 bug!("place local already assigned to");
1144 self.codegen_place(bx, &mir::PlaceRef {
1146 projection: &dest.projection,
1149 if fn_ret.is_indirect() {
1150 if dest.align < dest.layout.align.abi {
1151 // Currently, MIR code generation does not create calls
1152 // that store directly to fields of packed structs (in
1153 // fact, the calls it creates write only to temps).
1155 // If someone changes that, please update this code path
1156 // to create a temporary.
1157 span_bug!(self.mir.span, "can't directly store to unaligned value");
1159 llargs.push(dest.llval);
1162 ReturnDest::Store(dest)
1166 fn codegen_transmute(
1169 src: &mir::Operand<'tcx>,
1170 dst: &mir::Place<'tcx>
1172 if let Some(index) = dst.as_local() {
1173 match self.locals[index] {
1174 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1175 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1176 LocalRef::Operand(None) => {
1177 let dst_layout = bx.layout_of(self.monomorphized_place_ty(&dst.as_ref()));
1178 assert!(!dst_layout.ty.has_erasable_regions());
1179 let place = PlaceRef::alloca(bx, dst_layout);
1180 place.storage_live(bx);
1181 self.codegen_transmute_into(bx, src, place);
1182 let op = bx.load_operand(place);
1183 place.storage_dead(bx);
1184 self.locals[index] = LocalRef::Operand(Some(op));
1186 LocalRef::Operand(Some(op)) => {
1187 assert!(op.layout.is_zst(),
1188 "assigning to initialized SSAtemp");
1192 let dst = self.codegen_place(bx, &dst.as_ref());
1193 self.codegen_transmute_into(bx, src, dst);
1197 fn codegen_transmute_into(
1200 src: &mir::Operand<'tcx>,
1201 dst: PlaceRef<'tcx, Bx::Value>
1203 let src = self.codegen_operand(bx, src);
1204 let llty = bx.backend_type(src.layout);
1205 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1206 let align = src.layout.align.abi.min(dst.align);
1207 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1211 // Stores the return value of a function call into it's final location.
1215 dest: ReturnDest<'tcx, Bx::Value>,
1216 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1219 use self::ReturnDest::*;
1223 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1224 IndirectOperand(tmp, index) => {
1225 let op = bx.load_operand(tmp);
1226 tmp.storage_dead(bx);
1227 self.locals[index] = LocalRef::Operand(Some(op));
1229 DirectOperand(index) => {
1230 // If there is a cast, we have to store and reload.
1231 let op = if let PassMode::Cast(_) = ret_abi.mode {
1232 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1233 tmp.storage_live(bx);
1234 bx.store_arg(&ret_abi, llval, tmp);
1235 let op = bx.load_operand(tmp);
1236 tmp.storage_dead(bx);
1239 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1241 self.locals[index] = LocalRef::Operand(Some(op));
1247 enum ReturnDest<'tcx, V> {
1248 // Do nothing; the return value is indirect or ignored.
1250 // Store the return value to the pointer.
1251 Store(PlaceRef<'tcx, V>),
1252 // Store an indirect return value to an operand local place.
1253 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1254 // Store a direct return value to an operand local place.
1255 DirectOperand(mir::Local)