1 use rustc::middle::lang_items;
2 use rustc::ty::{self, Ty, TypeFoldable};
3 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
5 use rustc::mir::interpret::EvalErrorKind;
6 use rustc_target::abi::call::{ArgType, FnType, PassMode, IgnoreMode};
7 use rustc_target::spec::abi::Abi;
8 use rustc_mir::monomorphize;
11 use crate::common::{self, IntPredicate};
18 use syntax::symbol::Symbol;
21 use super::{FunctionCx, LocalRef};
22 use super::place::PlaceRef;
23 use super::operand::{OperandValue, OperandRef};
24 use super::operand::OperandValue::{Pair, Ref, Immediate};
26 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
27 /// e.g., creating a basic block, calling a function, etc.
28 struct TerminatorCodegenHelper<'a, 'tcx> {
29 bb: &'a mir::BasicBlock,
30 terminator: &'a mir::Terminator<'tcx>,
31 funclet_bb: Option<mir::BasicBlock>,
34 impl<'a, 'tcx> TerminatorCodegenHelper<'a, 'tcx> {
35 /// Returns the associated funclet from `FunctionCx::funclets` for the
36 /// `funclet_bb` member if it is not `None`.
37 fn funclet<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
39 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
40 ) -> Option<&'c Bx::Funclet> {
41 match self.funclet_bb {
42 Some(funcl) => fx.funclets[funcl].as_ref(),
47 fn lltarget<'b, 'c, Bx: BuilderMethods<'b, 'tcx>>(
49 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
50 target: mir::BasicBlock,
51 ) -> (Bx::BasicBlock, bool) {
52 let span = self.terminator.source_info.span;
53 let lltarget = fx.blocks[target];
54 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
55 match (self.funclet_bb, target_funclet) {
56 (None, None) => (lltarget, false),
57 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) =>
59 // jump *into* cleanup - need a landing pad if GNU
60 (None, Some(_)) => (fx.landing_pad_to(target), false),
61 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
62 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
66 /// Create a basic block.
67 fn llblock<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
69 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
70 target: mir::BasicBlock,
72 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
74 // MSVC cross-funclet jump - need a trampoline
76 debug!("llblock: creating cleanup trampoline for {:?}", target);
77 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
78 let mut trampoline = fx.new_block(name);
79 trampoline.cleanup_ret(self.funclet(fx).unwrap(),
87 fn funclet_br<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
89 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
91 target: mir::BasicBlock,
93 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
95 // micro-optimization: generate a `ret` rather than a jump
97 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
103 /// Call `fn_ptr` of `fn_ty` with the arguments `llargs`, the optional
104 /// return destination `destination` and the cleanup function `cleanup`.
105 fn do_call<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
107 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
109 fn_ty: FnType<'tcx, Ty<'tcx>>,
111 llargs: &[Bx::Value],
112 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
113 cleanup: Option<mir::BasicBlock>,
115 if let Some(cleanup) = cleanup {
116 let ret_bx = if let Some((_, target)) = destination {
119 fx.unreachable_block()
121 let invokeret = bx.invoke(fn_ptr,
124 self.llblock(fx, cleanup),
126 bx.apply_attrs_callsite(&fn_ty, invokeret);
128 if let Some((ret_dest, target)) = destination {
129 let mut ret_bx = fx.build_block(target);
130 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
131 fx.store_return(&mut ret_bx, ret_dest, &fn_ty.ret, invokeret);
134 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
135 bx.apply_attrs_callsite(&fn_ty, llret);
136 if fx.mir[*self.bb].is_cleanup {
137 // Cleanup is always the cold path. Don't inline
138 // drop glue. Also, when there is a deeply-nested
139 // struct, there are "symmetry" issues that cause
140 // exponential inlining - see issue #41696.
141 bx.do_not_inline(llret);
144 if let Some((ret_dest, target)) = destination {
145 fx.store_return(bx, ret_dest, &fn_ty.ret, llret);
146 self.funclet_br(fx, bx, target);
154 /// Codegen implementations for some terminator variants.
155 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
156 /// Generates code for a `Resume` terminator.
157 fn codegen_resume_terminator<'b>(
159 helper: TerminatorCodegenHelper<'b, 'tcx>,
162 if let Some(funclet) = helper.funclet(self) {
163 bx.cleanup_ret(funclet, None);
165 let slot = self.get_personality_slot(&mut bx);
166 let lp0 = slot.project_field(&mut bx, 0);
167 let lp0 = bx.load_operand(lp0).immediate();
168 let lp1 = slot.project_field(&mut bx, 1);
169 let lp1 = bx.load_operand(lp1).immediate();
170 slot.storage_dead(&mut bx);
172 if !bx.sess().target.target.options.custom_unwind_resume {
173 let mut lp = bx.const_undef(self.landing_pad_type());
174 lp = bx.insert_value(lp, lp0, 0);
175 lp = bx.insert_value(lp, lp1, 1);
178 bx.call(bx.eh_unwind_resume(), &[lp0],
179 helper.funclet(self));
185 fn codegen_switchint_terminator<'b>(
187 helper: TerminatorCodegenHelper<'b, 'tcx>,
189 discr: &mir::Operand<'tcx>,
191 values: &Cow<'tcx, [u128]>,
192 targets: &Vec<mir::BasicBlock>,
194 let discr = self.codegen_operand(&mut bx, &discr);
195 if targets.len() == 2 {
196 // If there are two targets, emit br instead of switch
197 let lltrue = helper.llblock(self, targets[0]);
198 let llfalse = helper.llblock(self, targets[1]);
199 if switch_ty == bx.tcx().types.bool {
200 // Don't generate trivial icmps when switching on bool
201 if let [0] = values[..] {
202 bx.cond_br(discr.immediate(), llfalse, lltrue);
204 assert_eq!(&values[..], &[1]);
205 bx.cond_br(discr.immediate(), lltrue, llfalse);
208 let switch_llty = bx.immediate_backend_type(
209 bx.layout_of(switch_ty)
211 let llval = bx.const_uint_big(switch_llty, values[0]);
212 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
213 bx.cond_br(cmp, lltrue, llfalse);
216 let (otherwise, targets) = targets.split_last().unwrap();
217 let switch = bx.switch(discr.immediate(),
218 helper.llblock(self, *otherwise),
220 let switch_llty = bx.immediate_backend_type(
221 bx.layout_of(switch_ty)
223 for (&value, target) in values.iter().zip(targets) {
224 let llval = bx.const_uint_big(switch_llty, value);
225 let llbb = helper.llblock(self, *target);
226 bx.add_case(switch, llval, llbb)
231 fn codegen_return_terminator<'b>(
235 if self.fn_ty.variadic {
236 if let Some(va_list) = self.va_list_ref {
237 bx.va_end(va_list.llval);
240 let llval = match self.fn_ty.ret.mode {
241 PassMode::Ignore(IgnoreMode::Zst) | PassMode::Indirect(..) => {
246 PassMode::Ignore(IgnoreMode::CVarArgs) => {
247 bug!("C-variadic arguments should never be the return type");
250 PassMode::Direct(_) | PassMode::Pair(..) => {
252 self.codegen_consume(&mut bx, &mir::Place::Local(mir::RETURN_PLACE));
253 if let Ref(llval, _, align) = op.val {
254 bx.load(llval, align)
256 op.immediate_or_packed_pair(&mut bx)
260 PassMode::Cast(cast_ty) => {
261 let op = match self.locals[mir::RETURN_PLACE] {
262 LocalRef::Operand(Some(op)) => op,
263 LocalRef::Operand(None) => bug!("use of return before def"),
264 LocalRef::Place(cg_place) => {
266 val: Ref(cg_place.llval, None, cg_place.align),
267 layout: cg_place.layout
270 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
272 let llslot = match op.val {
273 Immediate(_) | Pair(..) => {
275 PlaceRef::alloca(&mut bx, self.fn_ty.ret.layout, "ret");
276 op.val.store(&mut bx, scratch);
279 Ref(llval, _, align) => {
280 assert_eq!(align, op.layout.align.abi,
281 "return place is unaligned!");
285 let addr = bx.pointercast(llslot, bx.type_ptr_to(
286 bx.cast_backend_type(&cast_ty)
288 bx.load(addr, self.fn_ty.ret.layout.align.abi)
295 fn codegen_drop_terminator<'b>(
297 helper: TerminatorCodegenHelper<'b, 'tcx>,
299 location: &mir::Place<'tcx>,
300 target: mir::BasicBlock,
301 unwind: Option<mir::BasicBlock>,
303 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
304 let ty = self.monomorphize(&ty);
305 let drop_fn = monomorphize::resolve_drop_in_place(bx.tcx(), ty);
307 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
308 // we don't actually need to drop anything.
309 helper.funclet_br(self, &mut bx, target);
313 let place = self.codegen_place(&mut bx, location);
315 let mut args = if let Some(llextra) = place.llextra {
316 args2 = [place.llval, llextra];
319 args1 = [place.llval];
322 let (drop_fn, fn_ty) = match ty.sty {
324 let sig = drop_fn.fn_sig(self.cx.tcx());
325 let sig = self.cx.tcx().normalize_erasing_late_bound_regions(
326 ty::ParamEnv::reveal_all(),
329 let fn_ty = bx.new_vtable(sig, &[]);
330 let vtable = args[1];
332 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_ty), fn_ty)
336 bx.fn_type_of_instance(&drop_fn))
339 helper.do_call(self, &mut bx, fn_ty, drop_fn, args,
340 Some((ReturnDest::Nothing, target)),
344 fn codegen_assert_terminator<'b>(
346 helper: TerminatorCodegenHelper<'b, 'tcx>,
348 terminator: &mir::Terminator<'tcx>,
349 cond: &mir::Operand<'tcx>,
351 msg: &mir::AssertMessage<'tcx>,
352 target: mir::BasicBlock,
353 cleanup: Option<mir::BasicBlock>,
355 let span = terminator.source_info.span;
356 let cond = self.codegen_operand(&mut bx, cond).immediate();
357 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
359 // This case can currently arise only from functions marked
360 // with #[rustc_inherit_overflow_checks] and inlined from
361 // another crate (mostly core::num generic/#[inline] fns),
362 // while the current crate doesn't use overflow checks.
363 // NOTE: Unlike binops, negation doesn't have its own
364 // checked operation, just a comparison with the minimum
365 // value, so we have to check for the assert message.
366 if !bx.check_overflow() {
367 if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
368 const_cond = Some(expected);
372 // Don't codegen the panic block if success if known.
373 if const_cond == Some(expected) {
374 helper.funclet_br(self, &mut bx, target);
378 // Pass the condition through llvm.expect for branch hinting.
379 let cond = bx.expect(cond, expected);
381 // Create the failure block and the conditional branch to it.
382 let lltarget = helper.llblock(self, target);
383 let panic_block = self.new_block("panic");
385 bx.cond_br(cond, lltarget, panic_block.llbb());
387 bx.cond_br(cond, panic_block.llbb(), lltarget);
390 // After this point, bx is the block for the call to panic.
392 self.set_debug_loc(&mut bx, terminator.source_info);
394 // Get the location information.
395 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
396 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
397 let filename = bx.const_str_slice(filename);
398 let line = bx.const_u32(loc.line as u32);
399 let col = bx.const_u32(loc.col.to_usize() as u32 + 1);
400 let align = self.cx.tcx().data_layout.aggregate_align.abi
401 .max(self.cx.tcx().data_layout.i32_align.abi)
402 .max(self.cx.tcx().data_layout.pointer_align.abi);
404 // Put together the arguments to the panic entry point.
405 let (lang_item, args) = match *msg {
406 EvalErrorKind::BoundsCheck { ref len, ref index } => {
407 let len = self.codegen_operand(&mut bx, len).immediate();
408 let index = self.codegen_operand(&mut bx, index).immediate();
410 let file_line_col = bx.const_struct(&[filename, line, col], false);
411 let file_line_col = bx.static_addr_of(
414 Some("panic_bounds_check_loc")
416 (lang_items::PanicBoundsCheckFnLangItem,
417 vec![file_line_col, index, len])
420 let str = msg.description();
421 let msg_str = Symbol::intern(str).as_str();
422 let msg_str = bx.const_str_slice(msg_str);
423 let msg_file_line_col = bx.const_struct(
424 &[msg_str, filename, line, col],
427 let msg_file_line_col = bx.static_addr_of(
432 (lang_items::PanicFnLangItem,
433 vec![msg_file_line_col])
437 // Obtain the panic entry point.
438 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
439 let instance = ty::Instance::mono(bx.tcx(), def_id);
440 let fn_ty = bx.fn_type_of_instance(&instance);
441 let llfn = bx.get_fn(instance);
443 // Codegen the actual panic invoke/call.
444 helper.do_call(self, &mut bx, fn_ty, llfn, &args, None, cleanup);
447 fn codegen_call_terminator<'b>(
449 helper: TerminatorCodegenHelper<'b, 'tcx>,
451 terminator: &mir::Terminator<'tcx>,
452 func: &mir::Operand<'tcx>,
453 args: &Vec<mir::Operand<'tcx>>,
454 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
455 cleanup: Option<mir::BasicBlock>,
457 let span = terminator.source_info.span;
458 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
459 let callee = self.codegen_operand(&mut bx, func);
461 let (instance, mut llfn) = match callee.layout.ty.sty {
462 ty::FnDef(def_id, substs) => {
463 (Some(ty::Instance::resolve(bx.tcx(),
464 ty::ParamEnv::reveal_all(),
470 (None, Some(callee.immediate()))
472 _ => bug!("{} is not callable", callee.layout.ty),
474 let def = instance.map(|i| i.def);
475 let sig = callee.layout.ty.fn_sig(bx.tcx());
476 let sig = bx.tcx().normalize_erasing_late_bound_regions(
477 ty::ParamEnv::reveal_all(),
482 // Handle intrinsics old codegen wants Expr's for, ourselves.
483 let intrinsic = match def {
484 Some(ty::InstanceDef::Intrinsic(def_id)) =>
485 Some(bx.tcx().item_name(def_id).as_str()),
488 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
490 if intrinsic == Some("transmute") {
491 if let Some(destination_ref) = destination.as_ref() {
492 let &(ref dest, target) = destination_ref;
493 self.codegen_transmute(&mut bx, &args[0], dest);
494 helper.funclet_br(self, &mut bx, target);
496 // If we are trying to transmute to an uninhabited type,
497 // it is likely there is no allotted destination. In fact,
498 // transmuting to an uninhabited type is UB, which means
499 // we can do what we like. Here, we declare that transmuting
500 // into an uninhabited type is impossible, so anything following
501 // it must be unreachable.
502 assert_eq!(bx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
508 // The "spoofed" `VaList` added to a C-variadic functions signature
509 // should not be included in the `extra_args` calculation.
510 let extra_args_start_idx = sig.inputs().len() - if sig.variadic { 1 } else { 0 };
511 let extra_args = &args[extra_args_start_idx..];
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 bx.new_vtable(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.funclet_br(self, &mut bx, target);
527 _ => bx.new_fn_type(sig, &extra_args)
530 // Emit a panic or a no-op for `panic_if_uninhabited`.
531 if intrinsic == Some("panic_if_uninhabited") {
532 let ty = instance.unwrap().substs.type_at(0);
533 let layout = bx.layout_of(ty);
534 if layout.abi.is_uninhabited() {
535 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
536 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
537 let filename = bx.const_str_slice(filename);
538 let line = bx.const_u32(loc.line as u32);
539 let col = bx.const_u32(loc.col.to_usize() as u32 + 1);
540 let align = self.cx.tcx().data_layout.aggregate_align.abi
541 .max(self.cx.tcx().data_layout.i32_align.abi)
542 .max(self.cx.tcx().data_layout.pointer_align.abi);
545 "Attempted to instantiate uninhabited type {}",
548 let msg_str = Symbol::intern(&str).as_str();
549 let msg_str = bx.const_str_slice(msg_str);
550 let msg_file_line_col = bx.const_struct(
551 &[msg_str, filename, line, col],
554 let msg_file_line_col = bx.static_addr_of(
560 // Obtain the panic entry point.
562 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
563 let instance = ty::Instance::mono(bx.tcx(), def_id);
564 let fn_ty = bx.fn_type_of_instance(&instance);
565 let llfn = bx.get_fn(instance);
567 // Codegen the actual panic invoke/call.
573 &[msg_file_line_col],
574 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
579 helper.funclet_br(self, &mut bx, destination.as_ref().unwrap().1)
584 // The arguments we'll be passing. Plus one to account for outptr, if used.
585 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
586 let mut llargs = Vec::with_capacity(arg_count);
588 // Prepare the return value destination
589 let ret_dest = if let Some((ref dest, _)) = *destination {
590 let is_intrinsic = intrinsic.is_some();
591 self.make_return_dest(&mut bx, dest, &fn_ty.ret, &mut llargs,
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(mir::Place::Promoted(box(index, ty))) |
619 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
620 let param_env = ty::ParamEnv::reveal_all();
621 let cid = mir::interpret::GlobalId {
622 instance: self.instance,
623 promoted: Some(index),
625 let c = bx.tcx().const_eval(param_env.and(cid));
626 let (llval, ty) = self.simd_shuffle_indices(
628 terminator.source_info.span,
633 val: Immediate(llval),
634 layout: bx.layout_of(ty),
638 mir::Operand::Copy(_) |
639 mir::Operand::Move(_) => {
640 span_bug!(span, "shuffle indices must be constant");
642 mir::Operand::Constant(ref constant) => {
643 let c = self.eval_mir_constant(&bx, constant);
644 let (llval, ty) = self.simd_shuffle_indices(
651 val: Immediate(llval),
652 layout: bx.layout_of(ty)
658 self.codegen_operand(&mut bx, arg)
662 let callee_ty = instance.as_ref().unwrap().ty(bx.tcx());
663 bx.codegen_intrinsic_call(callee_ty, &fn_ty, &args, dest,
664 terminator.source_info.span);
666 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
667 self.store_return(&mut bx, ret_dest, &fn_ty.ret, dst.llval);
670 if let Some((_, target)) = *destination {
671 helper.funclet_br(self, &mut bx, target);
679 // Split the rust-call tupled arguments off.
680 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
681 let (tup, args) = args.split_last().unwrap();
687 // Useful determining if the current argument is the "spoofed" `VaList`
688 let last_arg_idx = if sig.inputs().is_empty() {
691 Some(sig.inputs().len() - 1)
693 'make_args: for (i, arg) in first_args.iter().enumerate() {
694 // If this is a C-variadic function the function signature contains
695 // an "spoofed" `VaList`. This argument is ignored, but we need to
696 // populate it with a dummy operand so that the users real arguments
697 // are not overwritten.
698 let i = if sig.variadic && last_arg_idx.map(|x| x == i).unwrap_or(false) {
699 let layout = match self.cx.tcx().lang_items().va_list() {
700 Some(did) => bx.cx().layout_of(bx.tcx().type_of(did)),
701 None => bug!("`va_list` language item required for C-variadics"),
703 let op = OperandRef {
704 val: OperandValue::Immediate(
705 bx.cx().const_undef(bx.cx().immediate_backend_type(layout)
709 self.codegen_argument(&mut bx, op, &mut llargs, &fn_ty.args[i]);
710 if i + 1 < fn_ty.args.len() {
718 let mut op = self.codegen_operand(&mut bx, arg);
720 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
721 if let Pair(..) = op.val {
722 // In the case of Rc<Self>, we need to explicitly pass a
723 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
724 // that is understood elsewhere in the compiler as a method on
726 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
727 // we get a value of a built-in pointer type
728 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
729 && !op.layout.ty.is_region_ptr()
731 'iter_fields: for i in 0..op.layout.fields.count() {
732 let field = op.extract_field(&mut bx, i);
733 if !field.layout.is_zst() {
734 // we found the one non-zero-sized field that is allowed
735 // now find *its* non-zero-sized field, or stop if it's a
738 continue 'descend_newtypes
742 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
745 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
746 // data pointer and vtable. Look up the method in the vtable, and pass
747 // the data pointer as the first argument
749 Pair(data_ptr, meta) => {
750 llfn = Some(meth::VirtualIndex::from_index(idx)
751 .get_fn(&mut bx, meta, &fn_ty));
752 llargs.push(data_ptr);
755 other => bug!("expected a Pair, got {:?}", other),
757 } else if let Ref(data_ptr, Some(meta), _) = op.val {
758 // by-value dynamic dispatch
759 llfn = Some(meth::VirtualIndex::from_index(idx)
760 .get_fn(&mut bx, meta, &fn_ty));
761 llargs.push(data_ptr);
764 span_bug!(span, "can't codegen a virtual call on {:?}", op);
768 // The callee needs to own the argument memory if we pass it
769 // by-ref, so make a local copy of non-immediate constants.
770 match (arg, op.val) {
771 (&mir::Operand::Copy(_), Ref(_, None, _)) |
772 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
773 let tmp = PlaceRef::alloca(&mut bx, op.layout, "const");
774 op.val.store(&mut bx, tmp);
775 op.val = Ref(tmp.llval, None, tmp.align);
780 self.codegen_argument(&mut bx, op, &mut llargs, &fn_ty.args[i]);
782 if let Some(tup) = untuple {
783 self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
784 &fn_ty.args[first_args.len()..])
787 let fn_ptr = match (llfn, instance) {
788 (Some(llfn), _) => llfn,
789 (None, Some(instance)) => bx.get_fn(instance),
790 _ => span_bug!(span, "no llfn for call"),
793 helper.do_call(self, &mut bx, fn_ty, fn_ptr, &llargs,
794 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
799 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
800 pub fn codegen_block(
804 let mut bx = self.build_block(bb);
805 let data = &self.mir[bb];
807 debug!("codegen_block({:?}={:?})", bb, data);
809 for statement in &data.statements {
810 bx = self.codegen_statement(bx, statement);
813 self.codegen_terminator(bx, bb, data.terminator());
816 fn codegen_terminator(
820 terminator: &mir::Terminator<'tcx>
822 debug!("codegen_terminator: {:?}", terminator);
824 // Create the cleanup bundle, if needed.
825 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
826 let helper = TerminatorCodegenHelper {
827 bb: &bb, terminator, funclet_bb
830 self.set_debug_loc(&mut bx, terminator.source_info);
831 match terminator.kind {
832 mir::TerminatorKind::Resume => {
833 self.codegen_resume_terminator(helper, bx)
836 mir::TerminatorKind::Abort => {
841 mir::TerminatorKind::Goto { target } => {
842 helper.funclet_br(self, &mut bx, target);
845 mir::TerminatorKind::SwitchInt {
846 ref discr, switch_ty, ref values, ref targets
848 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
852 mir::TerminatorKind::Return => {
853 self.codegen_return_terminator(bx);
856 mir::TerminatorKind::Unreachable => {
860 mir::TerminatorKind::Drop { ref location, target, unwind } => {
861 self.codegen_drop_terminator(helper, bx, location, target, unwind);
864 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
865 self.codegen_assert_terminator(helper, bx, terminator, cond,
866 expected, msg, target, cleanup);
869 mir::TerminatorKind::DropAndReplace { .. } => {
870 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
873 mir::TerminatorKind::Call {
880 self.codegen_call_terminator(helper, bx, terminator, func,
881 args, destination, cleanup);
883 mir::TerminatorKind::GeneratorDrop |
884 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
885 mir::TerminatorKind::FalseEdges { .. } |
886 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
893 op: OperandRef<'tcx, Bx::Value>,
894 llargs: &mut Vec<Bx::Value>,
895 arg: &ArgType<'tcx, Ty<'tcx>>
897 // Fill padding with undef value, where applicable.
898 if let Some(ty) = arg.pad {
899 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
906 if let PassMode::Pair(..) = arg.mode {
913 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
915 } else if arg.is_unsized_indirect() {
917 Ref(a, Some(b), _) => {
922 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
926 // Force by-ref if we have to load through a cast pointer.
927 let (mut llval, align, by_ref) = match op.val {
928 Immediate(_) | Pair(..) => {
930 PassMode::Indirect(..) | PassMode::Cast(_) => {
931 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
932 op.val.store(bx, scratch);
933 (scratch.llval, scratch.align, true)
936 (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
940 Ref(llval, _, align) => {
941 if arg.is_indirect() && align < arg.layout.align.abi {
942 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
943 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
944 // have scary latent bugs around.
946 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
947 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
948 op.layout, MemFlags::empty());
949 (scratch.llval, scratch.align, true)
956 if by_ref && !arg.is_indirect() {
957 // Have to load the argument, maybe while casting it.
958 if let PassMode::Cast(ty) = arg.mode {
959 let addr = bx.pointercast(llval, bx.type_ptr_to(
960 bx.cast_backend_type(&ty))
962 llval = bx.load(addr, align.min(arg.layout.align.abi));
964 // We can't use `PlaceRef::load` here because the argument
965 // may have a type we don't treat as immediate, but the ABI
966 // used for this call is passing it by-value. In that case,
967 // the load would just produce `OperandValue::Ref` instead
968 // of the `OperandValue::Immediate` we need for the call.
969 llval = bx.load(llval, align);
970 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
971 if scalar.is_bool() {
972 bx.range_metadata(llval, 0..2);
975 // We store bools as i8 so we need to truncate to i1.
976 llval = base::to_immediate(bx, llval, arg.layout);
983 fn codegen_arguments_untupled(
986 operand: &mir::Operand<'tcx>,
987 llargs: &mut Vec<Bx::Value>,
988 args: &[ArgType<'tcx, Ty<'tcx>>]
990 let tuple = self.codegen_operand(bx, operand);
992 // Handle both by-ref and immediate tuples.
993 if let Ref(llval, None, align) = tuple.val {
994 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
995 for i in 0..tuple.layout.fields.count() {
996 let field_ptr = tuple_ptr.project_field(bx, i);
997 let field = bx.load_operand(field_ptr);
998 self.codegen_argument(bx, field, llargs, &args[i]);
1000 } else if let Ref(_, Some(_), _) = tuple.val {
1001 bug!("closure arguments must be sized")
1003 // If the tuple is immediate, the elements are as well.
1004 for i in 0..tuple.layout.fields.count() {
1005 let op = tuple.extract_field(bx, i);
1006 self.codegen_argument(bx, op, llargs, &args[i]);
1011 fn get_personality_slot(
1014 ) -> PlaceRef<'tcx, Bx::Value> {
1016 if let Some(slot) = self.personality_slot {
1019 let layout = cx.layout_of(cx.tcx().intern_tup(&[
1020 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
1023 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
1024 self.personality_slot = Some(slot);
1029 /// Returns the landing-pad wrapper around the given basic block.
1031 /// No-op in MSVC SEH scheme.
1034 target_bb: mir::BasicBlock
1035 ) -> Bx::BasicBlock {
1036 if let Some(block) = self.landing_pads[target_bb] {
1040 let block = self.blocks[target_bb];
1041 let landing_pad = self.landing_pad_uncached(block);
1042 self.landing_pads[target_bb] = Some(landing_pad);
1046 fn landing_pad_uncached(
1048 target_bb: Bx::BasicBlock
1049 ) -> Bx::BasicBlock {
1050 if base::wants_msvc_seh(self.cx.sess()) {
1051 span_bug!(self.mir.span, "landing pad was not inserted?")
1054 let mut bx = self.new_block("cleanup");
1056 let llpersonality = self.cx.eh_personality();
1057 let llretty = self.landing_pad_type();
1058 let lp = bx.landing_pad(llretty, llpersonality, 1);
1061 let slot = self.get_personality_slot(&mut bx);
1062 slot.storage_live(&mut bx);
1063 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1069 fn landing_pad_type(&self) -> Bx::Type {
1071 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1074 fn unreachable_block(
1076 ) -> Bx::BasicBlock {
1077 self.unreachable_block.unwrap_or_else(|| {
1078 let mut bx = self.new_block("unreachable");
1080 self.unreachable_block = Some(bx.llbb());
1085 pub fn new_block(&self, name: &str) -> Bx {
1086 Bx::new_block(self.cx, self.llfn, name)
1093 let mut bx = Bx::with_cx(self.cx);
1094 bx.position_at_end(self.blocks[bb]);
1098 fn make_return_dest(
1101 dest: &mir::Place<'tcx>,
1102 fn_ret: &ArgType<'tcx, Ty<'tcx>>,
1103 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1104 ) -> ReturnDest<'tcx, Bx::Value> {
1105 // If the return is ignored, we can just return a do-nothing ReturnDest
1106 if fn_ret.is_ignore() {
1107 return ReturnDest::Nothing;
1109 let dest = if let mir::Place::Local(index) = *dest {
1110 match self.locals[index] {
1111 LocalRef::Place(dest) => dest,
1112 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1113 LocalRef::Operand(None) => {
1114 // Handle temporary places, specifically Operand ones, as
1115 // they don't have allocas
1116 return if fn_ret.is_indirect() {
1117 // Odd, but possible, case, we have an operand temporary,
1118 // but the calling convention has an indirect return.
1119 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
1120 tmp.storage_live(bx);
1121 llargs.push(tmp.llval);
1122 ReturnDest::IndirectOperand(tmp, index)
1123 } else if is_intrinsic {
1124 // Currently, intrinsics always need a location to store
1125 // the result. so we create a temporary alloca for the
1127 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
1128 tmp.storage_live(bx);
1129 ReturnDest::IndirectOperand(tmp, index)
1131 ReturnDest::DirectOperand(index)
1134 LocalRef::Operand(Some(_)) => {
1135 bug!("place local already assigned to");
1139 self.codegen_place(bx, dest)
1141 if fn_ret.is_indirect() {
1142 if dest.align < dest.layout.align.abi {
1143 // Currently, MIR code generation does not create calls
1144 // that store directly to fields of packed structs (in
1145 // fact, the calls it creates write only to temps),
1147 // If someone changes that, please update this code path
1148 // to create a temporary.
1149 span_bug!(self.mir.span, "can't directly store to unaligned value");
1151 llargs.push(dest.llval);
1154 ReturnDest::Store(dest)
1158 fn codegen_transmute(
1161 src: &mir::Operand<'tcx>,
1162 dst: &mir::Place<'tcx>
1164 if let mir::Place::Local(index) = *dst {
1165 match self.locals[index] {
1166 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1167 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1168 LocalRef::Operand(None) => {
1169 let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst));
1170 assert!(!dst_layout.ty.has_erasable_regions());
1171 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
1172 place.storage_live(bx);
1173 self.codegen_transmute_into(bx, src, place);
1174 let op = bx.load_operand(place);
1175 place.storage_dead(bx);
1176 self.locals[index] = LocalRef::Operand(Some(op));
1178 LocalRef::Operand(Some(op)) => {
1179 assert!(op.layout.is_zst(),
1180 "assigning to initialized SSAtemp");
1184 let dst = self.codegen_place(bx, dst);
1185 self.codegen_transmute_into(bx, src, dst);
1189 fn codegen_transmute_into(
1192 src: &mir::Operand<'tcx>,
1193 dst: PlaceRef<'tcx, Bx::Value>
1195 let src = self.codegen_operand(bx, src);
1196 let llty = bx.backend_type(src.layout);
1197 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1198 let align = src.layout.align.abi.min(dst.align);
1199 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1203 // Stores the return value of a function call into it's final location.
1207 dest: ReturnDest<'tcx, Bx::Value>,
1208 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1211 use self::ReturnDest::*;
1215 Store(dst) => bx.store_arg_ty(&ret_ty, llval, dst),
1216 IndirectOperand(tmp, index) => {
1217 let op = bx.load_operand(tmp);
1218 tmp.storage_dead(bx);
1219 self.locals[index] = LocalRef::Operand(Some(op));
1221 DirectOperand(index) => {
1222 // If there is a cast, we have to store and reload.
1223 let op = if let PassMode::Cast(_) = ret_ty.mode {
1224 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1225 tmp.storage_live(bx);
1226 bx.store_arg_ty(&ret_ty, llval, tmp);
1227 let op = bx.load_operand(tmp);
1228 tmp.storage_dead(bx);
1231 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1233 self.locals[index] = LocalRef::Operand(Some(op));
1239 enum ReturnDest<'tcx, V> {
1240 // Do nothing, the return value is indirect or ignored
1242 // Store the return value to the pointer
1243 Store(PlaceRef<'tcx, V>),
1244 // Stores an indirect return value to an operand local place
1245 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1246 // Stores a direct return value to an operand local place
1247 DirectOperand(mir::Local)