]> git.proxmox.com Git - rustc.git/blame - src/librustc_codegen_ssa/mir/block.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustc_codegen_ssa / mir / block.rs
CommitLineData
e74abb32 1use rustc_index::vec::Idx;
3157f602 2use rustc::middle::lang_items;
dc9dc135 3use rustc::ty::{self, Ty, TypeFoldable, Instance};
60c5eb7d 4use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, FnAbiExt};
e74abb32 5use rustc::mir::{self, PlaceBase, Static, StaticKind};
416331ca 6use rustc::mir::interpret::PanicInfo;
60c5eb7d 7use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
a1dfa0c6 8use rustc_target::spec::abi::Abi;
9fa01778
XL
9use crate::base;
10use crate::MemFlags;
11use crate::common::{self, IntPredicate};
12use crate::meth;
a1dfa0c6 13
9fa01778 14use crate::traits::*;
3157f602 15
532ac7d7
XL
16use std::borrow::Cow;
17
e74abb32 18use syntax::{source_map::Span, symbol::Symbol};
54a0048b 19
2c00a5a8 20use super::{FunctionCx, LocalRef};
ff7c6d11 21use super::place::PlaceRef;
54a0048b 22use super::operand::OperandRef;
c30ab7b3
SL
23use super::operand::OperandValue::{Pair, Ref, Immediate};
24
532ac7d7
XL
25/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
26/// e.g., creating a basic block, calling a function, etc.
60c5eb7d
XL
27struct TerminatorCodegenHelper<'tcx> {
28 bb: mir::BasicBlock,
29 terminator: &'tcx mir::Terminator<'tcx>,
532ac7d7
XL
30 funclet_bb: Option<mir::BasicBlock>,
31}
32
60c5eb7d 33impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
532ac7d7
XL
34 /// Returns the associated funclet from `FunctionCx::funclets` for the
35 /// `funclet_bb` member if it is not `None`.
60c5eb7d 36 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 37 &self,
60c5eb7d
XL
38 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
39 ) -> Option<&'b Bx::Funclet> {
532ac7d7
XL
40 match self.funclet_bb {
41 Some(funcl) => fx.funclets[funcl].as_ref(),
42 None => None,
43 }
44 }
3157f602 45
60c5eb7d 46 fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 47 &self,
60c5eb7d 48 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7
XL
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) =>
57 (lltarget, false),
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),
7cac9316 62 }
532ac7d7 63 }
7cac9316 64
532ac7d7 65 /// Create a basic block.
60c5eb7d 66 fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 67 &self,
60c5eb7d 68 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7
XL
69 target: mir::BasicBlock,
70 ) -> Bx::BasicBlock {
71 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
72 if is_cleanupret {
73 // MSVC cross-funclet jump - need a trampoline
74
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(),
79 Some(lltarget));
80 trampoline.llbb()
81 } else {
82 lltarget
83 }
7cac9316
XL
84 }
85
60c5eb7d 86 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 87 &self,
60c5eb7d 88 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7
XL
89 bx: &mut Bx,
90 target: mir::BasicBlock,
a1dfa0c6 91 ) {
532ac7d7
XL
92 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
93 if is_cleanupret {
94 // micro-optimization: generate a `ret` rather than a jump
95 // to a trampoline.
96 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
97 } else {
98 bx.br(lltarget);
99 }
100 }
7cac9316 101
60c5eb7d 102 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
532ac7d7 103 /// return destination `destination` and the cleanup function `cleanup`.
60c5eb7d 104 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 105 &self,
60c5eb7d 106 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7 107 bx: &mut Bx,
60c5eb7d 108 fn_abi: FnAbi<'tcx, Ty<'tcx>>,
532ac7d7
XL
109 fn_ptr: Bx::Value,
110 llargs: &[Bx::Value],
111 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
112 cleanup: Option<mir::BasicBlock>,
113 ) {
114 if let Some(cleanup) = cleanup {
115 let ret_bx = if let Some((_, target)) = destination {
116 fx.blocks[target]
117 } else {
118 fx.unreachable_block()
119 };
120 let invokeret = bx.invoke(fn_ptr,
121 &llargs,
122 ret_bx,
123 self.llblock(fx, cleanup),
124 self.funclet(fx));
60c5eb7d 125 bx.apply_attrs_callsite(&fn_abi, invokeret);
532ac7d7
XL
126
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);
60c5eb7d 130 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
a1dfa0c6 131 }
532ac7d7
XL
132 } else {
133 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
60c5eb7d
XL
134 bx.apply_attrs_callsite(&fn_abi, llret);
135 if fx.mir[self.bb].is_cleanup {
532ac7d7
XL
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);
3157f602 141 }
7cac9316 142
532ac7d7 143 if let Some((ret_dest, target)) = destination {
60c5eb7d 144 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
532ac7d7 145 self.funclet_br(fx, bx, target);
7cac9316 146 } else {
532ac7d7 147 bx.unreachable();
7cac9316 148 }
532ac7d7
XL
149 }
150 }
e74abb32
XL
151
152 // Generate sideeffect intrinsic if jumping to any of the targets can form
153 // a loop.
60c5eb7d 154 fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
e74abb32 155 &self,
60c5eb7d 156 mir: mir::ReadOnlyBodyAndCache<'tcx, 'tcx>,
e74abb32
XL
157 bx: &mut Bx,
158 targets: &[mir::BasicBlock],
159 ) {
160 if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
60c5eb7d
XL
161 if targets.iter().any(|&target| {
162 target <= self.bb
e74abb32
XL
163 && target
164 .start_location()
165 .is_predecessor_of(self.bb.start_location(), mir)
166 }) {
167 bx.sideeffect();
168 }
169 }
170 }
532ac7d7 171}
3157f602 172
532ac7d7 173/// Codegen implementations for some terminator variants.
dc9dc135 174impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
532ac7d7 175 /// Generates code for a `Resume` terminator.
60c5eb7d 176 fn codegen_resume_terminator(
532ac7d7 177 &mut self,
60c5eb7d 178 helper: TerminatorCodegenHelper<'tcx>,
532ac7d7
XL
179 mut bx: Bx,
180 ) {
181 if let Some(funclet) = helper.funclet(self) {
182 bx.cleanup_ret(funclet, None);
183 } else {
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);
190
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);
195 bx.resume(lp);
3157f602 196 } else {
532ac7d7
XL
197 bx.call(bx.eh_unwind_resume(), &[lp0],
198 helper.funclet(self));
199 bx.unreachable();
200 }
201 }
202 }
7cac9316 203
60c5eb7d 204 fn codegen_switchint_terminator(
532ac7d7 205 &mut self,
60c5eb7d 206 helper: TerminatorCodegenHelper<'tcx>,
532ac7d7
XL
207 mut bx: Bx,
208 discr: &mir::Operand<'tcx>,
209 switch_ty: Ty<'tcx>,
210 values: &Cow<'tcx, [u128]>,
211 targets: &Vec<mir::BasicBlock>,
212 ) {
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 {
e74abb32 219 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
532ac7d7
XL
220 // Don't generate trivial icmps when switching on bool
221 if let [0] = values[..] {
222 bx.cond_br(discr.immediate(), llfalse, lltrue);
3157f602 223 } else {
532ac7d7
XL
224 assert_eq!(&values[..], &[1]);
225 bx.cond_br(discr.immediate(), lltrue, llfalse);
3157f602 226 }
532ac7d7
XL
227 } else {
228 let switch_llty = bx.immediate_backend_type(
229 bx.layout_of(switch_ty)
230 );
231 let llval = bx.const_uint_big(switch_llty, values[0]);
232 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
e74abb32 233 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
532ac7d7 234 bx.cond_br(cmp, lltrue, llfalse);
3157f602 235 }
532ac7d7 236 } else {
e74abb32 237 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
532ac7d7
XL
238 let (otherwise, targets) = targets.split_last().unwrap();
239 bx.switch(
240 discr.immediate(),
241 helper.llblock(self, *otherwise),
242 values.iter().zip(targets).map(|(&value, target)| {
243 (value, helper.llblock(self, *target))
244 })
245 );
246 }
247 }
54a0048b 248
dc9dc135 249 fn codegen_return_terminator(&mut self, mut bx: Bx) {
e74abb32 250 // Call `va_end` if this is the definition of a C-variadic function.
60c5eb7d 251 if self.fn_abi.c_variadic {
e74abb32 252 // The `VaList` "spoofed" argument is just after all the real arguments.
60c5eb7d 253 let va_list_arg_idx = self.fn_abi.args.len();
e74abb32
XL
254 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
255 LocalRef::Place(va_list) => {
532ac7d7
XL
256 bx.va_end(va_list.llval);
257 }
e74abb32 258 _ => bug!("C-variadic function must have a `VaList` place"),
54a0048b 259 }
532ac7d7 260 }
60c5eb7d 261 if self.fn_abi.ret.layout.abi.is_uninhabited() {
532ac7d7
XL
262 // Functions with uninhabited return values are marked `noreturn`,
263 // so we should make sure that we never actually do.
60c5eb7d
XL
264 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
265 // if that turns out to be helpful.
532ac7d7 266 bx.abort();
60c5eb7d
XL
267 // `abort` does not terminate the block, so we still need to generate
268 // an `unreachable` terminator after it.
532ac7d7
XL
269 bx.unreachable();
270 return;
271 }
60c5eb7d 272 let llval = match self.fn_abi.ret.mode {
e74abb32 273 PassMode::Ignore | PassMode::Indirect(..) => {
532ac7d7
XL
274 bx.ret_void();
275 return;
ff7c6d11
XL
276 }
277
532ac7d7
XL
278 PassMode::Direct(_) | PassMode::Pair(..) => {
279 let op =
e1599b0c 280 self.codegen_consume(&mut bx, &mir::Place::return_place().as_ref());
532ac7d7
XL
281 if let Ref(llval, _, align) = op.val {
282 bx.load(llval, align)
8bb4bdeb 283 } else {
532ac7d7 284 op.immediate_or_packed_pair(&mut bx)
54a0048b
SL
285 }
286 }
287
532ac7d7
XL
288 PassMode::Cast(cast_ty) => {
289 let op = match self.locals[mir::RETURN_PLACE] {
290 LocalRef::Operand(Some(op)) => op,
291 LocalRef::Operand(None) => bug!("use of return before def"),
292 LocalRef::Place(cg_place) => {
293 OperandRef {
294 val: Ref(cg_place.llval, None, cg_place.align),
295 layout: cg_place.layout
32a655c1 296 }
ff7c6d11 297 }
532ac7d7
XL
298 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
299 };
300 let llslot = match op.val {
301 Immediate(_) | Pair(..) => {
302 let scratch =
60c5eb7d 303 PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
532ac7d7
XL
304 op.val.store(&mut bx, scratch);
305 scratch.llval
306 }
307 Ref(llval, _, align) => {
308 assert_eq!(align, op.layout.align.abi,
309 "return place is unaligned!");
310 llval
476ff2be 311 }
3157f602 312 };
532ac7d7
XL
313 let addr = bx.pointercast(llslot, bx.type_ptr_to(
314 bx.cast_backend_type(&cast_ty)
315 ));
60c5eb7d 316 bx.load(addr, self.fn_abi.ret.layout.align.abi)
3157f602 317 }
532ac7d7
XL
318 };
319 bx.ret(llval);
320 }
3157f602 321
532ac7d7 322
60c5eb7d 323 fn codegen_drop_terminator(
532ac7d7 324 &mut self,
60c5eb7d 325 helper: TerminatorCodegenHelper<'tcx>,
532ac7d7
XL
326 mut bx: Bx,
327 location: &mir::Place<'tcx>,
328 target: mir::BasicBlock,
329 unwind: Option<mir::BasicBlock>,
330 ) {
60c5eb7d 331 let ty = location.ty(*self.mir, bx.tcx()).ty;
532ac7d7 332 let ty = self.monomorphize(&ty);
dc9dc135 333 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
532ac7d7
XL
334
335 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
336 // we don't actually need to drop anything.
e74abb32 337 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
338 helper.funclet_br(self, &mut bx, target);
339 return
340 }
341
416331ca 342 let place = self.codegen_place(&mut bx, &location.as_ref());
532ac7d7
XL
343 let (args1, args2);
344 let mut args = if let Some(llextra) = place.llextra {
345 args2 = [place.llval, llextra];
346 &args2[..]
347 } else {
348 args1 = [place.llval];
349 &args1[..]
350 };
60c5eb7d
XL
351 let (drop_fn, fn_abi) = match ty.kind {
352 // FIXME(eddyb) perhaps move some of this logic into
353 // `Instance::resolve_drop_in_place`?
532ac7d7 354 ty::Dynamic(..) => {
60c5eb7d
XL
355 let virtual_drop = Instance {
356 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
357 substs: drop_fn.substs,
358 };
359 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
532ac7d7
XL
360 let vtable = args[1];
361 args = &args[..1];
60c5eb7d 362 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
54a0048b 363 }
532ac7d7 364 _ => {
e74abb32 365 (bx.get_fn_addr(drop_fn),
60c5eb7d 366 FnAbi::of_instance(&bx, drop_fn, &[]))
532ac7d7
XL
367 }
368 };
e74abb32 369 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
60c5eb7d 370 helper.do_call(self, &mut bx, fn_abi, drop_fn, args,
532ac7d7
XL
371 Some((ReturnDest::Nothing, target)),
372 unwind);
373 }
54a0048b 374
60c5eb7d 375 fn codegen_assert_terminator(
532ac7d7 376 &mut self,
60c5eb7d 377 helper: TerminatorCodegenHelper<'tcx>,
532ac7d7
XL
378 mut bx: Bx,
379 terminator: &mir::Terminator<'tcx>,
380 cond: &mir::Operand<'tcx>,
381 expected: bool,
382 msg: &mir::AssertMessage<'tcx>,
383 target: mir::BasicBlock,
384 cleanup: Option<mir::BasicBlock>,
385 ) {
386 let span = terminator.source_info.span;
387 let cond = self.codegen_operand(&mut bx, cond).immediate();
388 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
389
390 // This case can currently arise only from functions marked
391 // with #[rustc_inherit_overflow_checks] and inlined from
392 // another crate (mostly core::num generic/#[inline] fns),
393 // while the current crate doesn't use overflow checks.
394 // NOTE: Unlike binops, negation doesn't have its own
395 // checked operation, just a comparison with the minimum
396 // value, so we have to check for the assert message.
397 if !bx.check_overflow() {
416331ca 398 if let PanicInfo::OverflowNeg = *msg {
532ac7d7
XL
399 const_cond = Some(expected);
400 }
401 }
3157f602 402
532ac7d7
XL
403 // Don't codegen the panic block if success if known.
404 if const_cond == Some(expected) {
e74abb32 405 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
406 helper.funclet_br(self, &mut bx, target);
407 return;
408 }
409
410 // Pass the condition through llvm.expect for branch hinting.
411 let cond = bx.expect(cond, expected);
412
413 // Create the failure block and the conditional branch to it.
414 let lltarget = helper.llblock(self, target);
415 let panic_block = self.new_block("panic");
e74abb32 416 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
417 if expected {
418 bx.cond_br(cond, lltarget, panic_block.llbb());
419 } else {
420 bx.cond_br(cond, panic_block.llbb(), lltarget);
421 }
422
423 // After this point, bx is the block for the call to panic.
424 bx = panic_block;
425 self.set_debug_loc(&mut bx, terminator.source_info);
426
427 // Get the location information.
e74abb32 428 let location = self.get_caller_location(&mut bx, span).immediate();
532ac7d7
XL
429
430 // Put together the arguments to the panic entry point.
416331ca
XL
431 let (lang_item, args) = match msg {
432 PanicInfo::BoundsCheck { ref len, ref index } => {
532ac7d7
XL
433 let len = self.codegen_operand(&mut bx, len).immediate();
434 let index = self.codegen_operand(&mut bx, index).immediate();
e74abb32 435 (lang_items::PanicBoundsCheckFnLangItem, vec![location, index, len])
532ac7d7
XL
436 }
437 _ => {
e1599b0c 438 let msg_str = Symbol::intern(msg.description());
e74abb32
XL
439 let msg = bx.const_str(msg_str);
440 (lang_items::PanicFnLangItem, vec![msg.0, msg.1, location])
3157f602 441 }
532ac7d7 442 };
3157f602 443
532ac7d7
XL
444 // Obtain the panic entry point.
445 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
446 let instance = ty::Instance::mono(bx.tcx(), def_id);
60c5eb7d 447 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
e74abb32 448 let llfn = bx.get_fn_addr(instance);
3157f602 449
532ac7d7 450 // Codegen the actual panic invoke/call.
60c5eb7d 451 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
532ac7d7 452 }
3157f602 453
60c5eb7d 454 fn codegen_call_terminator(
532ac7d7 455 &mut self,
60c5eb7d 456 helper: TerminatorCodegenHelper<'tcx>,
532ac7d7
XL
457 mut bx: Bx,
458 terminator: &mir::Terminator<'tcx>,
459 func: &mir::Operand<'tcx>,
460 args: &Vec<mir::Operand<'tcx>>,
461 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
462 cleanup: Option<mir::BasicBlock>,
463 ) {
464 let span = terminator.source_info.span;
465 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
466 let callee = self.codegen_operand(&mut bx, func);
467
e74abb32 468 let (instance, mut llfn) = match callee.layout.ty.kind {
532ac7d7
XL
469 ty::FnDef(def_id, substs) => {
470 (Some(ty::Instance::resolve(bx.tcx(),
471 ty::ParamEnv::reveal_all(),
472 def_id,
473 substs).unwrap()),
474 None)
475 }
476 ty::FnPtr(_) => {
477 (None, Some(callee.immediate()))
478 }
479 _ => bug!("{} is not callable", callee.layout.ty),
480 };
481 let def = instance.map(|i| i.def);
60c5eb7d
XL
482
483 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
484 // Empty drop glue; a no-op.
485 let &(_, target) = destination.as_ref().unwrap();
486 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
487 helper.funclet_br(self, &mut bx, target);
488 return;
489 }
490
491 // FIXME(eddyb) avoid computing this if possible, when `instance` is
492 // available - right now `sig` is only needed for getting the `abi`
493 // and figuring out how many extra args were passed to a C-variadic `fn`.
532ac7d7 494 let sig = callee.layout.ty.fn_sig(bx.tcx());
60c5eb7d 495 let abi = sig.abi();
532ac7d7
XL
496
497 // Handle intrinsics old codegen wants Expr's for, ourselves.
498 let intrinsic = match def {
499 Some(ty::InstanceDef::Intrinsic(def_id)) =>
500 Some(bx.tcx().item_name(def_id).as_str()),
501 _ => None
502 };
503 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
3157f602 504
60c5eb7d
XL
505 let extra_args = &args[sig.inputs().skip_binder().len()..];
506 let extra_args = extra_args.iter().map(|op_arg| {
507 let op_ty = op_arg.ty(*self.mir, bx.tcx());
508 self.monomorphize(&op_ty)
509 }).collect::<Vec<_>>();
510
511 let fn_abi = match instance {
512 Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
513 None => FnAbi::of_fn_ptr(&bx, sig, &extra_args)
514 };
515
532ac7d7
XL
516 if intrinsic == Some("transmute") {
517 if let Some(destination_ref) = destination.as_ref() {
518 let &(ref dest, target) = destination_ref;
519 self.codegen_transmute(&mut bx, &args[0], dest);
e74abb32 520 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
521 helper.funclet_br(self, &mut bx, target);
522 } else {
523 // If we are trying to transmute to an uninhabited type,
524 // it is likely there is no allotted destination. In fact,
525 // transmuting to an uninhabited type is UB, which means
526 // we can do what we like. Here, we declare that transmuting
527 // into an uninhabited type is impossible, so anything following
528 // it must be unreachable.
60c5eb7d 529 assert_eq!(fn_abi.ret.layout.abi, layout::Abi::Uninhabited);
532ac7d7
XL
530 bx.unreachable();
531 }
532 return;
533 }
3157f602 534
60c5eb7d
XL
535 // For normal codegen, this Miri-specific intrinsic is just a NOP.
536 if intrinsic == Some("miri_start_panic") {
537 let target = destination.as_ref().unwrap().1;
538 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
539 helper.funclet_br(self, &mut bx, target);
540 return;
541 }
3157f602 542
532ac7d7
XL
543 // Emit a panic or a no-op for `panic_if_uninhabited`.
544 if intrinsic == Some("panic_if_uninhabited") {
545 let ty = instance.unwrap().substs.type_at(0);
546 let layout = bx.layout_of(ty);
547 if layout.abi.is_uninhabited() {
e74abb32
XL
548 let msg_str = format!("Attempted to instantiate uninhabited type {}", ty);
549 let msg = bx.const_str(Symbol::intern(&msg_str));
550 let location = self.get_caller_location(&mut bx, span).immediate();
3157f602 551
3157f602 552 // Obtain the panic entry point.
532ac7d7
XL
553 let def_id =
554 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
2c00a5a8 555 let instance = ty::Instance::mono(bx.tcx(), def_id);
60c5eb7d 556 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
e74abb32 557 let llfn = bx.get_fn_addr(instance);
3157f602 558
e74abb32
XL
559 if let Some((_, target)) = destination.as_ref() {
560 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
561 }
94b46f34 562 // Codegen the actual panic invoke/call.
532ac7d7
XL
563 helper.do_call(
564 self,
565 &mut bx,
60c5eb7d 566 fn_abi,
532ac7d7 567 llfn,
e74abb32 568 &[msg.0, msg.1, location],
532ac7d7
XL
569 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
570 cleanup,
571 );
572 } else {
573 // a NOP
e74abb32
XL
574 let target = destination.as_ref().unwrap().1;
575 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
60c5eb7d 576 helper.funclet_br(self, &mut bx, target)
54a0048b 577 }
532ac7d7
XL
578 return;
579 }
54a0048b 580
532ac7d7 581 // The arguments we'll be passing. Plus one to account for outptr, if used.
60c5eb7d 582 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
532ac7d7 583 let mut llargs = Vec::with_capacity(arg_count);
3157f602 584
532ac7d7
XL
585 // Prepare the return value destination
586 let ret_dest = if let Some((ref dest, _)) = *destination {
587 let is_intrinsic = intrinsic.is_some();
60c5eb7d 588 self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs,
532ac7d7
XL
589 is_intrinsic)
590 } else {
591 ReturnDest::Nothing
592 };
54a0048b 593
e74abb32
XL
594 if intrinsic == Some("caller_location") {
595 if let Some((_, target)) = destination.as_ref() {
596 let location = self.get_caller_location(&mut bx, span);
597
598 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
599 location.val.store(&mut bx, tmp);
600 }
60c5eb7d 601 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
e74abb32
XL
602
603 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
604 helper.funclet_br(self, &mut bx, *target);
605 }
606 return;
607 }
608
532ac7d7
XL
609 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
610 let dest = match ret_dest {
60c5eb7d 611 _ if fn_abi.ret.is_indirect() => llargs[0],
532ac7d7 612 ReturnDest::Nothing =>
60c5eb7d 613 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret))),
532ac7d7
XL
614 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) =>
615 dst.llval,
616 ReturnDest::DirectOperand(_) =>
617 bug!("Cannot use direct operand with an intrinsic call"),
618 };
54a0048b 619
532ac7d7
XL
620 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
621 // The indices passed to simd_shuffle* in the
622 // third argument must be constant. This is
623 // checked by const-qualification, which also
624 // promotes any complex rvalues to constants.
625 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
e74abb32 626 match arg {
532ac7d7
XL
627 // The shuffle array argument is usually not an explicit constant,
628 // but specified directly in the code. This means it gets promoted
629 // and we can then extract the value by evaluating the promoted.
e74abb32
XL
630 mir::Operand::Copy(place) | mir::Operand::Move(place) => {
631 if let mir::PlaceRef {
632 base:
633 &PlaceBase::Static(box Static {
634 kind: StaticKind::Promoted(promoted, _),
635 ty,
636 def_id: _,
637 }),
638 projection: &[],
639 } = place.as_ref()
640 {
641 let param_env = ty::ParamEnv::reveal_all();
642 let cid = mir::interpret::GlobalId {
643 instance: self.instance,
644 promoted: Some(promoted),
645 };
646 let c = bx.tcx().const_eval(param_env.and(cid));
647 let (llval, ty) = self.simd_shuffle_indices(
648 &bx,
649 terminator.source_info.span,
416331ca 650 ty,
e74abb32
XL
651 c,
652 );
653 return OperandRef {
654 val: Immediate(llval),
655 layout: bx.layout_of(ty),
656 };
657 } else {
658 span_bug!(span, "shuffle indices must be constant");
416331ca 659 }
532ac7d7 660 }
e74abb32
XL
661
662 mir::Operand::Constant(constant) => {
532ac7d7
XL
663 let c = self.eval_mir_constant(constant);
664 let (llval, ty) = self.simd_shuffle_indices(
665 &bx,
666 constant.span,
e1599b0c 667 constant.literal.ty,
532ac7d7
XL
668 c,
669 );
670 return OperandRef {
671 val: Immediate(llval),
672 layout: bx.layout_of(ty)
673 };
674 }
94b46f34 675 }
54a0048b
SL
676 }
677
532ac7d7
XL
678 self.codegen_operand(&mut bx, arg)
679 }).collect();
32a655c1 680
532ac7d7 681
60c5eb7d 682 bx.codegen_intrinsic_call(*instance.as_ref().unwrap(), &fn_abi, &args, dest,
532ac7d7
XL
683 terminator.source_info.span);
684
685 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
60c5eb7d 686 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
532ac7d7
XL
687 }
688
689 if let Some((_, target)) = *destination {
e74abb32 690 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
691 helper.funclet_br(self, &mut bx, target);
692 } else {
693 bx.unreachable();
694 }
695
696 return;
697 }
698
699 // Split the rust-call tupled arguments off.
700 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
701 let (tup, args) = args.split_last().unwrap();
702 (args, Some(tup))
703 } else {
704 (&args[..], None)
705 };
706
532ac7d7 707 'make_args: for (i, arg) in first_args.iter().enumerate() {
532ac7d7
XL
708 let mut op = self.codegen_operand(&mut bx, arg);
709
710 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
711 if let Pair(..) = op.val {
712 // In the case of Rc<Self>, we need to explicitly pass a
713 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
714 // that is understood elsewhere in the compiler as a method on
715 // `dyn Trait`.
716 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
717 // we get a value of a built-in pointer type
718 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
719 && !op.layout.ty.is_region_ptr()
720 {
60c5eb7d 721 for i in 0..op.layout.fields.count() {
532ac7d7
XL
722 let field = op.extract_field(&mut bx, i);
723 if !field.layout.is_zst() {
724 // we found the one non-zero-sized field that is allowed
725 // now find *its* non-zero-sized field, or stop if it's a
726 // pointer
727 op = field;
728 continue 'descend_newtypes
729 }
730 }
731
732 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
32a655c1 733 }
54a0048b 734
532ac7d7
XL
735 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
736 // data pointer and vtable. Look up the method in the vtable, and pass
737 // the data pointer as the first argument
738 match op.val {
739 Pair(data_ptr, meta) => {
740 llfn = Some(meth::VirtualIndex::from_index(idx)
60c5eb7d 741 .get_fn(&mut bx, meta, &fn_abi));
532ac7d7
XL
742 llargs.push(data_ptr);
743 continue 'make_args
744 }
745 other => bug!("expected a Pair, got {:?}", other),
0731742a 746 }
532ac7d7
XL
747 } else if let Ref(data_ptr, Some(meta), _) = op.val {
748 // by-value dynamic dispatch
749 llfn = Some(meth::VirtualIndex::from_index(idx)
60c5eb7d 750 .get_fn(&mut bx, meta, &fn_abi));
532ac7d7
XL
751 llargs.push(data_ptr);
752 continue;
753 } else {
754 span_bug!(span, "can't codegen a virtual call on {:?}", op);
0bf4aa26 755 }
532ac7d7 756 }
0bf4aa26 757
532ac7d7
XL
758 // The callee needs to own the argument memory if we pass it
759 // by-ref, so make a local copy of non-immediate constants.
760 match (arg, op.val) {
761 (&mir::Operand::Copy(_), Ref(_, None, _)) |
762 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
e1599b0c 763 let tmp = PlaceRef::alloca(&mut bx, op.layout);
532ac7d7
XL
764 op.val.store(&mut bx, tmp);
765 op.val = Ref(tmp.llval, None, tmp.align);
766 }
767 _ => {}
768 }
54a0048b 769
60c5eb7d 770 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
532ac7d7
XL
771 }
772 if let Some(tup) = untuple {
773 self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
60c5eb7d
XL
774 &fn_abi.args[first_args.len()..])
775 }
776
777 let needs_location =
778 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
779 if needs_location {
780 assert_eq!(
781 fn_abi.args.len(), args.len() + 1,
782 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
783 );
784 let location = self.get_caller_location(&mut bx, span);
785 let last_arg = fn_abi.args.last().unwrap();
786 self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
532ac7d7 787 }
54a0048b 788
532ac7d7
XL
789 let fn_ptr = match (llfn, instance) {
790 (Some(llfn), _) => llfn,
e74abb32 791 (None, Some(instance)) => bx.get_fn_addr(instance),
532ac7d7
XL
792 _ => span_bug!(span, "no llfn for call"),
793 };
54a0048b 794
e74abb32
XL
795 if let Some((_, target)) = destination.as_ref() {
796 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
797 }
60c5eb7d 798 helper.do_call(self, &mut bx, fn_abi, fn_ptr, &llargs,
532ac7d7
XL
799 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
800 cleanup);
801 }
802}
ff7c6d11 803
dc9dc135 804impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
532ac7d7
XL
805 pub fn codegen_block(
806 &mut self,
807 bb: mir::BasicBlock,
808 ) {
809 let mut bx = self.build_block(bb);
60c5eb7d
XL
810 let mir = self.mir;
811 let data = &mir[bb];
ff7c6d11 812
532ac7d7 813 debug!("codegen_block({:?}={:?})", bb, data);
ff7c6d11 814
532ac7d7
XL
815 for statement in &data.statements {
816 bx = self.codegen_statement(bx, statement);
817 }
cc61c64b 818
532ac7d7
XL
819 self.codegen_terminator(bx, bb, data.terminator());
820 }
cc61c64b 821
532ac7d7
XL
822 fn codegen_terminator(
823 &mut self,
824 mut bx: Bx,
825 bb: mir::BasicBlock,
60c5eb7d 826 terminator: &'tcx mir::Terminator<'tcx>
532ac7d7
XL
827 ) {
828 debug!("codegen_terminator: {:?}", terminator);
cc61c64b 829
532ac7d7
XL
830 // Create the cleanup bundle, if needed.
831 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
832 let helper = TerminatorCodegenHelper {
60c5eb7d 833 bb, terminator, funclet_bb
532ac7d7 834 };
cc61c64b 835
532ac7d7
XL
836 self.set_debug_loc(&mut bx, terminator.source_info);
837 match terminator.kind {
838 mir::TerminatorKind::Resume => {
839 self.codegen_resume_terminator(helper, bx)
840 }
ff7c6d11 841
532ac7d7
XL
842 mir::TerminatorKind::Abort => {
843 bx.abort();
60c5eb7d
XL
844 // `abort` does not terminate the block, so we still need to generate
845 // an `unreachable` terminator after it.
532ac7d7
XL
846 bx.unreachable();
847 }
a1dfa0c6 848
532ac7d7 849 mir::TerminatorKind::Goto { target } => {
e74abb32 850 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
532ac7d7
XL
851 helper.funclet_br(self, &mut bx, target);
852 }
ff7c6d11 853
532ac7d7
XL
854 mir::TerminatorKind::SwitchInt {
855 ref discr, switch_ty, ref values, ref targets
856 } => {
857 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
858 values, targets);
859 }
ff7c6d11 860
532ac7d7
XL
861 mir::TerminatorKind::Return => {
862 self.codegen_return_terminator(bx);
863 }
ff7c6d11 864
532ac7d7
XL
865 mir::TerminatorKind::Unreachable => {
866 bx.unreachable();
867 }
54a0048b 868
532ac7d7
XL
869 mir::TerminatorKind::Drop { ref location, target, unwind } => {
870 self.codegen_drop_terminator(helper, bx, location, target, unwind);
871 }
872
873 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
874 self.codegen_assert_terminator(helper, bx, terminator, cond,
875 expected, msg, target, cleanup);
876 }
877
878 mir::TerminatorKind::DropAndReplace { .. } => {
879 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
880 }
881
882 mir::TerminatorKind::Call {
883 ref func,
884 ref args,
885 ref destination,
886 cleanup,
887 from_hir_call: _
888 } => {
889 self.codegen_call_terminator(helper, bx, terminator, func,
890 args, destination, cleanup);
54a0048b 891 }
ea8adc8c 892 mir::TerminatorKind::GeneratorDrop |
94b46f34 893 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
2c00a5a8 894 mir::TerminatorKind::FalseEdges { .. } |
94b46f34 895 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
54a0048b
SL
896 }
897 }
898
a1dfa0c6
XL
899 fn codegen_argument(
900 &mut self,
901 bx: &mut Bx,
902 op: OperandRef<'tcx, Bx::Value>,
903 llargs: &mut Vec<Bx::Value>,
60c5eb7d 904 arg: &ArgAbi<'tcx, Ty<'tcx>>
a1dfa0c6 905 ) {
54a0048b
SL
906 // Fill padding with undef value, where applicable.
907 if let Some(ty) = arg.pad {
a1dfa0c6 908 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
54a0048b
SL
909 }
910
911 if arg.is_ignore() {
912 return;
913 }
914
ff7c6d11
XL
915 if let PassMode::Pair(..) = arg.mode {
916 match op.val {
917 Pair(a, b) => {
918 llargs.push(a);
919 llargs.push(b);
920 return;
921 }
b7449926
XL
922 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
923 }
924 } else if arg.is_unsized_indirect() {
925 match op.val {
926 Ref(a, Some(b), _) => {
927 llargs.push(a);
928 llargs.push(b);
929 return;
930 }
931 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
ff7c6d11
XL
932 }
933 }
934
54a0048b 935 // Force by-ref if we have to load through a cast pointer.
32a655c1 936 let (mut llval, align, by_ref) = match op.val {
3157f602 937 Immediate(_) | Pair(..) => {
ff7c6d11 938 match arg.mode {
b7449926 939 PassMode::Indirect(..) | PassMode::Cast(_) => {
e1599b0c 940 let scratch = PlaceRef::alloca(bx, arg.layout);
2c00a5a8 941 op.val.store(bx, scratch);
ff7c6d11
XL
942 (scratch.llval, scratch.align, true)
943 }
944 _ => {
a1dfa0c6 945 (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
ff7c6d11 946 }
3157f602 947 }
54a0048b 948 }
b7449926 949 Ref(llval, _, align) => {
a1dfa0c6 950 if arg.is_indirect() && align < arg.layout.align.abi {
ff7c6d11
XL
951 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
952 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
953 // have scary latent bugs around.
954
e1599b0c 955 let scratch = PlaceRef::alloca(bx, arg.layout);
a1dfa0c6
XL
956 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
957 op.layout, MemFlags::empty());
ff7c6d11
XL
958 (scratch.llval, scratch.align, true)
959 } else {
960 (llval, align, true)
961 }
32a655c1 962 }
54a0048b
SL
963 };
964
965 if by_ref && !arg.is_indirect() {
966 // Have to load the argument, maybe while casting it.
ff7c6d11 967 if let PassMode::Cast(ty) = arg.mode {
a1dfa0c6
XL
968 let addr = bx.pointercast(llval, bx.type_ptr_to(
969 bx.cast_backend_type(&ty))
970 );
971 llval = bx.load(addr, align.min(arg.layout.align.abi));
54a0048b 972 } else {
ff7c6d11
XL
973 // We can't use `PlaceRef::load` here because the argument
974 // may have a type we don't treat as immediate, but the ABI
975 // used for this call is passing it by-value. In that case,
976 // the load would just produce `OperandValue::Ref` instead
977 // of the `OperandValue::Immediate` we need for the call.
2c00a5a8 978 llval = bx.load(llval, align);
ff7c6d11
XL
979 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
980 if scalar.is_bool() {
2c00a5a8 981 bx.range_metadata(llval, 0..2);
ff7c6d11
XL
982 }
983 }
dc9dc135 984 // We store bools as `i8` so we need to truncate to `i1`.
2c00a5a8 985 llval = base::to_immediate(bx, llval, arg.layout);
54a0048b
SL
986 }
987 }
988
989 llargs.push(llval);
990 }
991
a1dfa0c6
XL
992 fn codegen_arguments_untupled(
993 &mut self,
994 bx: &mut Bx,
995 operand: &mir::Operand<'tcx>,
996 llargs: &mut Vec<Bx::Value>,
60c5eb7d 997 args: &[ArgAbi<'tcx, Ty<'tcx>>]
a1dfa0c6 998 ) {
94b46f34 999 let tuple = self.codegen_operand(bx, operand);
54a0048b 1000
a7813a04 1001 // Handle both by-ref and immediate tuples.
b7449926 1002 if let Ref(llval, None, align) = tuple.val {
e1599b0c 1003 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
ff7c6d11 1004 for i in 0..tuple.layout.fields.count() {
2c00a5a8 1005 let field_ptr = tuple_ptr.project_field(bx, i);
a1dfa0c6
XL
1006 let field = bx.load_operand(field_ptr);
1007 self.codegen_argument(bx, field, llargs, &args[i]);
3157f602 1008 }
b7449926
XL
1009 } else if let Ref(_, Some(_), _) = tuple.val {
1010 bug!("closure arguments must be sized")
ff7c6d11
XL
1011 } else {
1012 // If the tuple is immediate, the elements are as well.
1013 for i in 0..tuple.layout.fields.count() {
2c00a5a8 1014 let op = tuple.extract_field(bx, i);
94b46f34 1015 self.codegen_argument(bx, op, llargs, &args[i]);
a7813a04 1016 }
54a0048b
SL
1017 }
1018 }
1019
e74abb32
XL
1020 fn get_caller_location(
1021 &mut self,
1022 bx: &mut Bx,
1023 span: Span,
1024 ) -> OperandRef<'tcx, Bx::Value> {
60c5eb7d
XL
1025 self.caller_location.unwrap_or_else(|| {
1026 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1027 let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1028 let const_loc = bx.tcx().const_caller_location((
1029 Symbol::intern(&caller.file.name.to_string()),
1030 caller.line as u32,
1031 caller.col_display as u32 + 1,
1032 ));
1033 OperandRef::from_const(bx, const_loc)
1034 })
e74abb32
XL
1035 }
1036
a1dfa0c6
XL
1037 fn get_personality_slot(
1038 &mut self,
1039 bx: &mut Bx
1040 ) -> PlaceRef<'tcx, Bx::Value> {
1041 let cx = bx.cx();
ff7c6d11 1042 if let Some(slot) = self.personality_slot {
54a0048b
SL
1043 slot
1044 } else {
a1dfa0c6
XL
1045 let layout = cx.layout_of(cx.tcx().intern_tup(&[
1046 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
1047 cx.tcx().types.i32
0531ce1d 1048 ]));
e1599b0c 1049 let slot = PlaceRef::alloca(bx, layout);
ff7c6d11 1050 self.personality_slot = Some(slot);
32a655c1 1051 slot
54a0048b
SL
1052 }
1053 }
1054
9fa01778 1055 /// Returns the landing-pad wrapper around the given basic block.
54a0048b
SL
1056 ///
1057 /// No-op in MSVC SEH scheme.
a1dfa0c6
XL
1058 fn landing_pad_to(
1059 &mut self,
1060 target_bb: mir::BasicBlock
1061 ) -> Bx::BasicBlock {
3157f602
XL
1062 if let Some(block) = self.landing_pads[target_bb] {
1063 return block;
1064 }
1065
cc61c64b
XL
1066 let block = self.blocks[target_bb];
1067 let landing_pad = self.landing_pad_uncached(block);
1068 self.landing_pads[target_bb] = Some(landing_pad);
1069 landing_pad
1070 }
1071
a1dfa0c6
XL
1072 fn landing_pad_uncached(
1073 &mut self,
60c5eb7d 1074 target_bb: Bx::BasicBlock,
a1dfa0c6 1075 ) -> Bx::BasicBlock {
2c00a5a8 1076 if base::wants_msvc_seh(self.cx.sess()) {
7cac9316 1077 span_bug!(self.mir.span, "landing pad was not inserted?")
54a0048b 1078 }
3157f602 1079
a1dfa0c6 1080 let mut bx = self.new_block("cleanup");
3157f602 1081
2c00a5a8 1082 let llpersonality = self.cx.eh_personality();
ff7c6d11 1083 let llretty = self.landing_pad_type();
2c00a5a8
XL
1084 let lp = bx.landing_pad(llretty, llpersonality, 1);
1085 bx.set_cleanup(lp);
ff7c6d11 1086
a1dfa0c6
XL
1087 let slot = self.get_personality_slot(&mut bx);
1088 slot.storage_live(&mut bx);
1089 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
ff7c6d11 1090
2c00a5a8
XL
1091 bx.br(target_bb);
1092 bx.llbb()
54a0048b
SL
1093 }
1094
a1dfa0c6 1095 fn landing_pad_type(&self) -> Bx::Type {
2c00a5a8 1096 let cx = self.cx;
a1dfa0c6 1097 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
ff7c6d11
XL
1098 }
1099
a1dfa0c6
XL
1100 fn unreachable_block(
1101 &mut self
1102 ) -> Bx::BasicBlock {
54a0048b 1103 self.unreachable_block.unwrap_or_else(|| {
a1dfa0c6
XL
1104 let mut bx = self.new_block("unreachable");
1105 bx.unreachable();
1106 self.unreachable_block = Some(bx.llbb());
1107 bx.llbb()
54a0048b
SL
1108 })
1109 }
1110
a1dfa0c6
XL
1111 pub fn new_block(&self, name: &str) -> Bx {
1112 Bx::new_block(self.cx, self.llfn, name)
32a655c1
SL
1113 }
1114
a1dfa0c6
XL
1115 pub fn build_block(
1116 &self,
1117 bb: mir::BasicBlock
1118 ) -> Bx {
1119 let mut bx = Bx::with_cx(self.cx);
2c00a5a8
XL
1120 bx.position_at_end(self.blocks[bb]);
1121 bx
54a0048b
SL
1122 }
1123
a1dfa0c6
XL
1124 fn make_return_dest(
1125 &mut self,
1126 bx: &mut Bx,
1127 dest: &mir::Place<'tcx>,
60c5eb7d 1128 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
a1dfa0c6
XL
1129 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1130 ) -> ReturnDest<'tcx, Bx::Value> {
dc9dc135 1131 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
ff7c6d11 1132 if fn_ret.is_ignore() {
54a0048b
SL
1133 return ReturnDest::Nothing;
1134 }
e74abb32 1135 let dest = if let Some(index) = dest.as_local() {
3157f602 1136 match self.locals[index] {
ff7c6d11 1137 LocalRef::Place(dest) => dest,
b7449926 1138 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
3157f602 1139 LocalRef::Operand(None) => {
dc9dc135
XL
1140 // Handle temporary places, specifically `Operand` ones, as
1141 // they don't have `alloca`s.
ff7c6d11 1142 return if fn_ret.is_indirect() {
3157f602
XL
1143 // Odd, but possible, case, we have an operand temporary,
1144 // but the calling convention has an indirect return.
e1599b0c 1145 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2c00a5a8 1146 tmp.storage_live(bx);
32a655c1 1147 llargs.push(tmp.llval);
ff7c6d11 1148 ReturnDest::IndirectOperand(tmp, index)
3157f602
XL
1149 } else if is_intrinsic {
1150 // Currently, intrinsics always need a location to store
dc9dc135
XL
1151 // the result, so we create a temporary `alloca` for the
1152 // result.
e1599b0c 1153 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2c00a5a8 1154 tmp.storage_live(bx);
ff7c6d11 1155 ReturnDest::IndirectOperand(tmp, index)
3157f602
XL
1156 } else {
1157 ReturnDest::DirectOperand(index)
1158 };
1159 }
1160 LocalRef::Operand(Some(_)) => {
ff7c6d11 1161 bug!("place local already assigned to");
54a0048b
SL
1162 }
1163 }
3157f602 1164 } else {
416331ca
XL
1165 self.codegen_place(bx, &mir::PlaceRef {
1166 base: &dest.base,
1167 projection: &dest.projection,
1168 })
54a0048b 1169 };
ff7c6d11 1170 if fn_ret.is_indirect() {
a1dfa0c6 1171 if dest.align < dest.layout.align.abi {
ff7c6d11
XL
1172 // Currently, MIR code generation does not create calls
1173 // that store directly to fields of packed structs (in
dc9dc135 1174 // fact, the calls it creates write only to temps).
ff7c6d11
XL
1175 //
1176 // If someone changes that, please update this code path
1177 // to create a temporary.
1178 span_bug!(self.mir.span, "can't directly store to unaligned value");
8bb4bdeb 1179 }
ff7c6d11
XL
1180 llargs.push(dest.llval);
1181 ReturnDest::Nothing
54a0048b 1182 } else {
ff7c6d11 1183 ReturnDest::Store(dest)
54a0048b
SL
1184 }
1185 }
1186
a1dfa0c6
XL
1187 fn codegen_transmute(
1188 &mut self,
1189 bx: &mut Bx,
1190 src: &mir::Operand<'tcx>,
1191 dst: &mir::Place<'tcx>
1192 ) {
e74abb32 1193 if let Some(index) = dst.as_local() {
32a655c1 1194 match self.locals[index] {
94b46f34 1195 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
b7449926 1196 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
32a655c1 1197 LocalRef::Operand(None) => {
416331ca 1198 let dst_layout = bx.layout_of(self.monomorphized_place_ty(&dst.as_ref()));
ff7c6d11 1199 assert!(!dst_layout.ty.has_erasable_regions());
e1599b0c 1200 let place = PlaceRef::alloca(bx, dst_layout);
2c00a5a8 1201 place.storage_live(bx);
94b46f34 1202 self.codegen_transmute_into(bx, src, place);
a1dfa0c6 1203 let op = bx.load_operand(place);
2c00a5a8 1204 place.storage_dead(bx);
32a655c1
SL
1205 self.locals[index] = LocalRef::Operand(Some(op));
1206 }
ff7c6d11
XL
1207 LocalRef::Operand(Some(op)) => {
1208 assert!(op.layout.is_zst(),
32a655c1
SL
1209 "assigning to initialized SSAtemp");
1210 }
1211 }
1212 } else {
416331ca 1213 let dst = self.codegen_place(bx, &dst.as_ref());
94b46f34 1214 self.codegen_transmute_into(bx, src, dst);
32a655c1
SL
1215 }
1216 }
1217
a1dfa0c6
XL
1218 fn codegen_transmute_into(
1219 &mut self,
1220 bx: &mut Bx,
1221 src: &mir::Operand<'tcx>,
1222 dst: PlaceRef<'tcx, Bx::Value>
1223 ) {
94b46f34 1224 let src = self.codegen_operand(bx, src);
a1dfa0c6
XL
1225 let llty = bx.backend_type(src.layout);
1226 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1227 let align = src.layout.align.abi.min(dst.align);
e1599b0c 1228 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
54a0048b
SL
1229 }
1230
3157f602 1231
54a0048b 1232 // Stores the return value of a function call into it's final location.
a1dfa0c6
XL
1233 fn store_return(
1234 &mut self,
1235 bx: &mut Bx,
1236 dest: ReturnDest<'tcx, Bx::Value>,
60c5eb7d 1237 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
a1dfa0c6
XL
1238 llval: Bx::Value
1239 ) {
54a0048b
SL
1240 use self::ReturnDest::*;
1241
1242 match dest {
1243 Nothing => (),
60c5eb7d 1244 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
3157f602 1245 IndirectOperand(tmp, index) => {
a1dfa0c6 1246 let op = bx.load_operand(tmp);
2c00a5a8 1247 tmp.storage_dead(bx);
3157f602 1248 self.locals[index] = LocalRef::Operand(Some(op));
54a0048b 1249 }
3157f602
XL
1250 DirectOperand(index) => {
1251 // If there is a cast, we have to store and reload.
60c5eb7d
XL
1252 let op = if let PassMode::Cast(_) = ret_abi.mode {
1253 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2c00a5a8 1254 tmp.storage_live(bx);
60c5eb7d 1255 bx.store_arg(&ret_abi, llval, tmp);
a1dfa0c6 1256 let op = bx.load_operand(tmp);
2c00a5a8 1257 tmp.storage_dead(bx);
ff7c6d11 1258 op
54a0048b 1259 } else {
60c5eb7d 1260 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
54a0048b 1261 };
3157f602 1262 self.locals[index] = LocalRef::Operand(Some(op));
54a0048b
SL
1263 }
1264 }
1265 }
1266}
1267
a1dfa0c6 1268enum ReturnDest<'tcx, V> {
dc9dc135 1269 // Do nothing; the return value is indirect or ignored.
54a0048b 1270 Nothing,
dc9dc135 1271 // Store the return value to the pointer.
a1dfa0c6 1272 Store(PlaceRef<'tcx, V>),
dc9dc135 1273 // Store an indirect return value to an operand local place.
a1dfa0c6 1274 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
dc9dc135 1275 // Store a direct return value to an operand local place.
3157f602 1276 DirectOperand(mir::Local)
54a0048b 1277}