]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/block.rs
737b25a1231bb853639782672db2a44ecae5e1c3
[rust.git] / src / librustc_codegen_llvm / mir / block.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm::{self, BasicBlock};
12 use rustc::middle::lang_items;
13 use rustc::ty::{self, Ty, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
15 use rustc::mir;
16 use rustc::mir::interpret::EvalErrorKind;
17 use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
18 use base;
19 use callee;
20 use builder::{Builder, MemFlags};
21 use common::{self, IntPredicate};
22 use context::CodegenCx;
23 use consts;
24 use meth;
25 use monomorphize;
26 use type_of::LayoutLlvmExt;
27 use type_::Type;
28 use value::Value;
29
30 use interfaces::{BuilderMethods, CommonMethods};
31
32 use syntax::symbol::Symbol;
33 use syntax_pos::Pos;
34
35 use super::{FunctionCx, LocalRef};
36 use super::place::PlaceRef;
37 use super::operand::OperandRef;
38 use super::operand::OperandValue::{Pair, Ref, Immediate};
39
40 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
41     pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
42         let mut bx = self.build_block(bb);
43         let data = &self.mir[bb];
44
45         debug!("codegen_block({:?}={:?})", bb, data);
46
47         for statement in &data.statements {
48             bx = self.codegen_statement(bx, statement);
49         }
50
51         self.codegen_terminator(bx, bb, data.terminator());
52     }
53
54     fn codegen_terminator(&mut self,
55                           mut bx: Builder<'a, 'll, 'tcx>,
56                           bb: mir::BasicBlock,
57                           terminator: &mir::Terminator<'tcx>)
58     {
59         debug!("codegen_terminator: {:?}", terminator);
60
61         // Create the cleanup bundle, if needed.
62         let tcx = bx.tcx();
63         let span = terminator.source_info.span;
64         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
65         let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
66
67         let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
68         let cleanup_bundle = funclet.map(|l| l.bundle());
69
70         let lltarget = |this: &mut Self, target: mir::BasicBlock| {
71             let lltarget = this.blocks[target];
72             let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
73             match (funclet_bb, target_funclet) {
74                 (None, None) => (lltarget, false),
75                 (Some(f), Some(t_f))
76                     if f == t_f || !base::wants_msvc_seh(tcx.sess)
77                     => (lltarget, false),
78                 (None, Some(_)) => {
79                     // jump *into* cleanup - need a landing pad if GNU
80                     (this.landing_pad_to(target), false)
81                 }
82                 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
83                 (Some(_), Some(_)) => {
84                     (this.landing_pad_to(target), true)
85                 }
86             }
87         };
88
89         let llblock = |this: &mut Self, target: mir::BasicBlock| {
90             let (lltarget, is_cleanupret) = lltarget(this, target);
91             if is_cleanupret {
92                 // MSVC cross-funclet jump - need a trampoline
93
94                 debug!("llblock: creating cleanup trampoline for {:?}", target);
95                 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
96                 let trampoline = this.new_block(name);
97                 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
98                 trampoline.llbb()
99             } else {
100                 lltarget
101             }
102         };
103
104         let funclet_br =
105             |this: &mut Self, bx: Builder<'_, 'll, '_>, target: mir::BasicBlock| {
106                 let (lltarget, is_cleanupret) = lltarget(this, target);
107                 if is_cleanupret {
108                     // micro-optimization: generate a `ret` rather than a jump
109                     // to a trampoline.
110                     bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
111                 } else {
112                     bx.br(lltarget);
113                 }
114             };
115
116         let do_call = |
117             this: &mut Self,
118             bx: Builder<'a, 'll, 'tcx>,
119             fn_ty: FnType<'tcx, Ty<'tcx>>,
120             fn_ptr: &'ll Value,
121             llargs: &[&'ll Value],
122             destination: Option<(ReturnDest<'tcx, &'ll Value>, mir::BasicBlock)>,
123             cleanup: Option<mir::BasicBlock>
124         | {
125             if let Some(cleanup) = cleanup {
126                 let ret_bx = if let Some((_, target)) = destination {
127                     this.blocks[target]
128                 } else {
129                     this.unreachable_block()
130                 };
131                 let invokeret = bx.invoke(fn_ptr,
132                                           &llargs,
133                                           ret_bx,
134                                           llblock(this, cleanup),
135                                           cleanup_bundle);
136                 fn_ty.apply_attrs_callsite(&bx, invokeret);
137
138                 if let Some((ret_dest, target)) = destination {
139                     let ret_bx = this.build_block(target);
140                     this.set_debug_loc(&ret_bx, terminator.source_info);
141                     this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
142                 }
143             } else {
144                 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
145                 fn_ty.apply_attrs_callsite(&bx, llret);
146                 if this.mir[bb].is_cleanup {
147                     // Cleanup is always the cold path. Don't inline
148                     // drop glue. Also, when there is a deeply-nested
149                     // struct, there are "symmetry" issues that cause
150                     // exponential inlining - see issue #41696.
151                     llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
152                 }
153
154                 if let Some((ret_dest, target)) = destination {
155                     this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
156                     funclet_br(this, bx, target);
157                 } else {
158                     bx.unreachable();
159                 }
160             }
161         };
162
163         self.set_debug_loc(&bx, terminator.source_info);
164         match terminator.kind {
165             mir::TerminatorKind::Resume => {
166                 if let Some(cleanup_pad) = cleanup_pad {
167                     bx.cleanup_ret(cleanup_pad, None);
168                 } else {
169                     let slot = self.get_personality_slot(&bx);
170                     let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
171                     let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
172                     slot.storage_dead(&bx);
173
174                     if !bx.sess().target.target.options.custom_unwind_resume {
175                         let mut lp = bx.cx().c_undef(self.landing_pad_type());
176                         lp = bx.insert_value(lp, lp0, 0);
177                         lp = bx.insert_value(lp, lp1, 1);
178                         bx.resume(lp);
179                     } else {
180                         bx.call(bx.cx().eh_unwind_resume(), &[lp0], cleanup_bundle);
181                         bx.unreachable();
182                     }
183                 }
184             }
185
186             mir::TerminatorKind::Abort => {
187                 // Call core::intrinsics::abort()
188                 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
189                 bx.call(fnname, &[], None);
190                 bx.unreachable();
191             }
192
193             mir::TerminatorKind::Goto { target } => {
194                 funclet_br(self, bx, target);
195             }
196
197             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
198                 let discr = self.codegen_operand(&bx, discr);
199                 if targets.len() == 2 {
200                     // If there are two targets, emit br instead of switch
201                     let lltrue = llblock(self, targets[0]);
202                     let llfalse = llblock(self, targets[1]);
203                     if switch_ty == bx.tcx().types.bool {
204                         // Don't generate trivial icmps when switching on bool
205                         if let [0] = values[..] {
206                             bx.cond_br(discr.immediate(), llfalse, lltrue);
207                         } else {
208                             assert_eq!(&values[..], &[1]);
209                             bx.cond_br(discr.immediate(), lltrue, llfalse);
210                         }
211                     } else {
212                         let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
213                         let llval = bx.cx().c_uint_big(switch_llty, values[0]);
214                         let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
215                         bx.cond_br(cmp, lltrue, llfalse);
216                     }
217                 } else {
218                     let (otherwise, targets) = targets.split_last().unwrap();
219                     let switch = bx.switch(discr.immediate(),
220                                            llblock(self, *otherwise),
221                                            values.len());
222                     let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
223                     for (&value, target) in values.iter().zip(targets) {
224                         let llval =bx.cx().c_uint_big(switch_llty, value);
225                         let llbb = llblock(self, *target);
226                         bx.add_case(switch, llval, llbb)
227                     }
228                 }
229             }
230
231             mir::TerminatorKind::Return => {
232                 let llval = match self.fn_ty.ret.mode {
233                     PassMode::Ignore | PassMode::Indirect(..) => {
234                         bx.ret_void();
235                         return;
236                     }
237
238                     PassMode::Direct(_) | PassMode::Pair(..) => {
239                         let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
240                         if let Ref(llval, _, align) = op.val {
241                             bx.load(llval, align)
242                         } else {
243                             op.immediate_or_packed_pair(&bx)
244                         }
245                     }
246
247                     PassMode::Cast(cast_ty) => {
248                         let op = match self.locals[mir::RETURN_PLACE] {
249                             LocalRef::Operand(Some(op)) => op,
250                             LocalRef::Operand(None) => bug!("use of return before def"),
251                             LocalRef::Place(cg_place) => {
252                                 OperandRef {
253                                     val: Ref(cg_place.llval, None, cg_place.align),
254                                     layout: cg_place.layout
255                                 }
256                             }
257                             LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
258                         };
259                         let llslot = match op.val {
260                             Immediate(_) | Pair(..) => {
261                                 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
262                                 op.val.store(&bx, scratch);
263                                 scratch.llval
264                             }
265                             Ref(llval, _, align) => {
266                                 assert_eq!(align.abi(), op.layout.align.abi(),
267                                            "return place is unaligned!");
268                                 llval
269                             }
270                         };
271                         bx.load(
272                             bx.pointercast(llslot, cast_ty.llvm_type(bx.cx()).ptr_to()),
273                             self.fn_ty.ret.layout.align)
274                     }
275                 };
276                 bx.ret(llval);
277             }
278
279             mir::TerminatorKind::Unreachable => {
280                 bx.unreachable();
281             }
282
283             mir::TerminatorKind::Drop { ref location, target, unwind } => {
284                 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
285                 let ty = self.monomorphize(&ty);
286                 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx().tcx, ty);
287
288                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
289                     // we don't actually need to drop anything.
290                     funclet_br(self, bx, target);
291                     return
292                 }
293
294                 let place = self.codegen_place(&bx, location);
295                 let (args1, args2);
296                 let mut args = if let Some(llextra) = place.llextra {
297                     args2 = [place.llval, llextra];
298                     &args2[..]
299                 } else {
300                     args1 = [place.llval];
301                     &args1[..]
302                 };
303                 let (drop_fn, fn_ty) = match ty.sty {
304                     ty::Dynamic(..) => {
305                         let sig = drop_fn.fn_sig(bx.tcx());
306                         let sig = bx.tcx().normalize_erasing_late_bound_regions(
307                             ty::ParamEnv::reveal_all(),
308                             &sig,
309                         );
310                         let fn_ty = FnType::new_vtable(bx.cx(), sig, &[]);
311                         let vtable = args[1];
312                         args = &args[..1];
313                         (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
314                     }
315                     _ => {
316                         (callee::get_fn(bx.cx(), drop_fn),
317                          FnType::of_instance(bx.cx(), &drop_fn))
318                     }
319                 };
320                 do_call(self, bx, fn_ty, drop_fn, args,
321                         Some((ReturnDest::Nothing, target)),
322                         unwind);
323             }
324
325             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
326                 let cond = self.codegen_operand(&bx, cond).immediate();
327                 let mut const_cond = CodegenCx::const_to_opt_u128(cond, false).map(|c| c == 1);
328
329                 // This case can currently arise only from functions marked
330                 // with #[rustc_inherit_overflow_checks] and inlined from
331                 // another crate (mostly core::num generic/#[inline] fns),
332                 // while the current crate doesn't use overflow checks.
333                 // NOTE: Unlike binops, negation doesn't have its own
334                 // checked operation, just a comparison with the minimum
335                 // value, so we have to check for the assert message.
336                 if !bx.cx().check_overflow {
337                     if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
338                         const_cond = Some(expected);
339                     }
340                 }
341
342                 // Don't codegen the panic block if success if known.
343                 if const_cond == Some(expected) {
344                     funclet_br(self, bx, target);
345                     return;
346                 }
347
348                 // Pass the condition through llvm.expect for branch hinting.
349                 let expect = bx.cx().get_intrinsic(&"llvm.expect.i1");
350                 let cond = bx.call(expect, &[cond, CodegenCx::c_bool(bx.cx(), expected)], None);
351
352                 // Create the failure block and the conditional branch to it.
353                 let lltarget = llblock(self, target);
354                 let panic_block = self.new_block("panic");
355                 if expected {
356                     bx.cond_br(cond, lltarget, panic_block.llbb());
357                 } else {
358                     bx.cond_br(cond, panic_block.llbb(), lltarget);
359                 }
360
361                 // After this point, bx is the block for the call to panic.
362                 bx = panic_block;
363                 self.set_debug_loc(&bx, terminator.source_info);
364
365                 // Get the location information.
366                 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
367                 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
368                 let filename = CodegenCx::c_str_slice(bx.cx(), filename);
369                 let line = CodegenCx::c_u32(bx.cx(), loc.line as u32);
370                 let col = CodegenCx::c_u32(bx.cx(), loc.col.to_usize() as u32 + 1);
371                 let align = tcx.data_layout.aggregate_align
372                     .max(tcx.data_layout.i32_align)
373                     .max(tcx.data_layout.pointer_align);
374
375                 // Put together the arguments to the panic entry point.
376                 let (lang_item, args) = match *msg {
377                     EvalErrorKind::BoundsCheck { ref len, ref index } => {
378                         let len = self.codegen_operand(&mut bx, len).immediate();
379                         let index = self.codegen_operand(&mut bx, index).immediate();
380
381                         let file_line_col = CodegenCx::c_struct(bx.cx(),
382                              &[filename, line, col], false);
383                         let file_line_col = consts::addr_of(bx.cx(),
384                                                             file_line_col,
385                                                             align,
386                                                             Some("panic_bounds_check_loc"));
387                         (lang_items::PanicBoundsCheckFnLangItem,
388                          vec![file_line_col, index, len])
389                     }
390                     _ => {
391                         let str = msg.description();
392                         let msg_str = Symbol::intern(str).as_str();
393                         let msg_str = CodegenCx::c_str_slice(bx.cx(), msg_str);
394                         let msg_file_line_col = CodegenCx::c_struct(
395                             bx.cx(),
396                             &[msg_str, filename, line, col],
397                             false
398                         );
399                         let msg_file_line_col = consts::addr_of(bx.cx(),
400                                                                 msg_file_line_col,
401                                                                 align,
402                                                                 Some("panic_loc"));
403                         (lang_items::PanicFnLangItem,
404                          vec![msg_file_line_col])
405                     }
406                 };
407
408                 // Obtain the panic entry point.
409                 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
410                 let instance = ty::Instance::mono(bx.tcx(), def_id);
411                 let fn_ty = FnType::of_instance(bx.cx(), &instance);
412                 let llfn = callee::get_fn(bx.cx(), instance);
413
414                 // Codegen the actual panic invoke/call.
415                 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
416             }
417
418             mir::TerminatorKind::DropAndReplace { .. } => {
419                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
420             }
421
422             mir::TerminatorKind::Call {
423                 ref func,
424                 ref args,
425                 ref destination,
426                 cleanup,
427                 from_hir_call: _
428             } => {
429                 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
430                 let callee = self.codegen_operand(&bx, func);
431
432                 let (instance, mut llfn) = match callee.layout.ty.sty {
433                     ty::FnDef(def_id, substs) => {
434                         (Some(ty::Instance::resolve(bx.cx().tcx,
435                                                     ty::ParamEnv::reveal_all(),
436                                                     def_id,
437                                                     substs).unwrap()),
438                          None)
439                     }
440                     ty::FnPtr(_) => {
441                         (None, Some(callee.immediate()))
442                     }
443                     _ => bug!("{} is not callable", callee.layout.ty)
444                 };
445                 let def = instance.map(|i| i.def);
446                 let sig = callee.layout.ty.fn_sig(bx.tcx());
447                 let sig = bx.tcx().normalize_erasing_late_bound_regions(
448                     ty::ParamEnv::reveal_all(),
449                     &sig,
450                 );
451                 let abi = sig.abi;
452
453                 // Handle intrinsics old codegen wants Expr's for, ourselves.
454                 let intrinsic = match def {
455                     Some(ty::InstanceDef::Intrinsic(def_id))
456                         => Some(bx.tcx().item_name(def_id).as_str()),
457                     _ => None
458                 };
459                 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
460
461                 if intrinsic == Some("transmute") {
462                     if let Some(destination_ref) = destination.as_ref() {
463                         let &(ref dest, target) = destination_ref;
464                         self.codegen_transmute(&bx, &args[0], dest);
465                         funclet_br(self, bx, target);
466                     } else {
467                         // If we are trying to transmute to an uninhabited type,
468                         // it is likely there is no allotted destination. In fact,
469                         // transmuting to an uninhabited type is UB, which means
470                         // we can do what we like. Here, we declare that transmuting
471                         // into an uninhabited type is impossible, so anything following
472                         // it must be unreachable.
473                         assert_eq!(bx.cx().layout_of(sig.output()).abi, layout::Abi::Uninhabited);
474                         bx.unreachable();
475                     }
476                     return;
477                 }
478
479                 let extra_args = &args[sig.inputs().len()..];
480                 let extra_args = extra_args.iter().map(|op_arg| {
481                     let op_ty = op_arg.ty(self.mir, bx.tcx());
482                     self.monomorphize(&op_ty)
483                 }).collect::<Vec<_>>();
484
485                 let fn_ty = match def {
486                     Some(ty::InstanceDef::Virtual(..)) => {
487                         FnType::new_vtable(bx.cx(), sig, &extra_args)
488                     }
489                     Some(ty::InstanceDef::DropGlue(_, None)) => {
490                         // empty drop glue - a nop.
491                         let &(_, target) = destination.as_ref().unwrap();
492                         funclet_br(self, bx, target);
493                         return;
494                     }
495                     _ => FnType::new(bx.cx(), sig, &extra_args)
496                 };
497
498                 // emit a panic instead of instantiating an uninhabited type
499                 if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
500                     fn_ty.ret.layout.abi.is_uninhabited()
501                 {
502                     let loc = bx.sess().source_map().lookup_char_pos(span.lo());
503                     let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
504                     let filename = bx.cx.c_str_slice(filename);
505                     let line = bx.cx.c_u32(loc.line as u32);
506                     let col = bx.cx.c_u32(loc.col.to_usize() as u32 + 1);
507                     let align = tcx.data_layout.aggregate_align
508                         .max(tcx.data_layout.i32_align)
509                         .max(tcx.data_layout.pointer_align);
510
511                     let str = format!(
512                         "Attempted to instantiate uninhabited type {} using mem::{}",
513                         sig.output(),
514                         if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
515                     );
516                     let msg_str = Symbol::intern(&str).as_str();
517                     let msg_str = bx.cx.c_str_slice(msg_str);
518                     let msg_file_line_col = bx.cx.c_struct(
519                         &[msg_str, filename, line, col],
520                         false,
521                     );
522                     let msg_file_line_col = consts::addr_of(bx.cx,
523                                                             msg_file_line_col,
524                                                             align,
525                                                             Some("panic_loc"));
526
527                     // Obtain the panic entry point.
528                     let def_id =
529                         common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
530                     let instance = ty::Instance::mono(bx.tcx(), def_id);
531                     let fn_ty = FnType::of_instance(bx.cx, &instance);
532                     let llfn = callee::get_fn(bx.cx, instance);
533
534                     // Codegen the actual panic invoke/call.
535                     do_call(
536                         self,
537                         bx,
538                         fn_ty,
539                         llfn,
540                         &[msg_file_line_col],
541                         destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
542                         cleanup,
543                     );
544                     return;
545                 }
546
547                 // The arguments we'll be passing. Plus one to account for outptr, if used.
548                 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
549                 let mut llargs = Vec::with_capacity(arg_count);
550
551                 // Prepare the return value destination
552                 let ret_dest = if let Some((ref dest, _)) = *destination {
553                     let is_intrinsic = intrinsic.is_some();
554                     self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
555                                           is_intrinsic)
556                 } else {
557                     ReturnDest::Nothing
558                 };
559
560                 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
561                     use intrinsic::codegen_intrinsic_call;
562
563                     let dest = match ret_dest {
564                         _ if fn_ty.ret.is_indirect() => llargs[0],
565                         ReturnDest::Nothing => {
566                             bx.cx().c_undef(fn_ty.ret.memory_ty(bx.cx()).ptr_to())
567                         }
568                         ReturnDest::IndirectOperand(dst, _) |
569                         ReturnDest::Store(dst) => dst.llval,
570                         ReturnDest::DirectOperand(_) =>
571                             bug!("Cannot use direct operand with an intrinsic call")
572                     };
573
574                     let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
575                         // The indices passed to simd_shuffle* in the
576                         // third argument must be constant. This is
577                         // checked by const-qualification, which also
578                         // promotes any complex rvalues to constants.
579                         if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
580                             match *arg {
581                                 // The shuffle array argument is usually not an explicit constant,
582                                 // but specified directly in the code. This means it gets promoted
583                                 // and we can then extract the value by evaluating the promoted.
584                                 mir::Operand::Copy(mir::Place::Promoted(box(index, ty))) |
585                                 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
586                                     let param_env = ty::ParamEnv::reveal_all();
587                                     let cid = mir::interpret::GlobalId {
588                                         instance: self.instance,
589                                         promoted: Some(index),
590                                     };
591                                     let c = bx.tcx().const_eval(param_env.and(cid));
592                                     let (llval, ty) = self.simd_shuffle_indices(
593                                         &bx,
594                                         terminator.source_info.span,
595                                         ty,
596                                         c,
597                                     );
598                                     return OperandRef {
599                                         val: Immediate(llval),
600                                         layout: bx.cx().layout_of(ty),
601                                     };
602
603                                 },
604                                 mir::Operand::Copy(_) |
605                                 mir::Operand::Move(_) => {
606                                     span_bug!(span, "shuffle indices must be constant");
607                                 }
608                                 mir::Operand::Constant(ref constant) => {
609                                     let c = self.eval_mir_constant(&bx, constant);
610                                     let (llval, ty) = self.simd_shuffle_indices(
611                                         &bx,
612                                         constant.span,
613                                         constant.ty,
614                                         c,
615                                     );
616                                     return OperandRef {
617                                         val: Immediate(llval),
618                                         layout: bx.cx().layout_of(ty)
619                                     };
620                                 }
621                             }
622                         }
623
624                         self.codegen_operand(&bx, arg)
625                     }).collect();
626
627
628                     let callee_ty = instance.as_ref().unwrap().ty(bx.cx().tcx);
629                     codegen_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
630                                            terminator.source_info.span);
631
632                     if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
633                         self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
634                     }
635
636                     if let Some((_, target)) = *destination {
637                         funclet_br(self, bx, target);
638                     } else {
639                         bx.unreachable();
640                     }
641
642                     return;
643                 }
644
645                 // Split the rust-call tupled arguments off.
646                 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
647                     let (tup, args) = args.split_last().unwrap();
648                     (args, Some(tup))
649                 } else {
650                     (&args[..], None)
651                 };
652
653                 'make_args: for (i, arg) in first_args.iter().enumerate() {
654                     let mut op = self.codegen_operand(&bx, arg);
655
656                     if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
657                         if let Pair(..) = op.val {
658                             // In the case of Rc<Self>, we need to explicitly pass a
659                             // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
660                             // that is understood elsewhere in the compiler as a method on
661                             // `dyn Trait`.
662                             // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
663                             // we get a value of a built-in pointer type
664                             'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
665                                             && !op.layout.ty.is_region_ptr()
666                             {
667                                 'iter_fields: for i in 0..op.layout.fields.count() {
668                                     let field = op.extract_field(&bx, i);
669                                     if !field.layout.is_zst() {
670                                         // we found the one non-zero-sized field that is allowed
671                                         // now find *its* non-zero-sized field, or stop if it's a
672                                         // pointer
673                                         op = field;
674                                         continue 'descend_newtypes
675                                     }
676                                 }
677
678                                 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
679                             }
680
681                             // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
682                             // data pointer and vtable. Look up the method in the vtable, and pass
683                             // the data pointer as the first argument
684                             match op.val {
685                                 Pair(data_ptr, meta) => {
686                                     llfn = Some(meth::VirtualIndex::from_index(idx)
687                                         .get_fn(&bx, meta, &fn_ty));
688                                     llargs.push(data_ptr);
689                                     continue 'make_args
690                                 }
691                                 other => bug!("expected a Pair, got {:?}", other)
692                             }
693                         } else if let Ref(data_ptr, Some(meta), _) = op.val {
694                             // by-value dynamic dispatch
695                             llfn = Some(meth::VirtualIndex::from_index(idx)
696                                 .get_fn(&bx, meta, &fn_ty));
697                             llargs.push(data_ptr);
698                             continue;
699                         } else {
700                             span_bug!(span, "can't codegen a virtual call on {:?}", op);
701                         }
702                     }
703
704                     // The callee needs to own the argument memory if we pass it
705                     // by-ref, so make a local copy of non-immediate constants.
706                     match (arg, op.val) {
707                         (&mir::Operand::Copy(_), Ref(_, None, _)) |
708                         (&mir::Operand::Constant(_), Ref(_, None, _)) => {
709                             let tmp = PlaceRef::alloca(&bx, op.layout, "const");
710                             op.val.store(&bx, tmp);
711                             op.val = Ref(tmp.llval, None, tmp.align);
712                         }
713                         _ => {}
714                     }
715
716                     self.codegen_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
717                 }
718                 if let Some(tup) = untuple {
719                     self.codegen_arguments_untupled(&bx, tup, &mut llargs,
720                         &fn_ty.args[first_args.len()..])
721                 }
722
723                 let fn_ptr = match (llfn, instance) {
724                     (Some(llfn), _) => llfn,
725                     (None, Some(instance)) => callee::get_fn(bx.cx(), instance),
726                     _ => span_bug!(span, "no llfn for call"),
727                 };
728
729                 do_call(self, bx, fn_ty, fn_ptr, &llargs,
730                         destination.as_ref().map(|&(_, target)| (ret_dest, target)),
731                         cleanup);
732             }
733             mir::TerminatorKind::GeneratorDrop |
734             mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
735             mir::TerminatorKind::FalseEdges { .. } |
736             mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
737         }
738     }
739
740     fn codegen_argument(&mut self,
741                       bx: &Builder<'a, 'll, 'tcx>,
742                       op: OperandRef<'tcx, &'ll Value>,
743                       llargs: &mut Vec<&'ll Value>,
744                       arg: &ArgType<'tcx, Ty<'tcx>>) {
745         // Fill padding with undef value, where applicable.
746         if let Some(ty) = arg.pad {
747             llargs.push(bx.cx().c_undef(ty.llvm_type(bx.cx())));
748         }
749
750         if arg.is_ignore() {
751             return;
752         }
753
754         if let PassMode::Pair(..) = arg.mode {
755             match op.val {
756                 Pair(a, b) => {
757                     llargs.push(a);
758                     llargs.push(b);
759                     return;
760                 }
761                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
762             }
763         } else if arg.is_unsized_indirect() {
764             match op.val {
765                 Ref(a, Some(b), _) => {
766                     llargs.push(a);
767                     llargs.push(b);
768                     return;
769                 }
770                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
771             }
772         }
773
774         // Force by-ref if we have to load through a cast pointer.
775         let (mut llval, align, by_ref) = match op.val {
776             Immediate(_) | Pair(..) => {
777                 match arg.mode {
778                     PassMode::Indirect(..) | PassMode::Cast(_) => {
779                         let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
780                         op.val.store(bx, scratch);
781                         (scratch.llval, scratch.align, true)
782                     }
783                     _ => {
784                         (op.immediate_or_packed_pair(bx), arg.layout.align, false)
785                     }
786                 }
787             }
788             Ref(llval, _, align) => {
789                 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
790                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
791                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
792                     // have scary latent bugs around.
793
794                     let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
795                     base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
796                                     op.layout, MemFlags::empty());
797                     (scratch.llval, scratch.align, true)
798                 } else {
799                     (llval, align, true)
800                 }
801             }
802         };
803
804         if by_ref && !arg.is_indirect() {
805             // Have to load the argument, maybe while casting it.
806             if let PassMode::Cast(ty) = arg.mode {
807                 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx()).ptr_to()),
808                                 align.min(arg.layout.align));
809             } else {
810                 // We can't use `PlaceRef::load` here because the argument
811                 // may have a type we don't treat as immediate, but the ABI
812                 // used for this call is passing it by-value. In that case,
813                 // the load would just produce `OperandValue::Ref` instead
814                 // of the `OperandValue::Immediate` we need for the call.
815                 llval = bx.load(llval, align);
816                 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
817                     if scalar.is_bool() {
818                         bx.range_metadata(llval, 0..2);
819                     }
820                 }
821                 // We store bools as i8 so we need to truncate to i1.
822                 llval = base::to_immediate(bx, llval, arg.layout);
823             }
824         }
825
826         llargs.push(llval);
827     }
828
829     fn codegen_arguments_untupled(&mut self,
830                                   bx: &Builder<'a, 'll, 'tcx>,
831                                   operand: &mir::Operand<'tcx>,
832                                   llargs: &mut Vec<&'ll Value>,
833                                   args: &[ArgType<'tcx, Ty<'tcx>>]) {
834         let tuple = self.codegen_operand(bx, operand);
835
836         // Handle both by-ref and immediate tuples.
837         if let Ref(llval, None, align) = tuple.val {
838             let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
839             for i in 0..tuple.layout.fields.count() {
840                 let field_ptr = tuple_ptr.project_field(bx, i);
841                 self.codegen_argument(bx, field_ptr.load(bx), llargs, &args[i]);
842             }
843         } else if let Ref(_, Some(_), _) = tuple.val {
844             bug!("closure arguments must be sized")
845         } else {
846             // If the tuple is immediate, the elements are as well.
847             for i in 0..tuple.layout.fields.count() {
848                 let op = tuple.extract_field(bx, i);
849                 self.codegen_argument(bx, op, llargs, &args[i]);
850             }
851         }
852     }
853
854     fn get_personality_slot(
855         &mut self,
856         bx: &Builder<'a, 'll, 'tcx>
857     ) -> PlaceRef<'tcx, &'ll Value> {
858         let cx = bx.cx();
859         if let Some(slot) = self.personality_slot {
860             slot
861         } else {
862             let layout = cx.layout_of(cx.tcx.intern_tup(&[
863                 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
864                 cx.tcx.types.i32
865             ]));
866             let slot = PlaceRef::alloca(bx, layout, "personalityslot");
867             self.personality_slot = Some(slot);
868             slot
869         }
870     }
871
872     /// Return the landingpad wrapper around the given basic block
873     ///
874     /// No-op in MSVC SEH scheme.
875     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> &'ll BasicBlock {
876         if let Some(block) = self.landing_pads[target_bb] {
877             return block;
878         }
879
880         let block = self.blocks[target_bb];
881         let landing_pad = self.landing_pad_uncached(block);
882         self.landing_pads[target_bb] = Some(landing_pad);
883         landing_pad
884     }
885
886     fn landing_pad_uncached(&mut self, target_bb: &'ll BasicBlock) -> &'ll BasicBlock {
887         if base::wants_msvc_seh(self.cx.sess()) {
888             span_bug!(self.mir.span, "landing pad was not inserted?")
889         }
890
891         let bx = self.new_block("cleanup");
892
893         let llpersonality = self.cx.eh_personality();
894         let llretty = self.landing_pad_type();
895         let lp = bx.landing_pad(llretty, llpersonality, 1);
896         bx.set_cleanup(lp);
897
898         let slot = self.get_personality_slot(&bx);
899         slot.storage_live(&bx);
900         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
901
902         bx.br(target_bb);
903         bx.llbb()
904     }
905
906     fn landing_pad_type(&self) -> &'ll Type {
907         let cx = self.cx;
908         Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
909     }
910
911     fn unreachable_block(&mut self) -> &'ll BasicBlock {
912         self.unreachable_block.unwrap_or_else(|| {
913             let bl = self.new_block("unreachable");
914             bl.unreachable();
915             self.unreachable_block = Some(bl.llbb());
916             bl.llbb()
917         })
918     }
919
920     pub fn new_block(&self, name: &str) -> Builder<'a, 'll, 'tcx> {
921         Builder::new_block(self.cx, self.llfn, name)
922     }
923
924     pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'll, 'tcx> {
925         let bx = Builder::with_cx(self.cx);
926         bx.position_at_end(self.blocks[bb]);
927         bx
928     }
929
930     fn make_return_dest(&mut self, bx: &Builder<'a, 'll, 'tcx>,
931                         dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
932                         llargs: &mut Vec<&'ll Value>, is_intrinsic: bool)
933                         -> ReturnDest<'tcx, &'ll Value> {
934         // If the return is ignored, we can just return a do-nothing ReturnDest
935         if fn_ret.is_ignore() {
936             return ReturnDest::Nothing;
937         }
938         let dest = if let mir::Place::Local(index) = *dest {
939             match self.locals[index] {
940                 LocalRef::Place(dest) => dest,
941                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
942                 LocalRef::Operand(None) => {
943                     // Handle temporary places, specifically Operand ones, as
944                     // they don't have allocas
945                     return if fn_ret.is_indirect() {
946                         // Odd, but possible, case, we have an operand temporary,
947                         // but the calling convention has an indirect return.
948                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
949                         tmp.storage_live(bx);
950                         llargs.push(tmp.llval);
951                         ReturnDest::IndirectOperand(tmp, index)
952                     } else if is_intrinsic {
953                         // Currently, intrinsics always need a location to store
954                         // the result. so we create a temporary alloca for the
955                         // result
956                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
957                         tmp.storage_live(bx);
958                         ReturnDest::IndirectOperand(tmp, index)
959                     } else {
960                         ReturnDest::DirectOperand(index)
961                     };
962                 }
963                 LocalRef::Operand(Some(_)) => {
964                     bug!("place local already assigned to");
965                 }
966             }
967         } else {
968             self.codegen_place(bx, dest)
969         };
970         if fn_ret.is_indirect() {
971             if dest.align.abi() < dest.layout.align.abi() {
972                 // Currently, MIR code generation does not create calls
973                 // that store directly to fields of packed structs (in
974                 // fact, the calls it creates write only to temps),
975                 //
976                 // If someone changes that, please update this code path
977                 // to create a temporary.
978                 span_bug!(self.mir.span, "can't directly store to unaligned value");
979             }
980             llargs.push(dest.llval);
981             ReturnDest::Nothing
982         } else {
983             ReturnDest::Store(dest)
984         }
985     }
986
987     fn codegen_transmute(&mut self, bx: &Builder<'a, 'll, 'tcx>,
988                          src: &mir::Operand<'tcx>,
989                          dst: &mir::Place<'tcx>) {
990         if let mir::Place::Local(index) = *dst {
991             match self.locals[index] {
992                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
993                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
994                 LocalRef::Operand(None) => {
995                     let dst_layout = bx.cx().layout_of(self.monomorphized_place_ty(dst));
996                     assert!(!dst_layout.ty.has_erasable_regions());
997                     let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
998                     place.storage_live(bx);
999                     self.codegen_transmute_into(bx, src, place);
1000                     let op = place.load(bx);
1001                     place.storage_dead(bx);
1002                     self.locals[index] = LocalRef::Operand(Some(op));
1003                 }
1004                 LocalRef::Operand(Some(op)) => {
1005                     assert!(op.layout.is_zst(),
1006                             "assigning to initialized SSAtemp");
1007                 }
1008             }
1009         } else {
1010             let dst = self.codegen_place(bx, dst);
1011             self.codegen_transmute_into(bx, src, dst);
1012         }
1013     }
1014
1015     fn codegen_transmute_into(&mut self, bx: &Builder<'a, 'll, 'tcx>,
1016                               src: &mir::Operand<'tcx>,
1017                               dst: PlaceRef<'tcx, &'ll Value>) {
1018         let src = self.codegen_operand(bx, src);
1019         let llty = src.layout.llvm_type(bx.cx());
1020         let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
1021         let align = src.layout.align.min(dst.layout.align);
1022         src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1023     }
1024
1025
1026     // Stores the return value of a function call into it's final location.
1027     fn store_return(&mut self,
1028                     bx: &Builder<'a, 'll, 'tcx>,
1029                     dest: ReturnDest<'tcx, &'ll Value>,
1030                     ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1031                     llval: &'ll Value) {
1032         use self::ReturnDest::*;
1033
1034         match dest {
1035             Nothing => (),
1036             Store(dst) => ret_ty.store(bx, llval, dst),
1037             IndirectOperand(tmp, index) => {
1038                 let op = tmp.load(bx);
1039                 tmp.storage_dead(bx);
1040                 self.locals[index] = LocalRef::Operand(Some(op));
1041             }
1042             DirectOperand(index) => {
1043                 // If there is a cast, we have to store and reload.
1044                 let op = if let PassMode::Cast(_) = ret_ty.mode {
1045                     let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1046                     tmp.storage_live(bx);
1047                     ret_ty.store(bx, llval, tmp);
1048                     let op = tmp.load(bx);
1049                     tmp.storage_dead(bx);
1050                     op
1051                 } else {
1052                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1053                 };
1054                 self.locals[index] = LocalRef::Operand(Some(op));
1055             }
1056         }
1057     }
1058 }
1059
1060 enum ReturnDest<'tcx, V> {
1061     // Do nothing, the return value is indirect or ignored
1062     Nothing,
1063     // Store the return value to the pointer
1064     Store(PlaceRef<'tcx, V>),
1065     // Stores an indirect return value to an operand local place
1066     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1067     // Stores a direct return value to an operand local place
1068     DirectOperand(mir::Local)
1069 }