]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/block.rs
Rollup merge of #44562 - eddyb:ugh-rustdoc, r=nikomatsakis
[rust.git] / src / librustc_trans / 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, ValueRef, BasicBlockRef};
12 use rustc::middle::lang_items;
13 use rustc::middle::const_val::{ConstEvalErr, ConstInt, ErrKind};
14 use rustc::ty::{self, Ty, TypeFoldable};
15 use rustc::ty::layout::{self, LayoutTyper};
16 use rustc::mir;
17 use abi::{Abi, FnType, ArgType};
18 use adt;
19 use base::{self, Lifetime};
20 use callee;
21 use builder::Builder;
22 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_undef};
23 use consts;
24 use machine::llalign_of_min;
25 use meth;
26 use monomorphize;
27 use type_of;
28 use type_::Type;
29
30 use syntax::symbol::Symbol;
31 use syntax_pos::Pos;
32
33 use std::cmp;
34
35 use super::{MirContext, LocalRef};
36 use super::constant::Const;
37 use super::lvalue::{Alignment, LvalueRef};
38 use super::operand::OperandRef;
39 use super::operand::OperandValue::{Pair, Ref, Immediate};
40
41 impl<'a, 'tcx> MirContext<'a, 'tcx> {
42     pub fn trans_block(&mut self, bb: mir::BasicBlock) {
43         let mut bcx = self.get_builder(bb);
44         let data = &self.mir[bb];
45
46         debug!("trans_block({:?}={:?})", bb, data);
47
48         for statement in &data.statements {
49             bcx = self.trans_statement(bcx, statement);
50         }
51
52         self.trans_terminator(bcx, bb, data.terminator());
53     }
54
55     fn trans_terminator(&mut self,
56                         mut bcx: Builder<'a, 'tcx>,
57                         bb: mir::BasicBlock,
58                         terminator: &mir::Terminator<'tcx>)
59     {
60         debug!("trans_terminator: {:?}", terminator);
61
62         // Create the cleanup bundle, if needed.
63         let tcx = bcx.tcx();
64         let span = terminator.source_info.span;
65         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
66         let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
67
68         let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
69         let cleanup_bundle = funclet.map(|l| l.bundle());
70
71         let lltarget = |this: &mut Self, target: mir::BasicBlock| {
72             let lltarget = this.blocks[target];
73             let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
74             match (funclet_bb, target_funclet) {
75                 (None, None) => (lltarget, false),
76                 (Some(f), Some(t_f))
77                     if f == t_f || !base::wants_msvc_seh(tcx.sess)
78                     => (lltarget, false),
79                 (None, Some(_)) => {
80                     // jump *into* cleanup - need a landing pad if GNU
81                     (this.landing_pad_to(target), false)
82                 }
83                 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
84                 (Some(_), Some(_)) => {
85                     (this.landing_pad_to(target), true)
86                 }
87             }
88         };
89
90         let llblock = |this: &mut Self, target: mir::BasicBlock| {
91             let (lltarget, is_cleanupret) = lltarget(this, target);
92             if is_cleanupret {
93                 // MSVC cross-funclet jump - need a trampoline
94
95                 debug!("llblock: creating cleanup trampoline for {:?}", target);
96                 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
97                 let trampoline = this.new_block(name);
98                 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
99                 trampoline.llbb()
100             } else {
101                 lltarget
102             }
103         };
104
105         let funclet_br = |this: &mut Self, bcx: Builder, 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                 bcx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
111             } else {
112                 bcx.br(lltarget);
113             }
114         };
115
116         let do_call = |
117             this: &mut Self,
118             bcx: Builder<'a, 'tcx>,
119             fn_ty: FnType<'tcx>,
120             fn_ptr: ValueRef,
121             llargs: &[ValueRef],
122             destination: Option<(ReturnDest, Ty<'tcx>, mir::BasicBlock)>,
123             cleanup: Option<mir::BasicBlock>
124         | {
125             if let Some(cleanup) = cleanup {
126                 let ret_bcx = if let Some((_, _, target)) = destination {
127                     this.blocks[target]
128                 } else {
129                     this.unreachable_block()
130                 };
131                 let invokeret = bcx.invoke(fn_ptr,
132                                            &llargs,
133                                            ret_bcx,
134                                            llblock(this, cleanup),
135                                            cleanup_bundle);
136                 fn_ty.apply_attrs_callsite(invokeret);
137
138                 if let Some((ret_dest, ret_ty, target)) = destination {
139                     let ret_bcx = this.get_builder(target);
140                     this.set_debug_loc(&ret_bcx, terminator.source_info);
141                     let op = OperandRef {
142                         val: Immediate(invokeret),
143                         ty: ret_ty,
144                     };
145                     this.store_return(&ret_bcx, ret_dest, &fn_ty.ret, op);
146                 }
147             } else {
148                 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
149                 fn_ty.apply_attrs_callsite(llret);
150                 if this.mir[bb].is_cleanup {
151                     // Cleanup is always the cold path. Don't inline
152                     // drop glue. Also, when there is a deeply-nested
153                     // struct, there are "symmetry" issues that cause
154                     // exponential inlining - see issue #41696.
155                     llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
156                 }
157
158                 if let Some((ret_dest, ret_ty, target)) = destination {
159                     let op = OperandRef {
160                         val: Immediate(llret),
161                         ty: ret_ty,
162                     };
163                     this.store_return(&bcx, ret_dest, &fn_ty.ret, op);
164                     funclet_br(this, bcx, target);
165                 } else {
166                     bcx.unreachable();
167                 }
168             }
169         };
170
171         self.set_debug_loc(&bcx, terminator.source_info);
172         match terminator.kind {
173             mir::TerminatorKind::Resume => {
174                 if let Some(cleanup_pad) = cleanup_pad {
175                     bcx.cleanup_ret(cleanup_pad, None);
176                 } else {
177                     let ps = self.get_personality_slot(&bcx);
178                     let lp = bcx.load(ps, None);
179                     Lifetime::End.call(&bcx, ps);
180                     if !bcx.sess().target.target.options.custom_unwind_resume {
181                         bcx.resume(lp);
182                     } else {
183                         let exc_ptr = bcx.extract_value(lp, 0);
184                         bcx.call(bcx.ccx.eh_unwind_resume(), &[exc_ptr], cleanup_bundle);
185                         bcx.unreachable();
186                     }
187                 }
188             }
189
190             mir::TerminatorKind::Goto { target } => {
191                 funclet_br(self, bcx, target);
192             }
193
194             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
195                 let discr = self.trans_operand(&bcx, discr);
196                 if switch_ty == bcx.tcx().types.bool {
197                     let lltrue = llblock(self, targets[0]);
198                     let llfalse = llblock(self, targets[1]);
199                     if let [ConstInt::U8(0)] = values[..] {
200                         bcx.cond_br(discr.immediate(), llfalse, lltrue);
201                     } else {
202                         bcx.cond_br(discr.immediate(), lltrue, llfalse);
203                     }
204                 } else {
205                     let (otherwise, targets) = targets.split_last().unwrap();
206                     let switch = bcx.switch(discr.immediate(),
207                                             llblock(self, *otherwise), values.len());
208                     for (value, target) in values.iter().zip(targets) {
209                         let val = Const::from_constint(bcx.ccx, value);
210                         let llbb = llblock(self, *target);
211                         bcx.add_case(switch, val.llval, llbb)
212                     }
213                 }
214             }
215
216             mir::TerminatorKind::Return => {
217                 let ret = self.fn_ty.ret;
218                 if ret.is_ignore() || ret.is_indirect() {
219                     bcx.ret_void();
220                     return;
221                 }
222
223                 let llval = if let Some(cast_ty) = ret.cast {
224                     let op = match self.locals[mir::RETURN_POINTER] {
225                         LocalRef::Operand(Some(op)) => op,
226                         LocalRef::Operand(None) => bug!("use of return before def"),
227                         LocalRef::Lvalue(tr_lvalue) => {
228                             OperandRef {
229                                 val: Ref(tr_lvalue.llval, tr_lvalue.alignment),
230                                 ty: tr_lvalue.ty.to_ty(bcx.tcx())
231                             }
232                         }
233                     };
234                     let llslot = match op.val {
235                         Immediate(_) | Pair(..) => {
236                             let llscratch = bcx.alloca(ret.memory_ty(bcx.ccx), "ret", None);
237                             self.store_operand(&bcx, llscratch, None, op);
238                             llscratch
239                         }
240                         Ref(llval, align) => {
241                             assert_eq!(align, Alignment::AbiAligned,
242                                        "return pointer is unaligned!");
243                             llval
244                         }
245                     };
246                     let load = bcx.load(
247                         bcx.pointercast(llslot, cast_ty.ptr_to()),
248                         Some(ret.layout.align(bcx.ccx).abi() as u32));
249                     load
250                 } else {
251                     let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
252                     if let Ref(llval, align) = op.val {
253                         base::load_ty(&bcx, llval, align, op.ty)
254                     } else {
255                         op.pack_if_pair(&bcx).immediate()
256                     }
257                 };
258                 bcx.ret(llval);
259             }
260
261             mir::TerminatorKind::Unreachable => {
262                 bcx.unreachable();
263             }
264
265             mir::TerminatorKind::Drop { ref location, target, unwind } => {
266                 let ty = location.ty(self.mir, bcx.tcx()).to_ty(bcx.tcx());
267                 let ty = self.monomorphize(&ty);
268                 let drop_fn = monomorphize::resolve_drop_in_place(bcx.ccx.shared(), ty);
269
270                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
271                     // we don't actually need to drop anything.
272                     funclet_br(self, bcx, target);
273                     return
274                 }
275
276                 let lvalue = self.trans_lvalue(&bcx, location);
277                 let fn_ty = FnType::of_instance(bcx.ccx, &drop_fn);
278                 let (drop_fn, need_extra) = match ty.sty {
279                     ty::TyDynamic(..) => (meth::DESTRUCTOR.get_fn(&bcx, lvalue.llextra),
280                                           false),
281                     _ => (callee::get_fn(bcx.ccx, drop_fn), lvalue.has_extra())
282                 };
283                 let args = &[lvalue.llval, lvalue.llextra][..1 + need_extra as usize];
284                 do_call(self, bcx, fn_ty, drop_fn, args,
285                         Some((ReturnDest::Nothing, tcx.mk_nil(), target)),
286                         unwind);
287             }
288
289             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
290                 let cond = self.trans_operand(&bcx, cond).immediate();
291                 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
292
293                 // This case can currently arise only from functions marked
294                 // with #[rustc_inherit_overflow_checks] and inlined from
295                 // another crate (mostly core::num generic/#[inline] fns),
296                 // while the current crate doesn't use overflow checks.
297                 // NOTE: Unlike binops, negation doesn't have its own
298                 // checked operation, just a comparison with the minimum
299                 // value, so we have to check for the assert message.
300                 if !bcx.ccx.check_overflow() {
301                     use rustc_const_math::ConstMathErr::Overflow;
302                     use rustc_const_math::Op::Neg;
303
304                     if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
305                         const_cond = Some(expected);
306                     }
307                 }
308
309                 // Don't translate the panic block if success if known.
310                 if const_cond == Some(expected) {
311                     funclet_br(self, bcx, target);
312                     return;
313                 }
314
315                 // Pass the condition through llvm.expect for branch hinting.
316                 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
317                 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
318
319                 // Create the failure block and the conditional branch to it.
320                 let lltarget = llblock(self, target);
321                 let panic_block = self.new_block("panic");
322                 if expected {
323                     bcx.cond_br(cond, lltarget, panic_block.llbb());
324                 } else {
325                     bcx.cond_br(cond, panic_block.llbb(), lltarget);
326                 }
327
328                 // After this point, bcx is the block for the call to panic.
329                 bcx = panic_block;
330                 self.set_debug_loc(&bcx, terminator.source_info);
331
332                 // Get the location information.
333                 let loc = bcx.sess().codemap().lookup_char_pos(span.lo());
334                 let filename = Symbol::intern(&loc.file.name).as_str();
335                 let filename = C_str_slice(bcx.ccx, filename);
336                 let line = C_u32(bcx.ccx, loc.line as u32);
337                 let col = C_u32(bcx.ccx, loc.col.to_usize() as u32 + 1);
338
339                 // Put together the arguments to the panic entry point.
340                 let (lang_item, args, const_err) = match *msg {
341                     mir::AssertMessage::BoundsCheck { ref len, ref index } => {
342                         let len = self.trans_operand(&mut bcx, len).immediate();
343                         let index = self.trans_operand(&mut bcx, index).immediate();
344
345                         let const_err = common::const_to_opt_u128(len, false)
346                             .and_then(|len| common::const_to_opt_u128(index, false)
347                                 .map(|index| ErrKind::IndexOutOfBounds {
348                                     len: len as u64,
349                                     index: index as u64
350                                 }));
351
352                         let file_line_col = C_struct(bcx.ccx, &[filename, line, col], false);
353                         let align = llalign_of_min(bcx.ccx, common::val_ty(file_line_col));
354                         let file_line_col = consts::addr_of(bcx.ccx,
355                                                             file_line_col,
356                                                             align,
357                                                             "panic_bounds_check_loc");
358                         (lang_items::PanicBoundsCheckFnLangItem,
359                          vec![file_line_col, index, len],
360                          const_err)
361                     }
362                     mir::AssertMessage::Math(ref err) => {
363                         let msg_str = Symbol::intern(err.description()).as_str();
364                         let msg_str = C_str_slice(bcx.ccx, msg_str);
365                         let msg_file_line_col = C_struct(bcx.ccx,
366                                                      &[msg_str, filename, line, col],
367                                                      false);
368                         let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line_col));
369                         let msg_file_line_col = consts::addr_of(bcx.ccx,
370                                                                 msg_file_line_col,
371                                                                 align,
372                                                                 "panic_loc");
373                         (lang_items::PanicFnLangItem,
374                          vec![msg_file_line_col],
375                          Some(ErrKind::Math(err.clone())))
376                     }
377                     mir::AssertMessage::GeneratorResumedAfterReturn |
378                     mir::AssertMessage::GeneratorResumedAfterPanic => {
379                         let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
380                             "generator resumed after completion"
381                         } else {
382                             "generator resumed after panicking"
383                         };
384                         let msg_str = Symbol::intern(str).as_str();
385                         let msg_str = C_str_slice(bcx.ccx, msg_str);
386                         let msg_file_line_col = C_struct(bcx.ccx,
387                                                      &[msg_str, filename, line, col],
388                                                      false);
389                         let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line_col));
390                         let msg_file_line_col = consts::addr_of(bcx.ccx,
391                                                                 msg_file_line_col,
392                                                                 align,
393                                                                 "panic_loc");
394                         (lang_items::PanicFnLangItem,
395                          vec![msg_file_line_col],
396                          None)
397                     }
398                 };
399
400                 // If we know we always panic, and the error message
401                 // is also constant, then we can produce a warning.
402                 if const_cond == Some(!expected) {
403                     if let Some(err) = const_err {
404                         let err = ConstEvalErr{ span: span, kind: err };
405                         let mut diag = bcx.tcx().sess.struct_span_warn(
406                             span, "this expression will panic at run-time");
407                         err.note(bcx.tcx(), span, "expression", &mut diag);
408                         diag.emit();
409                     }
410                 }
411
412                 // Obtain the panic entry point.
413                 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
414                 let instance = ty::Instance::mono(bcx.tcx(), def_id);
415                 let fn_ty = FnType::of_instance(bcx.ccx, &instance);
416                 let llfn = callee::get_fn(bcx.ccx, instance);
417
418                 // Translate the actual panic invoke/call.
419                 do_call(self, bcx, fn_ty, llfn, &args, None, cleanup);
420             }
421
422             mir::TerminatorKind::DropAndReplace { .. } => {
423                 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
424             }
425
426             mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
427                 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
428                 let callee = self.trans_operand(&bcx, func);
429
430                 let (instance, mut llfn) = match callee.ty.sty {
431                     ty::TyFnDef(def_id, substs) => {
432                         (Some(monomorphize::resolve(bcx.ccx.shared(), def_id, substs)),
433                          None)
434                     }
435                     ty::TyFnPtr(_) => {
436                         (None, Some(callee.immediate()))
437                     }
438                     _ => bug!("{} is not callable", callee.ty)
439                 };
440                 let def = instance.map(|i| i.def);
441                 let sig = callee.ty.fn_sig(bcx.tcx());
442                 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(&sig);
443                 let abi = sig.abi;
444
445                 // Handle intrinsics old trans wants Expr's for, ourselves.
446                 let intrinsic = match def {
447                     Some(ty::InstanceDef::Intrinsic(def_id))
448                         => Some(bcx.tcx().item_name(def_id)),
449                     _ => None
450                 };
451                 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
452
453                 if intrinsic == Some("transmute") {
454                     let &(ref dest, target) = destination.as_ref().unwrap();
455                     self.trans_transmute(&bcx, &args[0], dest);
456                     funclet_br(self, bcx, target);
457                     return;
458                 }
459
460                 let extra_args = &args[sig.inputs().len()..];
461                 let extra_args = extra_args.iter().map(|op_arg| {
462                     let op_ty = op_arg.ty(self.mir, bcx.tcx());
463                     self.monomorphize(&op_ty)
464                 }).collect::<Vec<_>>();
465
466                 let fn_ty = match def {
467                     Some(ty::InstanceDef::Virtual(..)) => {
468                         FnType::new_vtable(bcx.ccx, sig, &extra_args)
469                     }
470                     Some(ty::InstanceDef::DropGlue(_, None)) => {
471                         // empty drop glue - a nop.
472                         let &(_, target) = destination.as_ref().unwrap();
473                         funclet_br(self, bcx, target);
474                         return;
475                     }
476                     _ => FnType::new(bcx.ccx, sig, &extra_args)
477                 };
478
479                 // The arguments we'll be passing. Plus one to account for outptr, if used.
480                 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
481                 let mut llargs = Vec::with_capacity(arg_count);
482
483                 // Prepare the return value destination
484                 let ret_dest = if let Some((ref dest, _)) = *destination {
485                     let is_intrinsic = intrinsic.is_some();
486                     self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs,
487                                           is_intrinsic)
488                 } else {
489                     ReturnDest::Nothing
490                 };
491
492                 // Split the rust-call tupled arguments off.
493                 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
494                     let (tup, args) = args.split_last().unwrap();
495                     (args, Some(tup))
496                 } else {
497                     (&args[..], None)
498                 };
499
500                 let is_shuffle = intrinsic.map_or(false, |name| {
501                     name.starts_with("simd_shuffle")
502                 });
503                 let mut idx = 0;
504                 for arg in first_args {
505                     // The indices passed to simd_shuffle* in the
506                     // third argument must be constant. This is
507                     // checked by const-qualification, which also
508                     // promotes any complex rvalues to constants.
509                     if is_shuffle && idx == 2 {
510                         match *arg {
511                             mir::Operand::Consume(_) => {
512                                 span_bug!(span, "shuffle indices must be constant");
513                             }
514                             mir::Operand::Constant(ref constant) => {
515                                 let val = self.trans_constant(&bcx, constant);
516                                 llargs.push(val.llval);
517                                 idx += 1;
518                                 continue;
519                             }
520                         }
521                     }
522
523                     let op = self.trans_operand(&bcx, arg);
524                     self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
525                                         &mut idx, &mut llfn, &def);
526                 }
527                 if let Some(tup) = untuple {
528                     self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
529                                                   &mut idx, &mut llfn, &def)
530                 }
531
532                 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
533                     use intrinsic::trans_intrinsic_call;
534
535                     let (dest, llargs) = match ret_dest {
536                         _ if fn_ty.ret.is_indirect() => {
537                             (llargs[0], &llargs[1..])
538                         }
539                         ReturnDest::Nothing => {
540                             (C_undef(fn_ty.ret.memory_ty(bcx.ccx).ptr_to()), &llargs[..])
541                         }
542                         ReturnDest::IndirectOperand(dst, _) |
543                         ReturnDest::Store(dst) => (dst, &llargs[..]),
544                         ReturnDest::DirectOperand(_) =>
545                             bug!("Cannot use direct operand with an intrinsic call")
546                     };
547
548                     let callee_ty = common::instance_ty(
549                         bcx.ccx.shared(), instance.as_ref().unwrap());
550                     trans_intrinsic_call(&bcx, callee_ty, &fn_ty, &llargs, dest,
551                                          terminator.source_info.span);
552
553                     if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
554                         // Make a fake operand for store_return
555                         let op = OperandRef {
556                             val: Ref(dst, Alignment::AbiAligned),
557                             ty: sig.output(),
558                         };
559                         self.store_return(&bcx, ret_dest, &fn_ty.ret, op);
560                     }
561
562                     if let Some((_, target)) = *destination {
563                         funclet_br(self, bcx, target);
564                     } else {
565                         bcx.unreachable();
566                     }
567
568                     return;
569                 }
570
571                 let fn_ptr = match (llfn, instance) {
572                     (Some(llfn), _) => llfn,
573                     (None, Some(instance)) => callee::get_fn(bcx.ccx, instance),
574                     _ => span_bug!(span, "no llfn for call"),
575                 };
576
577                 do_call(self, bcx, fn_ty, fn_ptr, &llargs,
578                         destination.as_ref().map(|&(_, target)| (ret_dest, sig.output(), target)),
579                         cleanup);
580             }
581             mir::TerminatorKind::GeneratorDrop |
582             mir::TerminatorKind::Yield { .. } => bug!("generator ops in trans"),
583         }
584     }
585
586     fn trans_argument(&mut self,
587                       bcx: &Builder<'a, 'tcx>,
588                       op: OperandRef<'tcx>,
589                       llargs: &mut Vec<ValueRef>,
590                       fn_ty: &FnType<'tcx>,
591                       next_idx: &mut usize,
592                       llfn: &mut Option<ValueRef>,
593                       def: &Option<ty::InstanceDef<'tcx>>) {
594         if let Pair(a, b) = op.val {
595             // Treat the values in a fat pointer separately.
596             if common::type_is_fat_ptr(bcx.ccx, op.ty) {
597                 let (ptr, meta) = (a, b);
598                 if *next_idx == 0 {
599                     if let Some(ty::InstanceDef::Virtual(_, idx)) = *def {
600                         let llmeth = meth::VirtualIndex::from_index(idx).get_fn(bcx, meta);
601                         let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
602                         *llfn = Some(bcx.pointercast(llmeth, llty));
603                     }
604                 }
605
606                 let imm_op = |x| OperandRef {
607                     val: Immediate(x),
608                     // We won't be checking the type again.
609                     ty: bcx.tcx().types.err
610                 };
611                 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, llfn, def);
612                 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, llfn, def);
613                 return;
614             }
615         }
616
617         let arg = &fn_ty.args[*next_idx];
618         *next_idx += 1;
619
620         // Fill padding with undef value, where applicable.
621         if let Some(ty) = arg.pad {
622             llargs.push(C_undef(ty));
623         }
624
625         if arg.is_ignore() {
626             return;
627         }
628
629         // Force by-ref if we have to load through a cast pointer.
630         let (mut llval, align, by_ref) = match op.val {
631             Immediate(_) | Pair(..) => {
632                 if arg.is_indirect() || arg.cast.is_some() {
633                     let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
634                     self.store_operand(bcx, llscratch, None, op);
635                     (llscratch, Alignment::AbiAligned, true)
636                 } else {
637                     (op.pack_if_pair(bcx).immediate(), Alignment::AbiAligned, false)
638                 }
639             }
640             Ref(llval, Alignment::Packed) if arg.is_indirect() => {
641                 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
642                 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
643                 // have scary latent bugs around.
644
645                 let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
646                 base::memcpy_ty(bcx, llscratch, llval, op.ty, Some(1));
647                 (llscratch, Alignment::AbiAligned, true)
648             }
649             Ref(llval, align) => (llval, align, true)
650         };
651
652         if by_ref && !arg.is_indirect() {
653             // Have to load the argument, maybe while casting it.
654             if arg.layout.ty == bcx.tcx().types.bool {
655                 // We store bools as i8 so we need to truncate to i1.
656                 llval = bcx.load_range_assert(llval, 0, 2, llvm::False, None);
657                 llval = bcx.trunc(llval, Type::i1(bcx.ccx));
658             } else if let Some(ty) = arg.cast {
659                 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()),
660                                  align.min_with(arg.layout.align(bcx.ccx).abi() as u32));
661             } else {
662                 llval = bcx.load(llval, align.to_align());
663             }
664         }
665
666         llargs.push(llval);
667     }
668
669     fn trans_arguments_untupled(&mut self,
670                                 bcx: &Builder<'a, 'tcx>,
671                                 operand: &mir::Operand<'tcx>,
672                                 llargs: &mut Vec<ValueRef>,
673                                 fn_ty: &FnType<'tcx>,
674                                 next_idx: &mut usize,
675                                 llfn: &mut Option<ValueRef>,
676                                 def: &Option<ty::InstanceDef<'tcx>>) {
677         let tuple = self.trans_operand(bcx, operand);
678
679         let arg_types = match tuple.ty.sty {
680             ty::TyTuple(ref tys, _) => tys,
681             _ => span_bug!(self.mir.span,
682                            "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
683         };
684
685         // Handle both by-ref and immediate tuples.
686         match tuple.val {
687             Ref(llval, align) => {
688                 for (n, &ty) in arg_types.iter().enumerate() {
689                     let ptr = LvalueRef::new_sized_ty(llval, tuple.ty, align);
690                     let (ptr, align) = ptr.trans_field_ptr(bcx, n);
691                     let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
692                         let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, align, ty);
693                         Pair(lldata, llextra)
694                     } else {
695                         // trans_argument will load this if it needs to
696                         Ref(ptr, align)
697                     };
698                     let op = OperandRef {
699                         val,
700                         ty,
701                     };
702                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
703                 }
704
705             }
706             Immediate(llval) => {
707                 let l = bcx.ccx.layout_of(tuple.ty);
708                 let v = if let layout::Univariant { ref variant, .. } = *l {
709                     variant
710                 } else {
711                     bug!("Not a tuple.");
712                 };
713                 for (n, &ty) in arg_types.iter().enumerate() {
714                     let mut elem = bcx.extract_value(
715                         llval, adt::struct_llfields_index(v, n));
716                     // Truncate bools to i1, if needed
717                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
718                         elem = bcx.trunc(elem, Type::i1(bcx.ccx));
719                     }
720                     // If the tuple is immediate, the elements are as well
721                     let op = OperandRef {
722                         val: Immediate(elem),
723                         ty,
724                     };
725                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
726                 }
727             }
728             Pair(a, b) => {
729                 let elems = [a, b];
730                 for (n, &ty) in arg_types.iter().enumerate() {
731                     let mut elem = elems[n];
732                     // Truncate bools to i1, if needed
733                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
734                         elem = bcx.trunc(elem, Type::i1(bcx.ccx));
735                     }
736                     // Pair is always made up of immediates
737                     let op = OperandRef {
738                         val: Immediate(elem),
739                         ty,
740                     };
741                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
742                 }
743             }
744         }
745
746     }
747
748     fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
749         let ccx = bcx.ccx;
750         if let Some(slot) = self.llpersonalityslot {
751             slot
752         } else {
753             let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
754             let slot = bcx.alloca(llretty, "personalityslot", None);
755             self.llpersonalityslot = Some(slot);
756             slot
757         }
758     }
759
760     /// Return the landingpad wrapper around the given basic block
761     ///
762     /// No-op in MSVC SEH scheme.
763     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
764         if let Some(block) = self.landing_pads[target_bb] {
765             return block;
766         }
767
768         let block = self.blocks[target_bb];
769         let landing_pad = self.landing_pad_uncached(block);
770         self.landing_pads[target_bb] = Some(landing_pad);
771         landing_pad
772     }
773
774     fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
775         if base::wants_msvc_seh(self.ccx.sess()) {
776             span_bug!(self.mir.span, "landing pad was not inserted?")
777         }
778
779         let bcx = self.new_block("cleanup");
780
781         let ccx = bcx.ccx;
782         let llpersonality = self.ccx.eh_personality();
783         let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
784         let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
785         bcx.set_cleanup(llretval);
786         let slot = self.get_personality_slot(&bcx);
787         Lifetime::Start.call(&bcx, slot);
788         bcx.store(llretval, slot, None);
789         bcx.br(target_bb);
790         bcx.llbb()
791     }
792
793     fn unreachable_block(&mut self) -> BasicBlockRef {
794         self.unreachable_block.unwrap_or_else(|| {
795             let bl = self.new_block("unreachable");
796             bl.unreachable();
797             self.unreachable_block = Some(bl.llbb());
798             bl.llbb()
799         })
800     }
801
802     pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
803         Builder::new_block(self.ccx, self.llfn, name)
804     }
805
806     pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
807         let builder = Builder::with_ccx(self.ccx);
808         builder.position_at_end(self.blocks[bb]);
809         builder
810     }
811
812     fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
813                         dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
814                         llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
815         // If the return is ignored, we can just return a do-nothing ReturnDest
816         if fn_ret_ty.is_ignore() {
817             return ReturnDest::Nothing;
818         }
819         let dest = if let mir::Lvalue::Local(index) = *dest {
820             let ret_ty = self.monomorphized_lvalue_ty(dest);
821             match self.locals[index] {
822                 LocalRef::Lvalue(dest) => dest,
823                 LocalRef::Operand(None) => {
824                     // Handle temporary lvalues, specifically Operand ones, as
825                     // they don't have allocas
826                     return if fn_ret_ty.is_indirect() {
827                         // Odd, but possible, case, we have an operand temporary,
828                         // but the calling convention has an indirect return.
829                         let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
830                         llargs.push(tmp.llval);
831                         ReturnDest::IndirectOperand(tmp.llval, index)
832                     } else if is_intrinsic {
833                         // Currently, intrinsics always need a location to store
834                         // the result. so we create a temporary alloca for the
835                         // result
836                         let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
837                         ReturnDest::IndirectOperand(tmp.llval, index)
838                     } else {
839                         ReturnDest::DirectOperand(index)
840                     };
841                 }
842                 LocalRef::Operand(Some(_)) => {
843                     bug!("lvalue local already assigned to");
844                 }
845             }
846         } else {
847             self.trans_lvalue(bcx, dest)
848         };
849         if fn_ret_ty.is_indirect() {
850             match dest.alignment {
851                 Alignment::AbiAligned => {
852                     llargs.push(dest.llval);
853                     ReturnDest::Nothing
854                 },
855                 Alignment::Packed => {
856                     // Currently, MIR code generation does not create calls
857                     // that store directly to fields of packed structs (in
858                     // fact, the calls it creates write only to temps),
859                     //
860                     // If someone changes that, please update this code path
861                     // to create a temporary.
862                     span_bug!(self.mir.span, "can't directly store to unaligned value");
863                 }
864             }
865         } else {
866             ReturnDest::Store(dest.llval)
867         }
868     }
869
870     fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
871                        src: &mir::Operand<'tcx>,
872                        dst: &mir::Lvalue<'tcx>) {
873         if let mir::Lvalue::Local(index) = *dst {
874             match self.locals[index] {
875                 LocalRef::Lvalue(lvalue) => self.trans_transmute_into(bcx, src, &lvalue),
876                 LocalRef::Operand(None) => {
877                     let lvalue_ty = self.monomorphized_lvalue_ty(dst);
878                     assert!(!lvalue_ty.has_erasable_regions());
879                     let lvalue = LvalueRef::alloca(bcx, lvalue_ty, "transmute_temp");
880                     self.trans_transmute_into(bcx, src, &lvalue);
881                     let op = self.trans_load(bcx, lvalue.llval, lvalue.alignment, lvalue_ty);
882                     self.locals[index] = LocalRef::Operand(Some(op));
883                 }
884                 LocalRef::Operand(Some(_)) => {
885                     let ty = self.monomorphized_lvalue_ty(dst);
886                     assert!(common::type_is_zero_size(bcx.ccx, ty),
887                             "assigning to initialized SSAtemp");
888                 }
889             }
890         } else {
891             let dst = self.trans_lvalue(bcx, dst);
892             self.trans_transmute_into(bcx, src, &dst);
893         }
894     }
895
896     fn trans_transmute_into(&mut self, bcx: &Builder<'a, 'tcx>,
897                             src: &mir::Operand<'tcx>,
898                             dst: &LvalueRef<'tcx>) {
899         let val = self.trans_operand(bcx, src);
900         let llty = type_of::type_of(bcx.ccx, val.ty);
901         let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
902         let in_type = val.ty;
903         let out_type = dst.ty.to_ty(bcx.tcx());
904         let llalign = cmp::min(bcx.ccx.align_of(in_type), bcx.ccx.align_of(out_type));
905         self.store_operand(bcx, cast_ptr, Some(llalign), val);
906     }
907
908
909     // Stores the return value of a function call into it's final location.
910     fn store_return(&mut self,
911                     bcx: &Builder<'a, 'tcx>,
912                     dest: ReturnDest,
913                     ret_ty: &ArgType<'tcx>,
914                     op: OperandRef<'tcx>) {
915         use self::ReturnDest::*;
916
917         match dest {
918             Nothing => (),
919             Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
920             IndirectOperand(tmp, index) => {
921                 let op = self.trans_load(bcx, tmp, Alignment::AbiAligned, op.ty);
922                 self.locals[index] = LocalRef::Operand(Some(op));
923             }
924             DirectOperand(index) => {
925                 // If there is a cast, we have to store and reload.
926                 let op = if ret_ty.cast.is_some() {
927                     let tmp = LvalueRef::alloca(bcx, op.ty, "tmp_ret");
928                     ret_ty.store(bcx, op.immediate(), tmp.llval);
929                     self.trans_load(bcx, tmp.llval, tmp.alignment, op.ty)
930                 } else {
931                     op.unpack_if_pair(bcx)
932                 };
933                 self.locals[index] = LocalRef::Operand(Some(op));
934             }
935         }
936     }
937 }
938
939 enum ReturnDest {
940     // Do nothing, the return value is indirect or ignored
941     Nothing,
942     // Store the return value to the pointer
943     Store(ValueRef),
944     // Stores an indirect return value to an operand local lvalue
945     IndirectOperand(ValueRef, mir::Local),
946     // Stores a direct return value to an operand local lvalue
947     DirectOperand(mir::Local)
948 }