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