1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
7 use crate::common::{self, IntPredicate};
13 use rustc_hir::lang_items::LangItem;
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir;
16 use rustc_middle::mir::interpret::ConstValue;
17 use rustc_middle::mir::AssertKind;
18 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
19 use rustc_middle::ty::print::with_no_trimmed_paths;
20 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
24 use rustc_target::abi::{self, LayoutOf};
25 use rustc_target::spec::abi::Abi;
29 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
30 /// e.g., creating a basic block, calling a function, etc.
31 struct TerminatorCodegenHelper<'tcx> {
33 terminator: &'tcx mir::Terminator<'tcx>,
34 funclet_bb: Option<mir::BasicBlock>,
37 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
38 /// Returns the associated funclet from `FunctionCx::funclets` for the
39 /// `funclet_bb` member if it is not `None`.
40 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
42 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
43 ) -> Option<&'b Bx::Funclet> {
44 match self.funclet_bb {
45 Some(funcl) => fx.funclets[funcl].as_ref(),
50 fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
52 fx: &mut FunctionCx<'a, 'tcx, Bx>,
53 target: mir::BasicBlock,
54 ) -> (Bx::BasicBlock, bool) {
55 let span = self.terminator.source_info.span;
56 let lltarget = fx.blocks[target];
57 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
58 match (self.funclet_bb, target_funclet) {
59 (None, None) => (lltarget, false),
60 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
63 // jump *into* cleanup - need a landing pad if GNU
64 (None, Some(_)) => (fx.landing_pad_to(target), false),
65 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
66 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
70 /// Create a basic block.
71 fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
73 fx: &mut FunctionCx<'a, 'tcx, Bx>,
74 target: mir::BasicBlock,
76 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
78 // MSVC cross-funclet jump - need a trampoline
80 debug!("llblock: creating cleanup trampoline for {:?}", target);
81 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
82 let mut trampoline = fx.new_block(name);
83 trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
90 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
92 fx: &mut FunctionCx<'a, 'tcx, Bx>,
94 target: mir::BasicBlock,
96 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
98 // micro-optimization: generate a `ret` rather than a jump
100 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
106 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
107 /// return destination `destination` and the cleanup function `cleanup`.
108 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
110 fx: &mut FunctionCx<'a, 'tcx, Bx>,
112 fn_abi: FnAbi<'tcx, Ty<'tcx>>,
114 llargs: &[Bx::Value],
115 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
116 cleanup: Option<mir::BasicBlock>,
118 // If there is a cleanup block and the function we're calling can unwind, then
119 // do an invoke, otherwise do a call.
120 if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
121 let ret_bx = if let Some((_, target)) = destination {
124 fx.unreachable_block()
127 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
128 bx.apply_attrs_callsite(&fn_abi, invokeret);
130 if let Some((ret_dest, target)) = destination {
131 let mut ret_bx = fx.build_block(target);
132 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
133 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
136 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
137 bx.apply_attrs_callsite(&fn_abi, llret);
138 if fx.mir[self.bb].is_cleanup {
139 // Cleanup is always the cold path. Don't inline
140 // drop glue. Also, when there is a deeply-nested
141 // struct, there are "symmetry" issues that cause
142 // exponential inlining - see issue #41696.
143 bx.do_not_inline(llret);
146 if let Some((ret_dest, target)) = destination {
147 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
148 self.funclet_br(fx, bx, target);
155 // Generate sideeffect intrinsic if jumping to any of the targets can form
157 fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
159 mir: &'tcx mir::Body<'tcx>,
161 targets: &[mir::BasicBlock],
163 if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
164 if targets.iter().any(|&target| {
166 && target.start_location().is_predecessor_of(self.bb.start_location(), mir)
174 /// Codegen implementations for some terminator variants.
175 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
176 /// Generates code for a `Resume` terminator.
177 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
178 if let Some(funclet) = helper.funclet(self) {
179 bx.cleanup_ret(funclet, None);
181 let slot = self.get_personality_slot(&mut bx);
182 let lp0 = slot.project_field(&mut bx, 0);
183 let lp0 = bx.load_operand(lp0).immediate();
184 let lp1 = slot.project_field(&mut bx, 1);
185 let lp1 = bx.load_operand(lp1).immediate();
186 slot.storage_dead(&mut bx);
188 let mut lp = bx.const_undef(self.landing_pad_type());
189 lp = bx.insert_value(lp, lp0, 0);
190 lp = bx.insert_value(lp, lp1, 1);
195 fn codegen_switchint_terminator(
197 helper: TerminatorCodegenHelper<'tcx>,
199 discr: &mir::Operand<'tcx>,
201 values: &Cow<'tcx, [u128]>,
202 targets: &Vec<mir::BasicBlock>,
204 let discr = self.codegen_operand(&mut bx, &discr);
205 // `switch_ty` is redundant, sanity-check that.
206 assert_eq!(discr.layout.ty, switch_ty);
207 if targets.len() == 2 {
208 // If there are two targets, emit br instead of switch
209 let lltrue = helper.llblock(self, targets[0]);
210 let llfalse = helper.llblock(self, targets[1]);
211 if switch_ty == bx.tcx().types.bool {
212 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
213 // Don't generate trivial icmps when switching on bool
214 if let [0] = values[..] {
215 bx.cond_br(discr.immediate(), llfalse, lltrue);
217 assert_eq!(&values[..], &[1]);
218 bx.cond_br(discr.immediate(), lltrue, llfalse);
221 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
222 let llval = bx.const_uint_big(switch_llty, values[0]);
223 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
224 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
225 bx.cond_br(cmp, lltrue, llfalse);
228 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
229 let (otherwise, targets) = targets.split_last().unwrap();
232 helper.llblock(self, *otherwise),
236 .map(|(&value, target)| (value, helper.llblock(self, *target))),
241 fn codegen_return_terminator(&mut self, mut bx: Bx) {
242 // Call `va_end` if this is the definition of a C-variadic function.
243 if self.fn_abi.c_variadic {
244 // The `VaList` "spoofed" argument is just after all the real arguments.
245 let va_list_arg_idx = self.fn_abi.args.len();
246 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
247 LocalRef::Place(va_list) => {
248 bx.va_end(va_list.llval);
250 _ => bug!("C-variadic function must have a `VaList` place"),
253 if self.fn_abi.ret.layout.abi.is_uninhabited() {
254 // Functions with uninhabited return values are marked `noreturn`,
255 // so we should make sure that we never actually do.
256 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
257 // if that turns out to be helpful.
259 // `abort` does not terminate the block, so we still need to generate
260 // an `unreachable` terminator after it.
264 let llval = match self.fn_abi.ret.mode {
265 PassMode::Ignore | PassMode::Indirect(..) => {
270 PassMode::Direct(_) | PassMode::Pair(..) => {
271 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
272 if let Ref(llval, _, align) = op.val {
273 bx.load(llval, align)
275 op.immediate_or_packed_pair(&mut bx)
279 PassMode::Cast(cast_ty) => {
280 let op = match self.locals[mir::RETURN_PLACE] {
281 LocalRef::Operand(Some(op)) => op,
282 LocalRef::Operand(None) => bug!("use of return before def"),
283 LocalRef::Place(cg_place) => OperandRef {
284 val: Ref(cg_place.llval, None, cg_place.align),
285 layout: cg_place.layout,
287 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
289 let llslot = match op.val {
290 Immediate(_) | Pair(..) => {
291 let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
292 op.val.store(&mut bx, scratch);
295 Ref(llval, _, align) => {
296 assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
300 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
301 bx.load(addr, self.fn_abi.ret.layout.align.abi)
307 fn codegen_drop_terminator(
309 helper: TerminatorCodegenHelper<'tcx>,
311 location: mir::Place<'tcx>,
312 target: mir::BasicBlock,
313 unwind: Option<mir::BasicBlock>,
315 let ty = location.ty(self.mir, bx.tcx()).ty;
316 let ty = self.monomorphize(&ty);
317 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
319 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
320 // we don't actually need to drop anything.
321 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
322 helper.funclet_br(self, &mut bx, target);
326 let place = self.codegen_place(&mut bx, location.as_ref());
328 let mut args = if let Some(llextra) = place.llextra {
329 args2 = [place.llval, llextra];
332 args1 = [place.llval];
335 let (drop_fn, fn_abi) = match ty.kind() {
336 // FIXME(eddyb) perhaps move some of this logic into
337 // `Instance::resolve_drop_in_place`?
339 let virtual_drop = Instance {
340 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
341 substs: drop_fn.substs,
343 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
344 let vtable = args[1];
346 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
348 _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
350 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
357 Some((ReturnDest::Nothing, target)),
362 fn codegen_assert_terminator(
364 helper: TerminatorCodegenHelper<'tcx>,
366 terminator: &mir::Terminator<'tcx>,
367 cond: &mir::Operand<'tcx>,
369 msg: &mir::AssertMessage<'tcx>,
370 target: mir::BasicBlock,
371 cleanup: Option<mir::BasicBlock>,
373 let span = terminator.source_info.span;
374 let cond = self.codegen_operand(&mut bx, cond).immediate();
375 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
377 // This case can currently arise only from functions marked
378 // with #[rustc_inherit_overflow_checks] and inlined from
379 // another crate (mostly core::num generic/#[inline] fns),
380 // while the current crate doesn't use overflow checks.
381 // NOTE: Unlike binops, negation doesn't have its own
382 // checked operation, just a comparison with the minimum
383 // value, so we have to check for the assert message.
384 if !bx.check_overflow() {
385 if let AssertKind::OverflowNeg(_) = *msg {
386 const_cond = Some(expected);
390 // Don't codegen the panic block if success if known.
391 if const_cond == Some(expected) {
392 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
393 helper.funclet_br(self, &mut bx, target);
397 // Pass the condition through llvm.expect for branch hinting.
398 let cond = bx.expect(cond, expected);
400 // Create the failure block and the conditional branch to it.
401 let lltarget = helper.llblock(self, target);
402 let panic_block = self.new_block("panic");
403 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
405 bx.cond_br(cond, lltarget, panic_block.llbb());
407 bx.cond_br(cond, panic_block.llbb(), lltarget);
410 // After this point, bx is the block for the call to panic.
412 self.set_debug_loc(&mut bx, terminator.source_info);
414 // Get the location information.
415 let location = self.get_caller_location(&mut bx, span).immediate();
417 // Put together the arguments to the panic entry point.
418 let (lang_item, args) = match msg {
419 AssertKind::BoundsCheck { ref len, ref index } => {
420 let len = self.codegen_operand(&mut bx, len).immediate();
421 let index = self.codegen_operand(&mut bx, index).immediate();
422 // It's `fn panic_bounds_check(index: usize, len: usize)`,
423 // and `#[track_caller]` adds an implicit third argument.
424 (LangItem::PanicBoundsCheck, vec![index, len, location])
427 let msg_str = Symbol::intern(msg.description());
428 let msg = bx.const_str(msg_str);
429 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
430 // as two arguments, and `#[track_caller]` adds an implicit third argument.
431 (LangItem::Panic, vec![msg.0, msg.1, location])
435 // Obtain the panic entry point.
436 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
437 let instance = ty::Instance::mono(bx.tcx(), def_id);
438 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
439 let llfn = bx.get_fn_addr(instance);
441 // Codegen the actual panic invoke/call.
442 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
445 /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
446 fn codegen_panic_intrinsic(
448 helper: &TerminatorCodegenHelper<'tcx>,
450 intrinsic: Option<Symbol>,
451 instance: Option<Instance<'tcx>>,
453 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
454 cleanup: Option<mir::BasicBlock>,
456 // Emit a panic or a no-op for `assert_*` intrinsics.
457 // These are intrinsics that compile to panics so that we can get a message
458 // which mentions the offending type, even from a const context.
459 #[derive(Debug, PartialEq)]
460 enum AssertIntrinsic {
465 let panic_intrinsic = intrinsic.and_then(|i| match i {
466 sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
467 sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
468 sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
471 if let Some(intrinsic) = panic_intrinsic {
472 use AssertIntrinsic::*;
473 let ty = instance.unwrap().substs.type_at(0);
474 let layout = bx.layout_of(ty);
475 let do_panic = match intrinsic {
476 Inhabited => layout.abi.is_uninhabited(),
477 // We unwrap as the error type is `!`.
478 ZeroValid => !layout.might_permit_raw_init(bx, /*zero:*/ true).unwrap(),
479 // We unwrap as the error type is `!`.
480 UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false).unwrap(),
483 let msg_str = with_no_trimmed_paths(|| {
484 if layout.abi.is_uninhabited() {
485 // Use this error even for the other intrinsics as it is more precise.
486 format!("attempted to instantiate uninhabited type `{}`", ty)
487 } else if intrinsic == ZeroValid {
488 format!("attempted to zero-initialize type `{}`, which is invalid", ty)
490 format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
493 let msg = bx.const_str(Symbol::intern(&msg_str));
494 let location = self.get_caller_location(bx, span).immediate();
496 // Obtain the panic entry point.
497 // FIXME: dedup this with `codegen_assert_terminator` above.
498 let def_id = common::langcall(bx.tcx(), Some(span), "", LangItem::Panic);
499 let instance = ty::Instance::mono(bx.tcx(), def_id);
500 let fn_abi = FnAbi::of_instance(bx, instance, &[]);
501 let llfn = bx.get_fn_addr(instance);
503 if let Some((_, target)) = destination.as_ref() {
504 helper.maybe_sideeffect(self.mir, bx, &[*target]);
506 // Codegen the actual panic invoke/call.
512 &[msg.0, msg.1, location],
513 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
518 let target = destination.as_ref().unwrap().1;
519 helper.maybe_sideeffect(self.mir, bx, &[target]);
520 helper.funclet_br(self, bx, target)
528 fn codegen_call_terminator(
530 helper: TerminatorCodegenHelper<'tcx>,
532 terminator: &mir::Terminator<'tcx>,
533 func: &mir::Operand<'tcx>,
534 args: &Vec<mir::Operand<'tcx>>,
535 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
536 cleanup: Option<mir::BasicBlock>,
539 let span = terminator.source_info.span;
540 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
541 let callee = self.codegen_operand(&mut bx, func);
543 let (instance, mut llfn) = match *callee.layout.ty.kind() {
544 ty::FnDef(def_id, substs) => (
546 ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
549 .polymorphize(bx.tcx()),
553 ty::FnPtr(_) => (None, Some(callee.immediate())),
554 _ => bug!("{} is not callable", callee.layout.ty),
556 let def = instance.map(|i| i.def);
558 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
559 // Empty drop glue; a no-op.
560 let &(_, target) = destination.as_ref().unwrap();
561 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
562 helper.funclet_br(self, &mut bx, target);
566 // FIXME(eddyb) avoid computing this if possible, when `instance` is
567 // available - right now `sig` is only needed for getting the `abi`
568 // and figuring out how many extra args were passed to a C-variadic `fn`.
569 let sig = callee.layout.ty.fn_sig(bx.tcx());
572 // Handle intrinsics old codegen wants Expr's for, ourselves.
573 let intrinsic = match def {
574 Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
578 let extra_args = &args[sig.inputs().skip_binder().len()..];
579 let extra_args = extra_args
582 let op_ty = op_arg.ty(self.mir, bx.tcx());
583 self.monomorphize(&op_ty)
585 .collect::<Vec<_>>();
587 let fn_abi = match instance {
588 Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
589 None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
592 if intrinsic == Some(sym::transmute) {
593 if let Some(destination_ref) = destination.as_ref() {
594 let &(dest, target) = destination_ref;
595 self.codegen_transmute(&mut bx, &args[0], dest);
596 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
597 helper.funclet_br(self, &mut bx, target);
599 // If we are trying to transmute to an uninhabited type,
600 // it is likely there is no allotted destination. In fact,
601 // transmuting to an uninhabited type is UB, which means
602 // we can do what we like. Here, we declare that transmuting
603 // into an uninhabited type is impossible, so anything following
604 // it must be unreachable.
605 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
611 if self.codegen_panic_intrinsic(
623 // The arguments we'll be passing. Plus one to account for outptr, if used.
624 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
625 let mut llargs = Vec::with_capacity(arg_count);
627 // Prepare the return value destination
628 let ret_dest = if let Some((dest, _)) = *destination {
629 let is_intrinsic = intrinsic.is_some();
630 self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
635 if intrinsic == Some(sym::caller_location) {
636 if let Some((_, target)) = destination.as_ref() {
637 let location = self.get_caller_location(&mut bx, fn_span);
639 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
640 location.val.store(&mut bx, tmp);
642 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
644 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
645 helper.funclet_br(self, &mut bx, *target);
650 if intrinsic.is_some() && intrinsic != Some(sym::drop_in_place) {
651 let intrinsic = intrinsic.unwrap();
652 let dest = match ret_dest {
653 _ if fn_abi.ret.is_indirect() => llargs[0],
654 ReturnDest::Nothing => {
655 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
657 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
658 ReturnDest::DirectOperand(_) => {
659 bug!("Cannot use direct operand with an intrinsic call")
663 let args: Vec<_> = args
667 // The indices passed to simd_shuffle* in the
668 // third argument must be constant. This is
669 // checked by const-qualification, which also
670 // promotes any complex rvalues to constants.
671 if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
672 if let mir::Operand::Constant(constant) = arg {
673 let c = self.eval_mir_constant(constant);
674 let (llval, ty) = self.simd_shuffle_indices(
680 return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) };
682 span_bug!(span, "shuffle indices must be constant");
686 self.codegen_operand(&mut bx, arg)
690 Self::codegen_intrinsic_call(
692 *instance.as_ref().unwrap(),
696 terminator.source_info.span,
699 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
700 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
703 if let Some((_, target)) = *destination {
704 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
705 helper.funclet_br(self, &mut bx, target);
713 // Split the rust-call tupled arguments off.
714 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
715 let (tup, args) = args.split_last().unwrap();
721 'make_args: for (i, arg) in first_args.iter().enumerate() {
722 let mut op = self.codegen_operand(&mut bx, arg);
724 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
725 if let Pair(..) = op.val {
726 // In the case of Rc<Self>, we need to explicitly pass a
727 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
728 // that is understood elsewhere in the compiler as a method on
730 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
731 // we get a value of a built-in pointer type
732 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
733 && !op.layout.ty.is_region_ptr()
735 for i in 0..op.layout.fields.count() {
736 let field = op.extract_field(&mut bx, i);
737 if !field.layout.is_zst() {
738 // we found the one non-zero-sized field that is allowed
739 // now find *its* non-zero-sized field, or stop if it's a
742 continue 'descend_newtypes;
746 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
749 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
750 // data pointer and vtable. Look up the method in the vtable, and pass
751 // the data pointer as the first argument
753 Pair(data_ptr, meta) => {
755 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
757 llargs.push(data_ptr);
760 other => bug!("expected a Pair, got {:?}", other),
762 } else if let Ref(data_ptr, Some(meta), _) = op.val {
763 // by-value dynamic dispatch
764 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
765 llargs.push(data_ptr);
768 span_bug!(span, "can't codegen a virtual call on {:?}", op);
772 // The callee needs to own the argument memory if we pass it
773 // by-ref, so make a local copy of non-immediate constants.
774 match (arg, op.val) {
775 (&mir::Operand::Copy(_), Ref(_, None, _))
776 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
777 let tmp = PlaceRef::alloca(&mut bx, op.layout);
778 op.val.store(&mut bx, tmp);
779 op.val = Ref(tmp.llval, None, tmp.align);
784 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
786 if let Some(tup) = untuple {
787 self.codegen_arguments_untupled(
791 &fn_abi.args[first_args.len()..],
796 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
801 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
803 let location = self.get_caller_location(&mut bx, fn_span);
805 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
806 terminator, location, fn_span
809 let last_arg = fn_abi.args.last().unwrap();
810 self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
813 let fn_ptr = match (llfn, instance) {
814 (Some(llfn), _) => llfn,
815 (None, Some(instance)) => bx.get_fn_addr(instance),
816 _ => span_bug!(span, "no llfn for call"),
819 if let Some((_, target)) = destination.as_ref() {
820 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
828 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
833 fn codegen_asm_terminator(
835 helper: TerminatorCodegenHelper<'tcx>,
837 terminator: &mir::Terminator<'tcx>,
838 template: &[ast::InlineAsmTemplatePiece],
839 operands: &[mir::InlineAsmOperand<'tcx>],
840 options: ast::InlineAsmOptions,
842 destination: Option<mir::BasicBlock>,
844 let span = terminator.source_info.span;
846 let operands: Vec<_> = operands
848 .map(|op| match *op {
849 mir::InlineAsmOperand::In { reg, ref value } => {
850 let value = self.codegen_operand(&mut bx, value);
851 InlineAsmOperandRef::In { reg, value }
853 mir::InlineAsmOperand::Out { reg, late, ref place } => {
854 let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
855 InlineAsmOperandRef::Out { reg, late, place }
857 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
858 let in_value = self.codegen_operand(&mut bx, in_value);
860 out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
861 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
863 mir::InlineAsmOperand::Const { ref value } => {
864 if let mir::Operand::Constant(constant) = value {
865 let const_value = self
866 .eval_mir_constant(constant)
867 .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
868 let ty = constant.literal.ty;
869 let size = bx.layout_of(ty).size;
870 let scalar = match const_value {
871 ConstValue::Scalar(s) => s,
874 "expected Scalar for promoted asm const, but got {:#?}",
878 let value = scalar.assert_bits(size);
879 let string = match ty.kind() {
880 ty::Uint(_) => value.to_string(),
882 match int_ty.normalize(bx.tcx().sess.target.ptr_width) {
883 ast::IntTy::I8 => (value as i8).to_string(),
884 ast::IntTy::I16 => (value as i16).to_string(),
885 ast::IntTy::I32 => (value as i32).to_string(),
886 ast::IntTy::I64 => (value as i64).to_string(),
887 ast::IntTy::I128 => (value as i128).to_string(),
888 ast::IntTy::Isize => unreachable!(),
891 ty::Float(ast::FloatTy::F32) => {
892 f32::from_bits(value as u32).to_string()
894 ty::Float(ast::FloatTy::F64) => {
895 f64::from_bits(value as u64).to_string()
897 _ => span_bug!(span, "asm const has bad type {}", ty),
899 InlineAsmOperandRef::Const { string }
901 span_bug!(span, "asm const is not a constant");
904 mir::InlineAsmOperand::SymFn { ref value } => {
905 let literal = self.monomorphize(&value.literal);
906 if let ty::FnDef(def_id, substs) = *literal.ty.kind() {
907 let instance = ty::Instance::resolve_for_fn_ptr(
909 ty::ParamEnv::reveal_all(),
914 InlineAsmOperandRef::SymFn { instance }
916 span_bug!(span, "invalid type for asm sym (fn)");
919 mir::InlineAsmOperand::SymStatic { def_id } => {
920 InlineAsmOperandRef::SymStatic { def_id }
925 bx.codegen_inline_asm(template, &operands, options, line_spans);
927 if let Some(target) = destination {
928 helper.funclet_br(self, &mut bx, target);
935 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
936 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
937 let mut bx = self.build_block(bb);
941 debug!("codegen_block({:?}={:?})", bb, data);
943 for statement in &data.statements {
944 bx = self.codegen_statement(bx, statement);
947 self.codegen_terminator(bx, bb, data.terminator());
950 fn codegen_terminator(
954 terminator: &'tcx mir::Terminator<'tcx>,
956 debug!("codegen_terminator: {:?}", terminator);
958 // Create the cleanup bundle, if needed.
959 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
960 let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
962 self.set_debug_loc(&mut bx, terminator.source_info);
963 match terminator.kind {
964 mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
966 mir::TerminatorKind::Abort => {
968 // `abort` does not terminate the block, so we still need to generate
969 // an `unreachable` terminator after it.
973 mir::TerminatorKind::Goto { target } => {
974 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
975 helper.funclet_br(self, &mut bx, target);
978 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
979 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, values, targets);
982 mir::TerminatorKind::Return => {
983 self.codegen_return_terminator(bx);
986 mir::TerminatorKind::Unreachable => {
990 mir::TerminatorKind::Drop { place, target, unwind } => {
991 self.codegen_drop_terminator(helper, bx, place, target, unwind);
994 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
995 self.codegen_assert_terminator(
996 helper, bx, terminator, cond, expected, msg, target, cleanup,
1000 mir::TerminatorKind::DropAndReplace { .. } => {
1001 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1004 mir::TerminatorKind::Call {
1012 self.codegen_call_terminator(
1023 mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1024 bug!("generator ops in codegen")
1026 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1027 bug!("borrowck false edges in codegen")
1030 mir::TerminatorKind::InlineAsm {
1037 self.codegen_asm_terminator(
1051 fn codegen_argument(
1054 op: OperandRef<'tcx, Bx::Value>,
1055 llargs: &mut Vec<Bx::Value>,
1056 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1058 // Fill padding with undef value, where applicable.
1059 if let Some(ty) = arg.pad {
1060 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
1063 if arg.is_ignore() {
1067 if let PassMode::Pair(..) = arg.mode {
1074 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1076 } else if arg.is_unsized_indirect() {
1078 Ref(a, Some(b), _) => {
1083 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1087 // Force by-ref if we have to load through a cast pointer.
1088 let (mut llval, align, by_ref) = match op.val {
1089 Immediate(_) | Pair(..) => match arg.mode {
1090 PassMode::Indirect(..) | PassMode::Cast(_) => {
1091 let scratch = PlaceRef::alloca(bx, arg.layout);
1092 op.val.store(bx, scratch);
1093 (scratch.llval, scratch.align, true)
1095 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1097 Ref(llval, _, align) => {
1098 if arg.is_indirect() && align < arg.layout.align.abi {
1099 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1100 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1101 // have scary latent bugs around.
1103 let scratch = PlaceRef::alloca(bx, arg.layout);
1113 (scratch.llval, scratch.align, true)
1115 (llval, align, true)
1120 if by_ref && !arg.is_indirect() {
1121 // Have to load the argument, maybe while casting it.
1122 if let PassMode::Cast(ty) = arg.mode {
1123 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
1124 llval = bx.load(addr, align.min(arg.layout.align.abi));
1126 // We can't use `PlaceRef::load` here because the argument
1127 // may have a type we don't treat as immediate, but the ABI
1128 // used for this call is passing it by-value. In that case,
1129 // the load would just produce `OperandValue::Ref` instead
1130 // of the `OperandValue::Immediate` we need for the call.
1131 llval = bx.load(llval, align);
1132 if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
1133 if scalar.is_bool() {
1134 bx.range_metadata(llval, 0..2);
1137 // We store bools as `i8` so we need to truncate to `i1`.
1138 llval = bx.to_immediate(llval, arg.layout);
1145 fn codegen_arguments_untupled(
1148 operand: &mir::Operand<'tcx>,
1149 llargs: &mut Vec<Bx::Value>,
1150 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1152 let tuple = self.codegen_operand(bx, operand);
1154 // Handle both by-ref and immediate tuples.
1155 if let Ref(llval, None, align) = tuple.val {
1156 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1157 for i in 0..tuple.layout.fields.count() {
1158 let field_ptr = tuple_ptr.project_field(bx, i);
1159 let field = bx.load_operand(field_ptr);
1160 self.codegen_argument(bx, field, llargs, &args[i]);
1162 } else if let Ref(_, Some(_), _) = tuple.val {
1163 bug!("closure arguments must be sized")
1165 // If the tuple is immediate, the elements are as well.
1166 for i in 0..tuple.layout.fields.count() {
1167 let op = tuple.extract_field(bx, i);
1168 self.codegen_argument(bx, op, llargs, &args[i]);
1173 fn get_caller_location(&mut self, bx: &mut Bx, span: Span) -> OperandRef<'tcx, Bx::Value> {
1174 self.caller_location.unwrap_or_else(|| {
1175 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1176 let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1177 let const_loc = bx.tcx().const_caller_location((
1178 Symbol::intern(&caller.file.name.to_string()),
1180 caller.col_display as u32 + 1,
1182 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1186 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1188 if let Some(slot) = self.personality_slot {
1191 let layout = cx.layout_of(
1192 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1194 let slot = PlaceRef::alloca(bx, layout);
1195 self.personality_slot = Some(slot);
1200 /// Returns the landing-pad wrapper around the given basic block.
1202 /// No-op in MSVC SEH scheme.
1203 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1204 if let Some(block) = self.landing_pads[target_bb] {
1208 let block = self.blocks[target_bb];
1209 let landing_pad = self.landing_pad_uncached(block);
1210 self.landing_pads[target_bb] = Some(landing_pad);
1214 fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1215 if base::wants_msvc_seh(self.cx.sess()) {
1216 span_bug!(self.mir.span, "landing pad was not inserted?")
1219 let mut bx = self.new_block("cleanup");
1221 let llpersonality = self.cx.eh_personality();
1222 let llretty = self.landing_pad_type();
1223 let lp = bx.landing_pad(llretty, llpersonality, 1);
1226 let slot = self.get_personality_slot(&mut bx);
1227 slot.storage_live(&mut bx);
1228 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1234 fn landing_pad_type(&self) -> Bx::Type {
1236 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1239 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1240 self.unreachable_block.unwrap_or_else(|| {
1241 let mut bx = self.new_block("unreachable");
1243 self.unreachable_block = Some(bx.llbb());
1248 pub fn new_block(&self, name: &str) -> Bx {
1249 Bx::new_block(self.cx, self.llfn, name)
1252 pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1253 let mut bx = Bx::with_cx(self.cx);
1254 bx.position_at_end(self.blocks[bb]);
1258 fn make_return_dest(
1261 dest: mir::Place<'tcx>,
1262 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1263 llargs: &mut Vec<Bx::Value>,
1265 ) -> ReturnDest<'tcx, Bx::Value> {
1266 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1267 if fn_ret.is_ignore() {
1268 return ReturnDest::Nothing;
1270 let dest = if let Some(index) = dest.as_local() {
1271 match self.locals[index] {
1272 LocalRef::Place(dest) => dest,
1273 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1274 LocalRef::Operand(None) => {
1275 // Handle temporary places, specifically `Operand` ones, as
1276 // they don't have `alloca`s.
1277 return if fn_ret.is_indirect() {
1278 // Odd, but possible, case, we have an operand temporary,
1279 // but the calling convention has an indirect return.
1280 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1281 tmp.storage_live(bx);
1282 llargs.push(tmp.llval);
1283 ReturnDest::IndirectOperand(tmp, index)
1284 } else if is_intrinsic {
1285 // Currently, intrinsics always need a location to store
1286 // the result, so we create a temporary `alloca` for the
1288 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1289 tmp.storage_live(bx);
1290 ReturnDest::IndirectOperand(tmp, index)
1292 ReturnDest::DirectOperand(index)
1295 LocalRef::Operand(Some(_)) => {
1296 bug!("place local already assigned to");
1302 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1305 if fn_ret.is_indirect() {
1306 if dest.align < dest.layout.align.abi {
1307 // Currently, MIR code generation does not create calls
1308 // that store directly to fields of packed structs (in
1309 // fact, the calls it creates write only to temps).
1311 // If someone changes that, please update this code path
1312 // to create a temporary.
1313 span_bug!(self.mir.span, "can't directly store to unaligned value");
1315 llargs.push(dest.llval);
1318 ReturnDest::Store(dest)
1322 fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1323 if let Some(index) = dst.as_local() {
1324 match self.locals[index] {
1325 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1326 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1327 LocalRef::Operand(None) => {
1328 let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1329 assert!(!dst_layout.ty.has_erasable_regions());
1330 let place = PlaceRef::alloca(bx, dst_layout);
1331 place.storage_live(bx);
1332 self.codegen_transmute_into(bx, src, place);
1333 let op = bx.load_operand(place);
1334 place.storage_dead(bx);
1335 self.locals[index] = LocalRef::Operand(Some(op));
1336 self.debug_introduce_local(bx, index);
1338 LocalRef::Operand(Some(op)) => {
1339 assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1343 let dst = self.codegen_place(bx, dst.as_ref());
1344 self.codegen_transmute_into(bx, src, dst);
1348 fn codegen_transmute_into(
1351 src: &mir::Operand<'tcx>,
1352 dst: PlaceRef<'tcx, Bx::Value>,
1354 let src = self.codegen_operand(bx, src);
1355 let llty = bx.backend_type(src.layout);
1356 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1357 let align = src.layout.align.abi.min(dst.align);
1358 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1361 // Stores the return value of a function call into it's final location.
1365 dest: ReturnDest<'tcx, Bx::Value>,
1366 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1369 use self::ReturnDest::*;
1373 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1374 IndirectOperand(tmp, index) => {
1375 let op = bx.load_operand(tmp);
1376 tmp.storage_dead(bx);
1377 self.locals[index] = LocalRef::Operand(Some(op));
1378 self.debug_introduce_local(bx, index);
1380 DirectOperand(index) => {
1381 // If there is a cast, we have to store and reload.
1382 let op = if let PassMode::Cast(_) = ret_abi.mode {
1383 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1384 tmp.storage_live(bx);
1385 bx.store_arg(&ret_abi, llval, tmp);
1386 let op = bx.load_operand(tmp);
1387 tmp.storage_dead(bx);
1390 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1392 self.locals[index] = LocalRef::Operand(Some(op));
1393 self.debug_introduce_local(bx, index);
1399 enum ReturnDest<'tcx, V> {
1400 // Do nothing; the return value is indirect or ignored.
1402 // Store the return value to the pointer.
1403 Store(PlaceRef<'tcx, V>),
1404 // Store an indirect return value to an operand local place.
1405 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1406 // Store a direct return value to an operand local place.
1407 DirectOperand(mir::Local),