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, FnTypeExt};
5 use rustc::mir::{self, PlaceBase, Static, StaticKind};
6 use rustc::mir::interpret::PanicInfo;
7 use rustc_target::abi::call::{ArgType, FnType, 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_ty` 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_ty: FnType<'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_ty, 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_ty.ret, invokeret);
133 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
134 bx.apply_attrs_callsite(&fn_ty, 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_ty.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_ty.c_variadic {
252 // The `VaList` "spoofed" argument is just after all the real arguments.
253 let va_list_arg_idx = self.fn_ty.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_ty.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_ty.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_ty.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_ty.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_ty) = 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_ty = FnType::new_vtable(&bx, sig, &[]);
355 let vtable = args[1];
357 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_ty), fn_ty)
360 (bx.get_fn_addr(drop_fn),
361 FnType::of_instance(&bx, drop_fn))
364 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
365 helper.do_call(self, &mut bx, fn_ty, 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_ty = FnType::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_ty, 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_ty = match def {
518 Some(ty::InstanceDef::Virtual(..)) => {
519 FnType::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 _ => FnType::new(&bx, sig, &extra_args)
531 // Emit a panic or a no-op for `panic_if_uninhabited`.
532 if intrinsic == Some("panic_if_uninhabited") {
533 let ty = instance.unwrap().substs.type_at(0);
534 let layout = bx.layout_of(ty);
535 if layout.abi.is_uninhabited() {
536 let msg_str = format!("Attempted to instantiate uninhabited type {}", ty);
537 let msg = bx.const_str(Symbol::intern(&msg_str));
538 let location = self.get_caller_location(&mut bx, span).immediate();
540 // Obtain the panic entry point.
542 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
543 let instance = ty::Instance::mono(bx.tcx(), def_id);
544 let fn_ty = FnType::of_instance(&bx, instance);
545 let llfn = bx.get_fn_addr(instance);
547 if let Some((_, target)) = destination.as_ref() {
548 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
550 // Codegen the actual panic invoke/call.
556 &[msg.0, msg.1, location],
557 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
562 let target = destination.as_ref().unwrap().1;
563 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
564 helper.funclet_br(self, &mut bx, target);
569 // The arguments we'll be passing. Plus one to account for outptr, if used.
570 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
571 let mut llargs = Vec::with_capacity(arg_count);
573 // Prepare the return value destination
574 let ret_dest = if let Some((ref dest, _)) = *destination {
575 let is_intrinsic = intrinsic.is_some();
576 self.make_return_dest(&mut bx, dest, &fn_ty.ret, &mut llargs,
582 if intrinsic == Some("caller_location") {
583 if let Some((_, target)) = destination.as_ref() {
584 let location = self.get_caller_location(&mut bx, span);
586 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
587 location.val.store(&mut bx, tmp);
589 self.store_return(&mut bx, ret_dest, &fn_ty.ret, location.immediate());
591 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
592 helper.funclet_br(self, &mut bx, *target);
597 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
598 let dest = match ret_dest {
599 _ if fn_ty.ret.is_indirect() => llargs[0],
600 ReturnDest::Nothing =>
601 bx.const_undef(bx.type_ptr_to(bx.memory_ty(&fn_ty.ret))),
602 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) =>
604 ReturnDest::DirectOperand(_) =>
605 bug!("Cannot use direct operand with an intrinsic call"),
608 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
609 // The indices passed to simd_shuffle* in the
610 // third argument must be constant. This is
611 // checked by const-qualification, which also
612 // promotes any complex rvalues to constants.
613 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
615 // The shuffle array argument is usually not an explicit constant,
616 // but specified directly in the code. This means it gets promoted
617 // and we can then extract the value by evaluating the promoted.
618 mir::Operand::Copy(place) | mir::Operand::Move(place) => {
619 if let mir::PlaceRef {
621 &PlaceBase::Static(box Static {
622 kind: StaticKind::Promoted(promoted, _),
629 let param_env = ty::ParamEnv::reveal_all();
630 let cid = mir::interpret::GlobalId {
631 instance: self.instance,
632 promoted: Some(promoted),
634 let c = bx.tcx().const_eval(param_env.and(cid));
635 let (llval, ty) = self.simd_shuffle_indices(
637 terminator.source_info.span,
642 val: Immediate(llval),
643 layout: bx.layout_of(ty),
646 span_bug!(span, "shuffle indices must be constant");
650 mir::Operand::Constant(constant) => {
651 let c = self.eval_mir_constant(constant);
652 let (llval, ty) = self.simd_shuffle_indices(
659 val: Immediate(llval),
660 layout: bx.layout_of(ty)
666 self.codegen_operand(&mut bx, arg)
670 bx.codegen_intrinsic_call(*instance.as_ref().unwrap(), &fn_ty, &args, dest,
671 terminator.source_info.span);
673 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
674 self.store_return(&mut bx, ret_dest, &fn_ty.ret, dst.llval);
677 if let Some((_, target)) = *destination {
678 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
679 helper.funclet_br(self, &mut bx, target);
687 // Split the rust-call tupled arguments off.
688 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
689 let (tup, args) = args.split_last().unwrap();
695 'make_args: for (i, arg) in first_args.iter().enumerate() {
696 let mut op = self.codegen_operand(&mut bx, arg);
698 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
699 if let Pair(..) = op.val {
700 // In the case of Rc<Self>, we need to explicitly pass a
701 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
702 // that is understood elsewhere in the compiler as a method on
704 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
705 // we get a value of a built-in pointer type
706 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
707 && !op.layout.ty.is_region_ptr()
709 'iter_fields: for i in 0..op.layout.fields.count() {
710 let field = op.extract_field(&mut bx, i);
711 if !field.layout.is_zst() {
712 // we found the one non-zero-sized field that is allowed
713 // now find *its* non-zero-sized field, or stop if it's a
716 continue 'descend_newtypes
720 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
723 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
724 // data pointer and vtable. Look up the method in the vtable, and pass
725 // the data pointer as the first argument
727 Pair(data_ptr, meta) => {
728 llfn = Some(meth::VirtualIndex::from_index(idx)
729 .get_fn(&mut bx, meta, &fn_ty));
730 llargs.push(data_ptr);
733 other => bug!("expected a Pair, got {:?}", other),
735 } else if let Ref(data_ptr, Some(meta), _) = op.val {
736 // by-value dynamic dispatch
737 llfn = Some(meth::VirtualIndex::from_index(idx)
738 .get_fn(&mut bx, meta, &fn_ty));
739 llargs.push(data_ptr);
742 span_bug!(span, "can't codegen a virtual call on {:?}", op);
746 // The callee needs to own the argument memory if we pass it
747 // by-ref, so make a local copy of non-immediate constants.
748 match (arg, op.val) {
749 (&mir::Operand::Copy(_), Ref(_, None, _)) |
750 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
751 let tmp = PlaceRef::alloca(&mut bx, op.layout);
752 op.val.store(&mut bx, tmp);
753 op.val = Ref(tmp.llval, None, tmp.align);
758 self.codegen_argument(&mut bx, op, &mut llargs, &fn_ty.args[i]);
760 if let Some(tup) = untuple {
761 self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
762 &fn_ty.args[first_args.len()..])
765 let fn_ptr = match (llfn, instance) {
766 (Some(llfn), _) => llfn,
767 (None, Some(instance)) => bx.get_fn_addr(instance),
768 _ => span_bug!(span, "no llfn for call"),
771 if let Some((_, target)) = destination.as_ref() {
772 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
774 helper.do_call(self, &mut bx, fn_ty, fn_ptr, &llargs,
775 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
780 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
781 pub fn codegen_block(
785 let mut bx = self.build_block(bb);
786 let data = &self.mir[bb];
788 debug!("codegen_block({:?}={:?})", bb, data);
790 for statement in &data.statements {
791 bx = self.codegen_statement(bx, statement);
794 self.codegen_terminator(bx, bb, data.terminator());
797 fn codegen_terminator(
801 terminator: &mir::Terminator<'tcx>
803 debug!("codegen_terminator: {:?}", terminator);
805 // Create the cleanup bundle, if needed.
806 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
807 let helper = TerminatorCodegenHelper {
808 bb: &bb, terminator, funclet_bb
811 self.set_debug_loc(&mut bx, terminator.source_info);
812 match terminator.kind {
813 mir::TerminatorKind::Resume => {
814 self.codegen_resume_terminator(helper, bx)
817 mir::TerminatorKind::Abort => {
822 mir::TerminatorKind::Goto { target } => {
823 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
824 helper.funclet_br(self, &mut bx, target);
827 mir::TerminatorKind::SwitchInt {
828 ref discr, switch_ty, ref values, ref targets
830 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
834 mir::TerminatorKind::Return => {
835 self.codegen_return_terminator(bx);
838 mir::TerminatorKind::Unreachable => {
842 mir::TerminatorKind::Drop { ref location, target, unwind } => {
843 self.codegen_drop_terminator(helper, bx, location, target, unwind);
846 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
847 self.codegen_assert_terminator(helper, bx, terminator, cond,
848 expected, msg, target, cleanup);
851 mir::TerminatorKind::DropAndReplace { .. } => {
852 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
855 mir::TerminatorKind::Call {
862 self.codegen_call_terminator(helper, bx, terminator, func,
863 args, destination, cleanup);
865 mir::TerminatorKind::GeneratorDrop |
866 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
867 mir::TerminatorKind::FalseEdges { .. } |
868 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
875 op: OperandRef<'tcx, Bx::Value>,
876 llargs: &mut Vec<Bx::Value>,
877 arg: &ArgType<'tcx, Ty<'tcx>>
879 // Fill padding with undef value, where applicable.
880 if let Some(ty) = arg.pad {
881 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
888 if let PassMode::Pair(..) = arg.mode {
895 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
897 } else if arg.is_unsized_indirect() {
899 Ref(a, Some(b), _) => {
904 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
908 // Force by-ref if we have to load through a cast pointer.
909 let (mut llval, align, by_ref) = match op.val {
910 Immediate(_) | Pair(..) => {
912 PassMode::Indirect(..) | PassMode::Cast(_) => {
913 let scratch = PlaceRef::alloca(bx, arg.layout);
914 op.val.store(bx, scratch);
915 (scratch.llval, scratch.align, true)
918 (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
922 Ref(llval, _, align) => {
923 if arg.is_indirect() && align < arg.layout.align.abi {
924 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
925 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
926 // have scary latent bugs around.
928 let scratch = PlaceRef::alloca(bx, arg.layout);
929 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
930 op.layout, MemFlags::empty());
931 (scratch.llval, scratch.align, true)
938 if by_ref && !arg.is_indirect() {
939 // Have to load the argument, maybe while casting it.
940 if let PassMode::Cast(ty) = arg.mode {
941 let addr = bx.pointercast(llval, bx.type_ptr_to(
942 bx.cast_backend_type(&ty))
944 llval = bx.load(addr, align.min(arg.layout.align.abi));
946 // We can't use `PlaceRef::load` here because the argument
947 // may have a type we don't treat as immediate, but the ABI
948 // used for this call is passing it by-value. In that case,
949 // the load would just produce `OperandValue::Ref` instead
950 // of the `OperandValue::Immediate` we need for the call.
951 llval = bx.load(llval, align);
952 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
953 if scalar.is_bool() {
954 bx.range_metadata(llval, 0..2);
957 // We store bools as `i8` so we need to truncate to `i1`.
958 llval = base::to_immediate(bx, llval, arg.layout);
965 fn codegen_arguments_untupled(
968 operand: &mir::Operand<'tcx>,
969 llargs: &mut Vec<Bx::Value>,
970 args: &[ArgType<'tcx, Ty<'tcx>>]
972 let tuple = self.codegen_operand(bx, operand);
974 // Handle both by-ref and immediate tuples.
975 if let Ref(llval, None, align) = tuple.val {
976 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
977 for i in 0..tuple.layout.fields.count() {
978 let field_ptr = tuple_ptr.project_field(bx, i);
979 let field = bx.load_operand(field_ptr);
980 self.codegen_argument(bx, field, llargs, &args[i]);
982 } else if let Ref(_, Some(_), _) = tuple.val {
983 bug!("closure arguments must be sized")
985 // If the tuple is immediate, the elements are as well.
986 for i in 0..tuple.layout.fields.count() {
987 let op = tuple.extract_field(bx, i);
988 self.codegen_argument(bx, op, llargs, &args[i]);
993 fn get_caller_location(
997 ) -> OperandRef<'tcx, Bx::Value> {
998 let caller = bx.tcx().sess.source_map().lookup_char_pos(span.lo());
999 let const_loc = bx.tcx().const_caller_location((
1000 Symbol::intern(&caller.file.name.to_string()),
1002 caller.col_display as u32 + 1,
1004 OperandRef::from_const(bx, const_loc)
1007 fn get_personality_slot(
1010 ) -> PlaceRef<'tcx, Bx::Value> {
1012 if let Some(slot) = self.personality_slot {
1015 let layout = cx.layout_of(cx.tcx().intern_tup(&[
1016 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
1019 let slot = PlaceRef::alloca(bx, layout);
1020 self.personality_slot = Some(slot);
1025 /// Returns the landing-pad wrapper around the given basic block.
1027 /// No-op in MSVC SEH scheme.
1030 target_bb: mir::BasicBlock
1031 ) -> Bx::BasicBlock {
1032 if let Some(block) = self.landing_pads[target_bb] {
1036 let block = self.blocks[target_bb];
1037 let landing_pad = self.landing_pad_uncached(block);
1038 self.landing_pads[target_bb] = Some(landing_pad);
1042 fn landing_pad_uncached(
1044 target_bb: Bx::BasicBlock
1045 ) -> Bx::BasicBlock {
1046 if base::wants_msvc_seh(self.cx.sess()) {
1047 span_bug!(self.mir.span, "landing pad was not inserted?")
1050 let mut bx = self.new_block("cleanup");
1052 let llpersonality = self.cx.eh_personality();
1053 let llretty = self.landing_pad_type();
1054 let lp = bx.landing_pad(llretty, llpersonality, 1);
1057 let slot = self.get_personality_slot(&mut bx);
1058 slot.storage_live(&mut bx);
1059 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1065 fn landing_pad_type(&self) -> Bx::Type {
1067 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1070 fn unreachable_block(
1072 ) -> Bx::BasicBlock {
1073 self.unreachable_block.unwrap_or_else(|| {
1074 let mut bx = self.new_block("unreachable");
1076 self.unreachable_block = Some(bx.llbb());
1081 pub fn new_block(&self, name: &str) -> Bx {
1082 Bx::new_block(self.cx, self.llfn, name)
1089 let mut bx = Bx::with_cx(self.cx);
1090 bx.position_at_end(self.blocks[bb]);
1094 fn make_return_dest(
1097 dest: &mir::Place<'tcx>,
1098 fn_ret: &ArgType<'tcx, Ty<'tcx>>,
1099 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1100 ) -> ReturnDest<'tcx, Bx::Value> {
1101 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1102 if fn_ret.is_ignore() {
1103 return ReturnDest::Nothing;
1105 let dest = if let Some(index) = dest.as_local() {
1106 match self.locals[index] {
1107 LocalRef::Place(dest) => dest,
1108 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1109 LocalRef::Operand(None) => {
1110 // Handle temporary places, specifically `Operand` ones, as
1111 // they don't have `alloca`s.
1112 return if fn_ret.is_indirect() {
1113 // Odd, but possible, case, we have an operand temporary,
1114 // but the calling convention has an indirect return.
1115 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1116 tmp.storage_live(bx);
1117 llargs.push(tmp.llval);
1118 ReturnDest::IndirectOperand(tmp, index)
1119 } else if is_intrinsic {
1120 // Currently, intrinsics always need a location to store
1121 // the result, so we create a temporary `alloca` for the
1123 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1124 tmp.storage_live(bx);
1125 ReturnDest::IndirectOperand(tmp, index)
1127 ReturnDest::DirectOperand(index)
1130 LocalRef::Operand(Some(_)) => {
1131 bug!("place local already assigned to");
1135 self.codegen_place(bx, &mir::PlaceRef {
1137 projection: &dest.projection,
1140 if fn_ret.is_indirect() {
1141 if dest.align < dest.layout.align.abi {
1142 // Currently, MIR code generation does not create calls
1143 // that store directly to fields of packed structs (in
1144 // fact, the calls it creates write only to temps).
1146 // If someone changes that, please update this code path
1147 // to create a temporary.
1148 span_bug!(self.mir.span, "can't directly store to unaligned value");
1150 llargs.push(dest.llval);
1153 ReturnDest::Store(dest)
1157 fn codegen_transmute(
1160 src: &mir::Operand<'tcx>,
1161 dst: &mir::Place<'tcx>
1163 if let Some(index) = dst.as_local() {
1164 match self.locals[index] {
1165 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1166 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1167 LocalRef::Operand(None) => {
1168 let dst_layout = bx.layout_of(self.monomorphized_place_ty(&dst.as_ref()));
1169 assert!(!dst_layout.ty.has_erasable_regions());
1170 let place = PlaceRef::alloca(bx, dst_layout);
1171 place.storage_live(bx);
1172 self.codegen_transmute_into(bx, src, place);
1173 let op = bx.load_operand(place);
1174 place.storage_dead(bx);
1175 self.locals[index] = LocalRef::Operand(Some(op));
1177 LocalRef::Operand(Some(op)) => {
1178 assert!(op.layout.is_zst(),
1179 "assigning to initialized SSAtemp");
1183 let dst = self.codegen_place(bx, &dst.as_ref());
1184 self.codegen_transmute_into(bx, src, dst);
1188 fn codegen_transmute_into(
1191 src: &mir::Operand<'tcx>,
1192 dst: PlaceRef<'tcx, Bx::Value>
1194 let src = self.codegen_operand(bx, src);
1195 let llty = bx.backend_type(src.layout);
1196 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1197 let align = src.layout.align.abi.min(dst.align);
1198 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1202 // Stores the return value of a function call into it's final location.
1206 dest: ReturnDest<'tcx, Bx::Value>,
1207 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1210 use self::ReturnDest::*;
1214 Store(dst) => bx.store_arg_ty(&ret_ty, llval, dst),
1215 IndirectOperand(tmp, index) => {
1216 let op = bx.load_operand(tmp);
1217 tmp.storage_dead(bx);
1218 self.locals[index] = LocalRef::Operand(Some(op));
1220 DirectOperand(index) => {
1221 // If there is a cast, we have to store and reload.
1222 let op = if let PassMode::Cast(_) = ret_ty.mode {
1223 let tmp = PlaceRef::alloca(bx, ret_ty.layout);
1224 tmp.storage_live(bx);
1225 bx.store_arg_ty(&ret_ty, llval, tmp);
1226 let op = bx.load_operand(tmp);
1227 tmp.storage_dead(bx);
1230 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1232 self.locals[index] = LocalRef::Operand(Some(op));
1238 enum ReturnDest<'tcx, V> {
1239 // Do nothing; the return value is indirect or ignored.
1241 // Store the return value to the pointer.
1242 Store(PlaceRef<'tcx, V>),
1243 // Store an indirect return value to an operand local place.
1244 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1245 // Store a direct return value to an operand local place.
1246 DirectOperand(mir::Local)