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