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