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