]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_ssa/src/mir/block.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_codegen_ssa / src / mir / block.rs
CommitLineData
dfeec247
XL
1use super::operand::OperandRef;
2use super::operand::OperandValue::{Immediate, Pair, Ref};
3use super::place::PlaceRef;
487cf647 4use super::{CachedLlbb, FunctionCx, LocalRef};
dfeec247 5
9fa01778 6use crate::base;
9fa01778
XL
7use crate::common::{self, IntPredicate};
8use crate::meth;
9fa01778 9use crate::traits::*;
dfeec247 10use crate::MemFlags;
3157f602 11
3dfed10e 12use rustc_ast as ast;
a2a8927a 13use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
3dfed10e 14use rustc_hir::lang_items::LangItem;
dfeec247 15use rustc_index::vec::Idx;
f2b60f7d 16use rustc_middle::mir::{self, AssertKind, SwitchTargets};
c295e0f8
XL
17use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
18use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
064997fb 19use rustc_middle::ty::{self, Instance, Ty, TypeVisitable};
487cf647 20use rustc_session::config::OptLevel;
3dfed10e
XL
21use rustc_span::source_map::Span;
22use rustc_span::{sym, Symbol};
064997fb 23use rustc_symbol_mangling::typeid::typeid_for_fnabi;
f2b60f7d 24use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg};
064997fb 25use rustc_target::abi::{self, HasDataLayout, WrappingRange};
dfeec247 26use rustc_target::spec::abi::Abi;
54a0048b 27
487cf647
FG
28// Indicates if we are in the middle of merging a BB's successor into it. This
29// can happen when BB jumps directly to its successor and the successor has no
30// other predecessors.
31#[derive(Debug, PartialEq)]
32enum MergingSucc {
33 False,
34 True,
35}
36
532ac7d7
XL
37/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
38/// e.g., creating a basic block, calling a function, etc.
60c5eb7d
XL
39struct TerminatorCodegenHelper<'tcx> {
40 bb: mir::BasicBlock,
41 terminator: &'tcx mir::Terminator<'tcx>,
532ac7d7
XL
42 funclet_bb: Option<mir::BasicBlock>,
43}
44
60c5eb7d 45impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
17df50a5
XL
46 /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
47 /// either already previously cached, or newly created, by `landing_pad_for`.
60c5eb7d 48 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 49 &self,
17df50a5 50 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
60c5eb7d 51 ) -> Option<&'b Bx::Funclet> {
17df50a5
XL
52 let funclet_bb = self.funclet_bb?;
53 if base::wants_msvc_seh(fx.cx.tcx().sess) {
54 // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
55 // it has to be now. This may not seem necessary, as RPO should lead
56 // to all the unwind edges being visited (and so to `landing_pad_for`
57 // getting called for them), before building any of the blocks inside
58 // the funclet itself - however, if MIR contains edges that end up not
59 // being needed in the LLVM IR after monomorphization, the funclet may
60 // be unreachable, and we don't have yet a way to skip building it in
61 // such an eventuality (which may be a better solution than this).
62 if fx.funclets[funclet_bb].is_none() {
63 fx.landing_pad_for(funclet_bb);
64 }
65
66 Some(
67 fx.funclets[funclet_bb]
68 .as_ref()
69 .expect("landing_pad_for didn't also create funclets entry"),
70 )
71 } else {
72 None
73 }
532ac7d7 74 }
3157f602 75
2b03887a
FG
76 /// Get a basic block (creating it if necessary), possibly with cleanup
77 /// stuff in it or next to it.
78 fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 79 &self,
60c5eb7d 80 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7
XL
81 target: mir::BasicBlock,
82 ) -> Bx::BasicBlock {
487cf647
FG
83 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
84 let mut lltarget = fx.llbb(target);
85 if needs_landing_pad {
86 lltarget = fx.landing_pad_for(target);
87 }
532ac7d7
XL
88 if is_cleanupret {
89 // MSVC cross-funclet jump - need a trampoline
2b03887a
FG
90 debug_assert!(base::wants_msvc_seh(fx.cx.tcx().sess));
91 debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
532ac7d7 92 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
2b03887a
FG
93 let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
94 let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
5e7ed085 95 trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
2b03887a 96 trampoline_llbb
532ac7d7
XL
97 } else {
98 lltarget
99 }
7cac9316
XL
100 }
101
487cf647
FG
102 fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
103 &self,
104 fx: &mut FunctionCx<'a, 'tcx, Bx>,
105 target: mir::BasicBlock,
106 ) -> (bool, bool) {
107 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
108 let (needs_landing_pad, is_cleanupret) = match (self.funclet_bb, target_funclet) {
109 (None, None) => (false, false),
110 (None, Some(_)) => (true, false),
111 (Some(_), None) => {
112 let span = self.terminator.source_info.span;
113 span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
114 }
115 (Some(f), Some(t_f)) => {
116 if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) {
117 (false, false)
118 } else {
119 (true, true)
120 }
121 }
122 };
123 (needs_landing_pad, is_cleanupret)
124 }
125
60c5eb7d 126 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 127 &self,
60c5eb7d 128 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7
XL
129 bx: &mut Bx,
130 target: mir::BasicBlock,
487cf647
FG
131 mergeable_succ: bool,
132 ) -> MergingSucc {
133 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
134 if mergeable_succ && !needs_landing_pad && !is_cleanupret {
135 // We can merge the successor into this bb, so no need for a `br`.
136 MergingSucc::True
532ac7d7 137 } else {
487cf647
FG
138 let mut lltarget = fx.llbb(target);
139 if needs_landing_pad {
140 lltarget = fx.landing_pad_for(target);
141 }
142 if is_cleanupret {
143 // micro-optimization: generate a `ret` rather than a jump
144 // to a trampoline.
145 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
146 } else {
147 bx.br(lltarget);
148 }
149 MergingSucc::False
532ac7d7
XL
150 }
151 }
7cac9316 152
60c5eb7d 153 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
532ac7d7 154 /// return destination `destination` and the cleanup function `cleanup`.
60c5eb7d 155 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
532ac7d7 156 &self,
60c5eb7d 157 fx: &mut FunctionCx<'a, 'tcx, Bx>,
532ac7d7 158 bx: &mut Bx,
c295e0f8 159 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
532ac7d7
XL
160 fn_ptr: Bx::Value,
161 llargs: &[Bx::Value],
162 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
163 cleanup: Option<mir::BasicBlock>,
064997fb 164 copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
487cf647
FG
165 mergeable_succ: bool,
166 ) -> MergingSucc {
ba9703b0
XL
167 // If there is a cleanup block and the function we're calling can unwind, then
168 // do an invoke, otherwise do a call.
94222f64 169 let fn_ty = bx.fn_decl_backend_type(&fn_abi);
5e7ed085
FG
170
171 let unwind_block = if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
2b03887a 172 Some(self.llbb_with_cleanup(fx, cleanup))
5e7ed085
FG
173 } else if fx.mir[self.bb].is_cleanup
174 && fn_abi.can_unwind
175 && !base::wants_msvc_seh(fx.cx.tcx().sess)
176 {
177 // Exception must not propagate out of the execution of a cleanup (doing so
178 // can cause undefined behaviour). We insert a double unwind guard for
179 // functions that can potentially unwind to protect against this.
180 //
181 // This is not necessary for SEH which does not use successive unwinding
182 // like Itanium EH. EH frames in SEH are different from normal function
183 // frames and SEH will abort automatically if an exception tries to
184 // propagate out from cleanup.
185 Some(fx.double_unwind_guard())
186 } else {
187 None
188 };
189
190 if let Some(unwind_block) = unwind_block {
17df50a5
XL
191 let ret_llbb = if let Some((_, target)) = destination {
192 fx.llbb(target)
532ac7d7
XL
193 } else {
194 fx.unreachable_block()
195 };
2b03887a
FG
196 let invokeret = bx.invoke(
197 fn_ty,
198 Some(&fn_abi),
199 fn_ptr,
200 &llargs,
201 ret_llbb,
202 unwind_block,
203 self.funclet(fx),
204 );
5e7ed085
FG
205 if fx.mir[self.bb].is_cleanup {
206 bx.do_not_inline(invokeret);
207 }
532ac7d7
XL
208
209 if let Some((ret_dest, target)) = destination {
5e7ed085
FG
210 bx.switch_to_block(fx.llbb(target));
211 fx.set_debug_loc(bx, self.terminator.source_info);
064997fb
FG
212 for tmp in copied_constant_arguments {
213 bx.lifetime_end(tmp.llval, tmp.layout.size);
214 }
5e7ed085 215 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
a1dfa0c6 216 }
487cf647 217 MergingSucc::False
532ac7d7 218 } else {
2b03887a 219 let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx));
60c5eb7d 220 if fx.mir[self.bb].is_cleanup {
5e7ed085
FG
221 // Cleanup is always the cold path. Don't inline
222 // drop glue. Also, when there is a deeply-nested
223 // struct, there are "symmetry" issues that cause
224 // exponential inlining - see issue #41696.
225 bx.do_not_inline(llret);
3157f602 226 }
7cac9316 227
532ac7d7 228 if let Some((ret_dest, target)) = destination {
064997fb
FG
229 for tmp in copied_constant_arguments {
230 bx.lifetime_end(tmp.llval, tmp.layout.size);
231 }
60c5eb7d 232 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
487cf647 233 self.funclet_br(fx, bx, target, mergeable_succ)
7cac9316 234 } else {
532ac7d7 235 bx.unreachable();
487cf647 236 MergingSucc::False
7cac9316 237 }
532ac7d7
XL
238 }
239 }
a2a8927a
XL
240
241 /// Generates inline assembly with optional `destination` and `cleanup`.
242 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
243 &self,
244 fx: &mut FunctionCx<'a, 'tcx, Bx>,
245 bx: &mut Bx,
246 template: &[InlineAsmTemplatePiece],
247 operands: &[InlineAsmOperandRef<'tcx, Bx>],
248 options: InlineAsmOptions,
249 line_spans: &[Span],
250 destination: Option<mir::BasicBlock>,
251 cleanup: Option<mir::BasicBlock>,
252 instance: Instance<'_>,
487cf647
FG
253 mergeable_succ: bool,
254 ) -> MergingSucc {
a2a8927a
XL
255 if let Some(cleanup) = cleanup {
256 let ret_llbb = if let Some(target) = destination {
257 fx.llbb(target)
258 } else {
259 fx.unreachable_block()
260 };
261
262 bx.codegen_inline_asm(
263 template,
264 &operands,
265 options,
266 line_spans,
267 instance,
2b03887a 268 Some((ret_llbb, self.llbb_with_cleanup(fx, cleanup), self.funclet(fx))),
a2a8927a 269 );
487cf647 270 MergingSucc::False
a2a8927a
XL
271 } else {
272 bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None);
273
274 if let Some(target) = destination {
487cf647 275 self.funclet_br(fx, bx, target, mergeable_succ)
a2a8927a
XL
276 } else {
277 bx.unreachable();
487cf647 278 MergingSucc::False
a2a8927a
XL
279 }
280 }
281 }
532ac7d7 282}
3157f602 283
532ac7d7 284/// Codegen implementations for some terminator variants.
dc9dc135 285impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
532ac7d7 286 /// Generates code for a `Resume` terminator.
487cf647 287 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
532ac7d7
XL
288 if let Some(funclet) = helper.funclet(self) {
289 bx.cleanup_ret(funclet, None);
290 } else {
487cf647 291 let slot = self.get_personality_slot(bx);
9c376795
FG
292 let exn0 = slot.project_field(bx, 0);
293 let exn0 = bx.load_operand(exn0).immediate();
294 let exn1 = slot.project_field(bx, 1);
295 let exn1 = bx.load_operand(exn1).immediate();
487cf647 296 slot.storage_dead(bx);
532ac7d7 297
9c376795 298 bx.resume(exn0, exn1);
532ac7d7
XL
299 }
300 }
7cac9316 301
60c5eb7d 302 fn codegen_switchint_terminator(
532ac7d7 303 &mut self,
60c5eb7d 304 helper: TerminatorCodegenHelper<'tcx>,
487cf647 305 bx: &mut Bx,
532ac7d7 306 discr: &mir::Operand<'tcx>,
29967ef6 307 targets: &SwitchTargets,
532ac7d7 308 ) {
487cf647 309 let discr = self.codegen_operand(bx, &discr);
9c376795 310 let switch_ty = discr.layout.ty;
29967ef6
XL
311 let mut target_iter = targets.iter();
312 if target_iter.len() == 1 {
487cf647
FG
313 // If there are two targets (one conditional, one fallback), emit `br` instead of
314 // `switch`.
29967ef6 315 let (test_value, target) = target_iter.next().unwrap();
2b03887a
FG
316 let lltrue = helper.llbb_with_cleanup(self, target);
317 let llfalse = helper.llbb_with_cleanup(self, targets.otherwise());
532ac7d7 318 if switch_ty == bx.tcx().types.bool {
487cf647 319 // Don't generate trivial icmps when switching on bool.
29967ef6
XL
320 match test_value {
321 0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
322 1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
323 _ => bug!(),
3157f602 324 }
532ac7d7 325 } else {
dfeec247 326 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
29967ef6 327 let llval = bx.const_uint_big(switch_llty, test_value);
532ac7d7
XL
328 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
329 bx.cond_br(cmp, lltrue, llfalse);
3157f602 330 }
487cf647
FG
331 } else if self.cx.sess().opts.optimize == OptLevel::No
332 && target_iter.len() == 2
333 && self.mir[targets.otherwise()].is_empty_unreachable()
334 {
335 // In unoptimized builds, if there are two normal targets and the `otherwise` target is
336 // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
337 // BB, which will usually (but not always) be dead code.
338 //
339 // Why only in unoptimized builds?
340 // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
341 // must fall back to the to the slower SelectionDAG isel. Therefore, using `br` gives
342 // significant compile time speedups for unoptimized builds.
343 // - In optimized builds the above doesn't hold, and using `br` sometimes results in
344 // worse generated code because LLVM can no longer tell that the value being switched
345 // on can only have two values, e.g. 0 and 1.
346 //
347 let (test_value1, target1) = target_iter.next().unwrap();
348 let (_test_value2, target2) = target_iter.next().unwrap();
349 let ll1 = helper.llbb_with_cleanup(self, target1);
350 let ll2 = helper.llbb_with_cleanup(self, target2);
351 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
352 let llval = bx.const_uint_big(switch_llty, test_value1);
353 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
354 bx.cond_br(cmp, ll1, ll2);
532ac7d7 355 } else {
532ac7d7
XL
356 bx.switch(
357 discr.immediate(),
2b03887a
FG
358 helper.llbb_with_cleanup(self, targets.otherwise()),
359 target_iter.map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
532ac7d7
XL
360 );
361 }
362 }
54a0048b 363
487cf647 364 fn codegen_return_terminator(&mut self, bx: &mut Bx) {
e74abb32 365 // Call `va_end` if this is the definition of a C-variadic function.
60c5eb7d 366 if self.fn_abi.c_variadic {
e74abb32 367 // The `VaList` "spoofed" argument is just after all the real arguments.
60c5eb7d 368 let va_list_arg_idx = self.fn_abi.args.len();
e74abb32
XL
369 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
370 LocalRef::Place(va_list) => {
532ac7d7
XL
371 bx.va_end(va_list.llval);
372 }
e74abb32 373 _ => bug!("C-variadic function must have a `VaList` place"),
54a0048b 374 }
532ac7d7 375 }
60c5eb7d 376 if self.fn_abi.ret.layout.abi.is_uninhabited() {
532ac7d7
XL
377 // Functions with uninhabited return values are marked `noreturn`,
378 // so we should make sure that we never actually do.
60c5eb7d
XL
379 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
380 // if that turns out to be helpful.
532ac7d7 381 bx.abort();
60c5eb7d
XL
382 // `abort` does not terminate the block, so we still need to generate
383 // an `unreachable` terminator after it.
532ac7d7
XL
384 bx.unreachable();
385 return;
386 }
f2b60f7d 387 let llval = match &self.fn_abi.ret.mode {
fc512014 388 PassMode::Ignore | PassMode::Indirect { .. } => {
532ac7d7
XL
389 bx.ret_void();
390 return;
ff7c6d11
XL
391 }
392
532ac7d7 393 PassMode::Direct(_) | PassMode::Pair(..) => {
487cf647 394 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
532ac7d7 395 if let Ref(llval, _, align) = op.val {
136023e0 396 bx.load(bx.backend_type(op.layout), llval, align)
8bb4bdeb 397 } else {
487cf647 398 op.immediate_or_packed_pair(bx)
54a0048b
SL
399 }
400 }
401
f2b60f7d 402 PassMode::Cast(cast_ty, _) => {
532ac7d7
XL
403 let op = match self.locals[mir::RETURN_PLACE] {
404 LocalRef::Operand(Some(op)) => op,
405 LocalRef::Operand(None) => bug!("use of return before def"),
dfeec247
XL
406 LocalRef::Place(cg_place) => OperandRef {
407 val: Ref(cg_place.llval, None, cg_place.align),
408 layout: cg_place.layout,
409 },
532ac7d7
XL
410 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
411 };
412 let llslot = match op.val {
413 Immediate(_) | Pair(..) => {
487cf647
FG
414 let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
415 op.val.store(bx, scratch);
532ac7d7
XL
416 scratch.llval
417 }
418 Ref(llval, _, align) => {
dfeec247 419 assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
532ac7d7 420 llval
476ff2be 421 }
3157f602 422 };
f2b60f7d 423 let ty = bx.cast_backend_type(cast_ty);
136023e0
XL
424 let addr = bx.pointercast(llslot, bx.type_ptr_to(ty));
425 bx.load(ty, addr, self.fn_abi.ret.layout.align.abi)
3157f602 426 }
532ac7d7
XL
427 };
428 bx.ret(llval);
429 }
3157f602 430
f2b60f7d 431 #[tracing::instrument(level = "trace", skip(self, helper, bx))]
60c5eb7d 432 fn codegen_drop_terminator(
532ac7d7 433 &mut self,
60c5eb7d 434 helper: TerminatorCodegenHelper<'tcx>,
487cf647 435 bx: &mut Bx,
ba9703b0 436 location: mir::Place<'tcx>,
532ac7d7
XL
437 target: mir::BasicBlock,
438 unwind: Option<mir::BasicBlock>,
487cf647
FG
439 mergeable_succ: bool,
440 ) -> MergingSucc {
f9f354fc 441 let ty = location.ty(self.mir, bx.tcx()).ty;
fc512014 442 let ty = self.monomorphize(ty);
dc9dc135 443 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
532ac7d7
XL
444
445 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
446 // we don't actually need to drop anything.
487cf647 447 return helper.funclet_br(self, bx, target, mergeable_succ);
532ac7d7
XL
448 }
449
487cf647 450 let place = self.codegen_place(bx, location.as_ref());
532ac7d7
XL
451 let (args1, args2);
452 let mut args = if let Some(llextra) = place.llextra {
453 args2 = [place.llval, llextra];
454 &args2[..]
455 } else {
456 args1 = [place.llval];
457 &args1[..]
458 };
1b1a35ee 459 let (drop_fn, fn_abi) = match ty.kind() {
60c5eb7d
XL
460 // FIXME(eddyb) perhaps move some of this logic into
461 // `Instance::resolve_drop_in_place`?
f2b60f7d
FG
462 ty::Dynamic(_, _, ty::Dyn) => {
463 // IN THIS ARM, WE HAVE:
464 // ty = *mut (dyn Trait)
465 // which is: exists<T> ( *mut T, Vtable<T: Trait> )
466 // args[0] args[1]
467 //
468 // args = ( Data, Vtable )
469 // |
470 // v
471 // /-------\
472 // | ... |
473 // \-------/
474 //
60c5eb7d
XL
475 let virtual_drop = Instance {
476 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
477 substs: drop_fn.substs,
478 };
f2b60f7d
FG
479 debug!("ty = {:?}", ty);
480 debug!("drop_fn = {:?}", drop_fn);
481 debug!("args = {:?}", args);
c295e0f8 482 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
532ac7d7 483 let vtable = args[1];
f2b60f7d 484 // Truncate vtable off of args list
532ac7d7 485 args = &args[..1];
136023e0
XL
486 (
487 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
487cf647 488 .get_fn(bx, vtable, ty, &fn_abi),
136023e0
XL
489 fn_abi,
490 )
54a0048b 491 }
f2b60f7d
FG
492 ty::Dynamic(_, _, ty::DynStar) => {
493 // IN THIS ARM, WE HAVE:
494 // ty = *mut (dyn* Trait)
495 // which is: *mut exists<T: sizeof(T) == sizeof(usize)> (T, Vtable<T: Trait>)
496 //
497 // args = [ * ]
498 // |
499 // v
500 // ( Data, Vtable )
501 // |
502 // v
503 // /-------\
504 // | ... |
505 // \-------/
506 //
507 //
508 // WE CAN CONVERT THIS INTO THE ABOVE LOGIC BY DOING
509 //
510 // data = &(*args[0]).0 // gives a pointer to Data above (really the same pointer)
511 // vtable = (*args[0]).1 // loads the vtable out
512 // (data, vtable) // an equivalent Rust `*mut dyn Trait`
513 //
514 // SO THEN WE CAN USE THE ABOVE CODE.
515 let virtual_drop = Instance {
516 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
517 substs: drop_fn.substs,
518 };
519 debug!("ty = {:?}", ty);
520 debug!("drop_fn = {:?}", drop_fn);
521 debug!("args = {:?}", args);
522 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
523 let data = args[0];
524 let data_ty = bx.cx().backend_type(place.layout);
525 let vtable_ptr =
526 bx.gep(data_ty, data, &[bx.cx().const_i32(0), bx.cx().const_i32(1)]);
527 let vtable = bx.load(bx.type_i8p(), vtable_ptr, abi::Align::ONE);
528 // Truncate vtable off of args list
529 args = &args[..1];
530 debug!("args' = {:?}", args);
531 (
532 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
487cf647 533 .get_fn(bx, vtable, ty, &fn_abi),
f2b60f7d
FG
534 fn_abi,
535 )
536 }
c295e0f8 537 _ => (bx.get_fn_addr(drop_fn), bx.fn_abi_of_instance(drop_fn, ty::List::empty())),
532ac7d7 538 };
dfeec247
XL
539 helper.do_call(
540 self,
487cf647 541 bx,
dfeec247
XL
542 fn_abi,
543 drop_fn,
544 args,
545 Some((ReturnDest::Nothing, target)),
546 unwind,
064997fb 547 &[],
487cf647
FG
548 mergeable_succ,
549 )
532ac7d7 550 }
54a0048b 551
60c5eb7d 552 fn codegen_assert_terminator(
532ac7d7 553 &mut self,
60c5eb7d 554 helper: TerminatorCodegenHelper<'tcx>,
487cf647 555 bx: &mut Bx,
532ac7d7
XL
556 terminator: &mir::Terminator<'tcx>,
557 cond: &mir::Operand<'tcx>,
558 expected: bool,
559 msg: &mir::AssertMessage<'tcx>,
560 target: mir::BasicBlock,
561 cleanup: Option<mir::BasicBlock>,
487cf647
FG
562 mergeable_succ: bool,
563 ) -> MergingSucc {
532ac7d7 564 let span = terminator.source_info.span;
487cf647 565 let cond = self.codegen_operand(bx, cond).immediate();
532ac7d7
XL
566 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
567
568 // This case can currently arise only from functions marked
569 // with #[rustc_inherit_overflow_checks] and inlined from
570 // another crate (mostly core::num generic/#[inline] fns),
571 // while the current crate doesn't use overflow checks.
572 // NOTE: Unlike binops, negation doesn't have its own
573 // checked operation, just a comparison with the minimum
574 // value, so we have to check for the assert message.
575 if !bx.check_overflow() {
f035d41b 576 if let AssertKind::OverflowNeg(_) = *msg {
532ac7d7
XL
577 const_cond = Some(expected);
578 }
579 }
3157f602 580
532ac7d7
XL
581 // Don't codegen the panic block if success if known.
582 if const_cond == Some(expected) {
487cf647 583 return helper.funclet_br(self, bx, target, mergeable_succ);
532ac7d7
XL
584 }
585
586 // Pass the condition through llvm.expect for branch hinting.
587 let cond = bx.expect(cond, expected);
588
589 // Create the failure block and the conditional branch to it.
2b03887a 590 let lltarget = helper.llbb_with_cleanup(self, target);
5e7ed085 591 let panic_block = bx.append_sibling_block("panic");
532ac7d7 592 if expected {
5e7ed085 593 bx.cond_br(cond, lltarget, panic_block);
532ac7d7 594 } else {
5e7ed085 595 bx.cond_br(cond, panic_block, lltarget);
532ac7d7
XL
596 }
597
598 // After this point, bx is the block for the call to panic.
5e7ed085 599 bx.switch_to_block(panic_block);
487cf647 600 self.set_debug_loc(bx, terminator.source_info);
532ac7d7
XL
601
602 // Get the location information.
487cf647 603 let location = self.get_caller_location(bx, terminator.source_info).immediate();
532ac7d7
XL
604
605 // Put together the arguments to the panic entry point.
416331ca 606 let (lang_item, args) = match msg {
74b04a01 607 AssertKind::BoundsCheck { ref len, ref index } => {
487cf647
FG
608 let len = self.codegen_operand(bx, len).immediate();
609 let index = self.codegen_operand(bx, index).immediate();
ba9703b0
XL
610 // It's `fn panic_bounds_check(index: usize, len: usize)`,
611 // and `#[track_caller]` adds an implicit third argument.
3dfed10e 612 (LangItem::PanicBoundsCheck, vec![index, len, location])
532ac7d7
XL
613 }
614 _ => {
064997fb 615 let msg = bx.const_str(msg.description());
ba9703b0
XL
616 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
617 // as two arguments, and `#[track_caller]` adds an implicit third argument.
3dfed10e 618 (LangItem::Panic, vec![msg.0, msg.1, location])
3157f602 619 }
532ac7d7 620 };
3157f602 621
487cf647 622 let (fn_abi, llfn) = common::build_langcall(bx, Some(span), lang_item);
3157f602 623
532ac7d7 624 // Codegen the actual panic invoke/call.
487cf647
FG
625 let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &args, None, cleanup, &[], false);
626 assert_eq!(merging_succ, MergingSucc::False);
627 MergingSucc::False
532ac7d7 628 }
3157f602 629
5099ac24
FG
630 fn codegen_abort_terminator(
631 &mut self,
632 helper: TerminatorCodegenHelper<'tcx>,
487cf647 633 bx: &mut Bx,
5099ac24
FG
634 terminator: &mir::Terminator<'tcx>,
635 ) {
636 let span = terminator.source_info.span;
487cf647 637 self.set_debug_loc(bx, terminator.source_info);
5099ac24 638
5099ac24 639 // Obtain the panic entry point.
9c376795 640 let (fn_abi, llfn) = common::build_langcall(bx, Some(span), LangItem::PanicCannotUnwind);
5099ac24
FG
641
642 // Codegen the actual panic invoke/call.
487cf647
FG
643 let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &[], None, None, &[], false);
644 assert_eq!(merging_succ, MergingSucc::False);
5099ac24
FG
645 }
646
487cf647 647 /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
ba9703b0
XL
648 fn codegen_panic_intrinsic(
649 &mut self,
650 helper: &TerminatorCodegenHelper<'tcx>,
651 bx: &mut Bx,
3dfed10e 652 intrinsic: Option<Symbol>,
ba9703b0 653 instance: Option<Instance<'tcx>>,
29967ef6 654 source_info: mir::SourceInfo,
923072b8 655 target: Option<mir::BasicBlock>,
ba9703b0 656 cleanup: Option<mir::BasicBlock>,
487cf647
FG
657 mergeable_succ: bool,
658 ) -> Option<MergingSucc> {
ba9703b0
XL
659 // Emit a panic or a no-op for `assert_*` intrinsics.
660 // These are intrinsics that compile to panics so that we can get a message
661 // which mentions the offending type, even from a const context.
662 #[derive(Debug, PartialEq)]
663 enum AssertIntrinsic {
664 Inhabited,
665 ZeroValid,
9c376795 666 MemUninitializedValid,
fc512014 667 }
ba9703b0 668 let panic_intrinsic = intrinsic.and_then(|i| match i {
3dfed10e
XL
669 sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
670 sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
9c376795 671 sym::assert_mem_uninitialized_valid => Some(AssertIntrinsic::MemUninitializedValid),
ba9703b0
XL
672 _ => None,
673 });
674 if let Some(intrinsic) = panic_intrinsic {
675 use AssertIntrinsic::*;
064997fb 676
ba9703b0
XL
677 let ty = instance.unwrap().substs.type_at(0);
678 let layout = bx.layout_of(ty);
679 let do_panic = match intrinsic {
680 Inhabited => layout.abi.is_uninhabited(),
064997fb 681 ZeroValid => !bx.tcx().permits_zero_init(layout),
9c376795 682 MemUninitializedValid => !bx.tcx().permits_uninit_init(layout),
ba9703b0 683 };
487cf647 684 Some(if do_panic {
5e7ed085
FG
685 let msg_str = with_no_visible_paths!({
686 with_no_trimmed_paths!({
c295e0f8
XL
687 if layout.abi.is_uninhabited() {
688 // Use this error even for the other intrinsics as it is more precise.
689 format!("attempted to instantiate uninhabited type `{}`", ty)
690 } else if intrinsic == ZeroValid {
691 format!("attempted to zero-initialize type `{}`, which is invalid", ty)
692 } else {
693 format!(
694 "attempted to leave type `{}` uninitialized, which is invalid",
695 ty
696 )
697 }
698 })
1b1a35ee 699 });
064997fb 700 let msg = bx.const_str(&msg_str);
ba9703b0
XL
701
702 // Obtain the panic entry point.
04454e1e 703 let (fn_abi, llfn) =
9c376795 704 common::build_langcall(bx, Some(source_info.span), LangItem::PanicNounwind);
ba9703b0 705
ba9703b0
XL
706 // Codegen the actual panic invoke/call.
707 helper.do_call(
708 self,
709 bx,
710 fn_abi,
711 llfn,
9c376795 712 &[msg.0, msg.1],
923072b8 713 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
ba9703b0 714 cleanup,
064997fb 715 &[],
487cf647
FG
716 mergeable_succ,
717 )
ba9703b0
XL
718 } else {
719 // a NOP
923072b8 720 let target = target.unwrap();
487cf647
FG
721 helper.funclet_br(self, bx, target, mergeable_succ)
722 })
ba9703b0 723 } else {
487cf647 724 None
ba9703b0
XL
725 }
726 }
727
60c5eb7d 728 fn codegen_call_terminator(
532ac7d7 729 &mut self,
60c5eb7d 730 helper: TerminatorCodegenHelper<'tcx>,
487cf647 731 bx: &mut Bx,
532ac7d7
XL
732 terminator: &mir::Terminator<'tcx>,
733 func: &mir::Operand<'tcx>,
5869c6ff 734 args: &[mir::Operand<'tcx>],
923072b8
FG
735 destination: mir::Place<'tcx>,
736 target: Option<mir::BasicBlock>,
532ac7d7 737 cleanup: Option<mir::BasicBlock>,
f035d41b 738 fn_span: Span,
487cf647
FG
739 mergeable_succ: bool,
740 ) -> MergingSucc {
29967ef6
XL
741 let source_info = terminator.source_info;
742 let span = source_info.span;
743
532ac7d7 744 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
487cf647 745 let callee = self.codegen_operand(bx, func);
532ac7d7 746
1b1a35ee 747 let (instance, mut llfn) = match *callee.layout.ty.kind() {
dfeec247
XL
748 ty::FnDef(def_id, substs) => (
749 Some(
9c376795
FG
750 ty::Instance::expect_resolve(
751 bx.tcx(),
752 ty::ParamEnv::reveal_all(),
753 def_id,
754 substs,
755 )
756 .polymorphize(bx.tcx()),
dfeec247
XL
757 ),
758 None,
759 ),
760 ty::FnPtr(_) => (None, Some(callee.immediate())),
532ac7d7
XL
761 _ => bug!("{} is not callable", callee.layout.ty),
762 };
763 let def = instance.map(|i| i.def);
60c5eb7d
XL
764
765 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
766 // Empty drop glue; a no-op.
923072b8 767 let target = target.unwrap();
487cf647 768 return helper.funclet_br(self, bx, target, mergeable_succ);
60c5eb7d
XL
769 }
770
771 // FIXME(eddyb) avoid computing this if possible, when `instance` is
772 // available - right now `sig` is only needed for getting the `abi`
773 // and figuring out how many extra args were passed to a C-variadic `fn`.
532ac7d7 774 let sig = callee.layout.ty.fn_sig(bx.tcx());
60c5eb7d 775 let abi = sig.abi();
532ac7d7
XL
776
777 // Handle intrinsics old codegen wants Expr's for, ourselves.
778 let intrinsic = match def {
3dfed10e 779 Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
dfeec247 780 _ => None,
532ac7d7 781 };
3157f602 782
60c5eb7d 783 let extra_args = &args[sig.inputs().skip_binder().len()..];
c295e0f8
XL
784 let extra_args = bx.tcx().mk_type_list(extra_args.iter().map(|op_arg| {
785 let op_ty = op_arg.ty(self.mir, bx.tcx());
786 self.monomorphize(op_ty)
787 }));
60c5eb7d
XL
788
789 let fn_abi = match instance {
c295e0f8
XL
790 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
791 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
60c5eb7d
XL
792 };
793
3dfed10e 794 if intrinsic == Some(sym::transmute) {
487cf647
FG
795 return if let Some(target) = target {
796 self.codegen_transmute(bx, &args[0], destination);
797 helper.funclet_br(self, bx, target, mergeable_succ)
532ac7d7
XL
798 } else {
799 // If we are trying to transmute to an uninhabited type,
800 // it is likely there is no allotted destination. In fact,
801 // transmuting to an uninhabited type is UB, which means
802 // we can do what we like. Here, we declare that transmuting
803 // into an uninhabited type is impossible, so anything following
804 // it must be unreachable.
ba9703b0 805 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
532ac7d7 806 bx.unreachable();
487cf647
FG
807 MergingSucc::False
808 };
532ac7d7 809 }
3157f602 810
487cf647 811 if let Some(merging_succ) = self.codegen_panic_intrinsic(
ba9703b0 812 &helper,
487cf647 813 bx,
ba9703b0
XL
814 intrinsic,
815 instance,
29967ef6 816 source_info,
923072b8 817 target,
ba9703b0 818 cleanup,
487cf647 819 mergeable_succ,
ba9703b0 820 ) {
487cf647 821 return merging_succ;
532ac7d7 822 }
54a0048b 823
532ac7d7 824 // The arguments we'll be passing. Plus one to account for outptr, if used.
60c5eb7d 825 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
532ac7d7 826 let mut llargs = Vec::with_capacity(arg_count);
3157f602 827
532ac7d7 828 // Prepare the return value destination
923072b8 829 let ret_dest = if target.is_some() {
532ac7d7 830 let is_intrinsic = intrinsic.is_some();
487cf647 831 self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs, is_intrinsic)
532ac7d7
XL
832 } else {
833 ReturnDest::Nothing
834 };
54a0048b 835
3dfed10e 836 if intrinsic == Some(sym::caller_location) {
487cf647
FG
837 return if let Some(target) = target {
838 let location =
839 self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
e74abb32
XL
840
841 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
487cf647 842 location.val.store(bx, tmp);
e74abb32 843 }
487cf647
FG
844 self.store_return(bx, ret_dest, &fn_abi.ret, location.immediate());
845 helper.funclet_br(self, bx, target, mergeable_succ)
846 } else {
847 MergingSucc::False
848 };
e74abb32
XL
849 }
850
6a06907d
XL
851 match intrinsic {
852 None | Some(sym::drop_in_place) => {}
853 Some(sym::copy_nonoverlapping) => unreachable!(),
854 Some(intrinsic) => {
855 let dest = match ret_dest {
856 _ if fn_abi.ret.is_indirect() => llargs[0],
857 ReturnDest::Nothing => {
858 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
859 }
860 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
861 ReturnDest::DirectOperand(_) => {
862 bug!("Cannot use direct operand with an intrinsic call")
863 }
864 };
54a0048b 865
6a06907d
XL
866 let args: Vec<_> = args
867 .iter()
868 .enumerate()
869 .map(|(i, arg)| {
870 // The indices passed to simd_shuffle* in the
871 // third argument must be constant. This is
872 // checked by const-qualification, which also
873 // promotes any complex rvalues to constants.
874 if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
875 if let mir::Operand::Constant(constant) = arg {
876 let c = self.eval_mir_constant(constant);
c295e0f8
XL
877 let (llval, ty) = self.simd_shuffle_indices(
878 &bx,
879 constant.span,
880 self.monomorphize(constant.ty()),
881 c,
882 );
6a06907d
XL
883 return OperandRef {
884 val: Immediate(llval),
885 layout: bx.layout_of(ty),
886 };
887 } else {
888 span_bug!(span, "shuffle indices must be constant");
889 }
532ac7d7 890 }
54a0048b 891
487cf647 892 self.codegen_operand(bx, arg)
6a06907d
XL
893 })
894 .collect();
895
896 Self::codegen_intrinsic_call(
487cf647 897 bx,
6a06907d
XL
898 *instance.as_ref().unwrap(),
899 &fn_abi,
900 &args,
901 dest,
902 span,
903 );
dfeec247 904
6a06907d 905 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
487cf647 906 self.store_return(bx, ret_dest, &fn_abi.ret, dst.llval);
6a06907d 907 }
532ac7d7 908
487cf647
FG
909 return if let Some(target) = target {
910 helper.funclet_br(self, bx, target, mergeable_succ)
6a06907d
XL
911 } else {
912 bx.unreachable();
487cf647
FG
913 MergingSucc::False
914 };
532ac7d7 915 }
532ac7d7
XL
916 }
917
918 // Split the rust-call tupled arguments off.
919 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
920 let (tup, args) = args.split_last().unwrap();
921 (args, Some(tup))
922 } else {
6a06907d 923 (args, None)
532ac7d7
XL
924 };
925
064997fb 926 let mut copied_constant_arguments = vec![];
532ac7d7 927 'make_args: for (i, arg) in first_args.iter().enumerate() {
487cf647 928 let mut op = self.codegen_operand(bx, arg);
532ac7d7
XL
929
930 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
f2b60f7d
FG
931 match op.val {
932 Pair(data_ptr, meta) => {
933 // In the case of Rc<Self>, we need to explicitly pass a
934 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
935 // that is understood elsewhere in the compiler as a method on
936 // `dyn Trait`.
937 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
487cf647
FG
938 // we get a value of a built-in pointer type.
939 //
940 // This is also relevant for `Pin<&mut Self>`, where we need to peel the `Pin`.
f2b60f7d
FG
941 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
942 && !op.layout.ty.is_region_ptr()
943 {
944 for i in 0..op.layout.fields.count() {
487cf647 945 let field = op.extract_field(bx, i);
f2b60f7d
FG
946 if !field.layout.is_zst() {
947 // we found the one non-zero-sized field that is allowed
948 // now find *its* non-zero-sized field, or stop if it's a
949 // pointer
950 op = field;
951 continue 'descend_newtypes;
952 }
532ac7d7 953 }
f2b60f7d
FG
954
955 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
532ac7d7
XL
956 }
957
f2b60f7d
FG
958 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
959 // data pointer and vtable. Look up the method in the vtable, and pass
960 // the data pointer as the first argument
961 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
487cf647 962 bx,
f2b60f7d
FG
963 meta,
964 op.layout.ty,
965 &fn_abi,
966 ));
967 llargs.push(data_ptr);
968 continue 'make_args;
32a655c1 969 }
f2b60f7d
FG
970 Ref(data_ptr, Some(meta), _) => {
971 // by-value dynamic dispatch
972 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
487cf647 973 bx,
f2b60f7d
FG
974 meta,
975 op.layout.ty,
976 &fn_abi,
977 ));
978 llargs.push(data_ptr);
979 continue;
980 }
981 Immediate(_) => {
487cf647
FG
982 // See comment above explaining why we peel these newtypes
983 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
984 && !op.layout.ty.is_region_ptr()
985 {
986 for i in 0..op.layout.fields.count() {
987 let field = op.extract_field(bx, i);
988 if !field.layout.is_zst() {
989 // we found the one non-zero-sized field that is allowed
990 // now find *its* non-zero-sized field, or stop if it's a
991 // pointer
992 op = field;
993 continue 'descend_newtypes;
994 }
995 }
996
997 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
998 }
999
1000 // Make sure that we've actually unwrapped the rcvr down
1001 // to a pointer or ref to `dyn* Trait`.
1002 if !op.layout.ty.builtin_deref(true).unwrap().ty.is_dyn_star() {
f2b60f7d 1003 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
532ac7d7 1004 }
f2b60f7d 1005 let place = op.deref(bx.cx());
487cf647
FG
1006 let data_ptr = place.project_field(bx, 0);
1007 let meta_ptr = place.project_field(bx, 1);
f2b60f7d
FG
1008 let meta = bx.load_operand(meta_ptr);
1009 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
487cf647 1010 bx,
f2b60f7d
FG
1011 meta.immediate(),
1012 op.layout.ty,
1013 &fn_abi,
1014 ));
1015 llargs.push(data_ptr.llval);
1016 continue;
1017 }
1018 _ => {
1019 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
0731742a 1020 }
0bf4aa26 1021 }
532ac7d7 1022 }
0bf4aa26 1023
532ac7d7
XL
1024 // The callee needs to own the argument memory if we pass it
1025 // by-ref, so make a local copy of non-immediate constants.
1026 match (arg, op.val) {
dfeec247
XL
1027 (&mir::Operand::Copy(_), Ref(_, None, _))
1028 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
487cf647 1029 let tmp = PlaceRef::alloca(bx, op.layout);
064997fb 1030 bx.lifetime_start(tmp.llval, tmp.layout.size);
487cf647 1031 op.val.store(bx, tmp);
532ac7d7 1032 op.val = Ref(tmp.llval, None, tmp.align);
064997fb 1033 copied_constant_arguments.push(tmp);
532ac7d7
XL
1034 }
1035 _ => {}
1036 }
54a0048b 1037
487cf647 1038 self.codegen_argument(bx, op, &mut llargs, &fn_abi.args[i]);
532ac7d7 1039 }
c295e0f8 1040 let num_untupled = untuple.map(|tup| {
487cf647 1041 self.codegen_arguments_untupled(bx, tup, &mut llargs, &fn_abi.args[first_args.len()..])
c295e0f8 1042 });
60c5eb7d
XL
1043
1044 let needs_location =
1045 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
1046 if needs_location {
c295e0f8
XL
1047 let mir_args = if let Some(num_untupled) = num_untupled {
1048 first_args.len() + num_untupled
1049 } else {
1050 args.len()
1051 };
60c5eb7d 1052 assert_eq!(
dfeec247 1053 fn_abi.args.len(),
c295e0f8
XL
1054 mir_args + 1,
1055 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}",
1056 instance,
1057 fn_span,
1058 fn_abi,
60c5eb7d 1059 );
29967ef6 1060 let location =
487cf647 1061 self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
f035d41b
XL
1062 debug!(
1063 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1064 terminator, location, fn_span
1065 );
1066
60c5eb7d 1067 let last_arg = fn_abi.args.last().unwrap();
487cf647 1068 self.codegen_argument(bx, location, &mut llargs, last_arg);
532ac7d7 1069 }
54a0048b 1070
3c0e092e
XL
1071 let (is_indirect_call, fn_ptr) = match (llfn, instance) {
1072 (Some(llfn), _) => (true, llfn),
1073 (None, Some(instance)) => (false, bx.get_fn_addr(instance)),
532ac7d7
XL
1074 _ => span_bug!(span, "no llfn for call"),
1075 };
54a0048b 1076
3c0e092e
XL
1077 // For backends that support CFI using type membership (i.e., testing whether a given
1078 // pointer is associated with a type identifier).
1079 if bx.tcx().sess.is_sanitizer_cfi_enabled() && is_indirect_call {
1080 // Emit type metadata and checks.
1081 // FIXME(rcvalle): Add support for generalized identifiers.
1082 // FIXME(rcvalle): Create distinct unnamed MDNodes for internal identifiers.
1083 let typeid = typeid_for_fnabi(bx.tcx(), fn_abi);
064997fb 1084 let typeid_metadata = self.cx.typeid_metadata(typeid);
3c0e092e
XL
1085
1086 // Test whether the function pointer is associated with the type identifier.
1087 let cond = bx.type_test(fn_ptr, typeid_metadata);
5e7ed085
FG
1088 let bb_pass = bx.append_sibling_block("type_test.pass");
1089 let bb_fail = bx.append_sibling_block("type_test.fail");
1090 bx.cond_br(cond, bb_pass, bb_fail);
3c0e092e 1091
5e7ed085 1092 bx.switch_to_block(bb_pass);
487cf647 1093 let merging_succ = helper.do_call(
3c0e092e 1094 self,
487cf647 1095 bx,
3c0e092e
XL
1096 fn_abi,
1097 fn_ptr,
1098 &llargs,
923072b8 1099 target.as_ref().map(|&target| (ret_dest, target)),
3c0e092e 1100 cleanup,
064997fb 1101 &copied_constant_arguments,
487cf647 1102 false,
3c0e092e 1103 );
487cf647 1104 assert_eq!(merging_succ, MergingSucc::False);
3c0e092e 1105
5e7ed085
FG
1106 bx.switch_to_block(bb_fail);
1107 bx.abort();
1108 bx.unreachable();
3c0e092e 1109
487cf647 1110 return MergingSucc::False;
3c0e092e
XL
1111 }
1112
dfeec247
XL
1113 helper.do_call(
1114 self,
487cf647 1115 bx,
dfeec247
XL
1116 fn_abi,
1117 fn_ptr,
1118 &llargs,
923072b8 1119 target.as_ref().map(|&target| (ret_dest, target)),
dfeec247 1120 cleanup,
064997fb 1121 &copied_constant_arguments,
487cf647
FG
1122 mergeable_succ,
1123 )
532ac7d7 1124 }
f9f354fc
XL
1125
1126 fn codegen_asm_terminator(
1127 &mut self,
1128 helper: TerminatorCodegenHelper<'tcx>,
487cf647 1129 bx: &mut Bx,
f9f354fc
XL
1130 terminator: &mir::Terminator<'tcx>,
1131 template: &[ast::InlineAsmTemplatePiece],
1132 operands: &[mir::InlineAsmOperand<'tcx>],
1133 options: ast::InlineAsmOptions,
1134 line_spans: &[Span],
1135 destination: Option<mir::BasicBlock>,
a2a8927a 1136 cleanup: Option<mir::BasicBlock>,
3c0e092e 1137 instance: Instance<'_>,
487cf647
FG
1138 mergeable_succ: bool,
1139 ) -> MergingSucc {
f9f354fc
XL
1140 let span = terminator.source_info.span;
1141
1142 let operands: Vec<_> = operands
1143 .iter()
1144 .map(|op| match *op {
1145 mir::InlineAsmOperand::In { reg, ref value } => {
487cf647 1146 let value = self.codegen_operand(bx, value);
f9f354fc
XL
1147 InlineAsmOperandRef::In { reg, value }
1148 }
1149 mir::InlineAsmOperand::Out { reg, late, ref place } => {
487cf647 1150 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
f9f354fc
XL
1151 InlineAsmOperandRef::Out { reg, late, place }
1152 }
1153 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
487cf647 1154 let in_value = self.codegen_operand(bx, in_value);
f9f354fc 1155 let out_place =
487cf647 1156 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
f9f354fc
XL
1157 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1158 }
1159 mir::InlineAsmOperand::Const { ref value } => {
cdc7bbd5
XL
1160 let const_value = self
1161 .eval_mir_constant(value)
1162 .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
17df50a5
XL
1163 let string = common::asm_const_to_str(
1164 bx.tcx(),
1165 span,
1166 const_value,
1167 bx.layout_of(value.ty()),
1168 );
cdc7bbd5 1169 InlineAsmOperandRef::Const { string }
f9f354fc
XL
1170 }
1171 mir::InlineAsmOperand::SymFn { ref value } => {
fc512014 1172 let literal = self.monomorphize(value.literal);
6a06907d 1173 if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
f9f354fc
XL
1174 let instance = ty::Instance::resolve_for_fn_ptr(
1175 bx.tcx(),
1176 ty::ParamEnv::reveal_all(),
1177 def_id,
1178 substs,
1179 )
1180 .unwrap();
1181 InlineAsmOperandRef::SymFn { instance }
1182 } else {
1183 span_bug!(span, "invalid type for asm sym (fn)");
1184 }
1185 }
f035d41b
XL
1186 mir::InlineAsmOperand::SymStatic { def_id } => {
1187 InlineAsmOperandRef::SymStatic { def_id }
f9f354fc
XL
1188 }
1189 })
1190 .collect();
1191
a2a8927a
XL
1192 helper.do_inlineasm(
1193 self,
487cf647 1194 bx,
a2a8927a
XL
1195 template,
1196 &operands,
1197 options,
1198 line_spans,
1199 destination,
1200 cleanup,
1201 instance,
487cf647
FG
1202 mergeable_succ,
1203 )
f9f354fc 1204 }
532ac7d7 1205}
ff7c6d11 1206
dc9dc135 1207impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
487cf647
FG
1208 pub fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1209 let llbb = match self.try_llbb(bb) {
1210 Some(llbb) => llbb,
1211 None => return,
1212 };
1213 let bx = &mut Bx::build(self.cx, llbb);
60c5eb7d 1214 let mir = self.mir;
ff7c6d11 1215
487cf647
FG
1216 // MIR basic blocks stop at any function call. This may not be the case
1217 // for the backend's basic blocks, in which case we might be able to
1218 // combine multiple MIR basic blocks into a single backend basic block.
1219 loop {
1220 let data = &mir[bb];
ff7c6d11 1221
487cf647
FG
1222 debug!("codegen_block({:?}={:?})", bb, data);
1223
1224 for statement in &data.statements {
1225 self.codegen_statement(bx, statement);
1226 }
cc61c64b 1227
487cf647
FG
1228 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1229 if let MergingSucc::False = merging_succ {
1230 break;
1231 }
1232
1233 // We are merging the successor into the produced backend basic
1234 // block. Record that the successor should be skipped when it is
1235 // reached.
1236 //
1237 // Note: we must not have already generated code for the successor.
1238 // This is implicitly ensured by the reverse postorder traversal,
1239 // and the assertion explicitly guarantees that.
1240 let mut successors = data.terminator().successors();
1241 let succ = successors.next().unwrap();
1242 assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1243 self.cached_llbbs[succ] = CachedLlbb::Skip;
1244 bb = succ;
1245 }
532ac7d7 1246 }
cc61c64b 1247
532ac7d7
XL
1248 fn codegen_terminator(
1249 &mut self,
487cf647 1250 bx: &mut Bx,
532ac7d7 1251 bb: mir::BasicBlock,
dfeec247 1252 terminator: &'tcx mir::Terminator<'tcx>,
487cf647 1253 ) -> MergingSucc {
532ac7d7 1254 debug!("codegen_terminator: {:?}", terminator);
cc61c64b 1255
532ac7d7
XL
1256 // Create the cleanup bundle, if needed.
1257 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
dfeec247 1258 let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
cc61c64b 1259
487cf647
FG
1260 let mergeable_succ = || {
1261 // Note: any call to `switch_to_block` will invalidate a `true` value
1262 // of `mergeable_succ`.
1263 let mut successors = terminator.successors();
1264 if let Some(succ) = successors.next()
1265 && successors.next().is_none()
1266 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1267 {
1268 // bb has a single successor, and bb is its only predecessor. This
1269 // makes it a candidate for merging.
1270 assert_eq!(succ_pred, bb);
1271 true
1272 } else {
1273 false
1274 }
1275 };
1276
1277 self.set_debug_loc(bx, terminator.source_info);
532ac7d7 1278 match terminator.kind {
487cf647
FG
1279 mir::TerminatorKind::Resume => {
1280 self.codegen_resume_terminator(helper, bx);
1281 MergingSucc::False
1282 }
ff7c6d11 1283
532ac7d7 1284 mir::TerminatorKind::Abort => {
5099ac24 1285 self.codegen_abort_terminator(helper, bx, terminator);
487cf647 1286 MergingSucc::False
532ac7d7 1287 }
a1dfa0c6 1288
532ac7d7 1289 mir::TerminatorKind::Goto { target } => {
487cf647 1290 helper.funclet_br(self, bx, target, mergeable_succ())
532ac7d7 1291 }
ff7c6d11 1292
9c376795
FG
1293 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1294 self.codegen_switchint_terminator(helper, bx, discr, targets);
487cf647 1295 MergingSucc::False
532ac7d7 1296 }
ff7c6d11 1297
532ac7d7
XL
1298 mir::TerminatorKind::Return => {
1299 self.codegen_return_terminator(bx);
487cf647 1300 MergingSucc::False
532ac7d7 1301 }
ff7c6d11 1302
532ac7d7
XL
1303 mir::TerminatorKind::Unreachable => {
1304 bx.unreachable();
487cf647 1305 MergingSucc::False
532ac7d7 1306 }
54a0048b 1307
f035d41b 1308 mir::TerminatorKind::Drop { place, target, unwind } => {
487cf647 1309 self.codegen_drop_terminator(helper, bx, place, target, unwind, mergeable_succ())
532ac7d7
XL
1310 }
1311
487cf647
FG
1312 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => self
1313 .codegen_assert_terminator(
1314 helper,
1315 bx,
1316 terminator,
1317 cond,
1318 expected,
1319 msg,
1320 target,
1321 cleanup,
1322 mergeable_succ(),
1323 ),
532ac7d7
XL
1324
1325 mir::TerminatorKind::DropAndReplace { .. } => {
1326 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1327 }
1328
1329 mir::TerminatorKind::Call {
1330 ref func,
1331 ref args,
923072b8
FG
1332 destination,
1333 target,
532ac7d7 1334 cleanup,
dfeec247 1335 from_hir_call: _,
f035d41b 1336 fn_span,
487cf647
FG
1337 } => self.codegen_call_terminator(
1338 helper,
1339 bx,
1340 terminator,
1341 func,
1342 args,
1343 destination,
1344 target,
1345 cleanup,
1346 fn_span,
1347 mergeable_succ(),
1348 ),
dfeec247
XL
1349 mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1350 bug!("generator ops in codegen")
1351 }
f035d41b 1352 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
dfeec247 1353 bug!("borrowck false edges in codegen")
54a0048b 1354 }
f9f354fc
XL
1355
1356 mir::TerminatorKind::InlineAsm {
1357 template,
1358 ref operands,
1359 options,
1360 line_spans,
1361 destination,
a2a8927a 1362 cleanup,
487cf647
FG
1363 } => self.codegen_asm_terminator(
1364 helper,
1365 bx,
1366 terminator,
1367 template,
1368 operands,
1369 options,
1370 line_spans,
1371 destination,
1372 cleanup,
1373 self.instance,
1374 mergeable_succ(),
1375 ),
54a0048b
SL
1376 }
1377 }
1378
a1dfa0c6
XL
1379 fn codegen_argument(
1380 &mut self,
1381 bx: &mut Bx,
1382 op: OperandRef<'tcx, Bx::Value>,
1383 llargs: &mut Vec<Bx::Value>,
dfeec247 1384 arg: &ArgAbi<'tcx, Ty<'tcx>>,
a1dfa0c6 1385 ) {
f2b60f7d
FG
1386 match arg.mode {
1387 PassMode::Ignore => return,
1388 PassMode::Cast(_, true) => {
1389 // Fill padding with undef value, where applicable.
1390 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1391 }
1392 PassMode::Pair(..) => match op.val {
ff7c6d11
XL
1393 Pair(a, b) => {
1394 llargs.push(a);
1395 llargs.push(b);
1396 return;
1397 }
dfeec247 1398 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
f2b60f7d
FG
1399 },
1400 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => match op.val {
b7449926
XL
1401 Ref(a, Some(b), _) => {
1402 llargs.push(a);
1403 llargs.push(b);
1404 return;
1405 }
dfeec247 1406 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
f2b60f7d
FG
1407 },
1408 _ => {}
ff7c6d11
XL
1409 }
1410
54a0048b 1411 // Force by-ref if we have to load through a cast pointer.
32a655c1 1412 let (mut llval, align, by_ref) = match op.val {
dfeec247 1413 Immediate(_) | Pair(..) => match arg.mode {
f2b60f7d 1414 PassMode::Indirect { .. } | PassMode::Cast(..) => {
dfeec247
XL
1415 let scratch = PlaceRef::alloca(bx, arg.layout);
1416 op.val.store(bx, scratch);
1417 (scratch.llval, scratch.align, true)
3157f602 1418 }
dfeec247
XL
1419 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1420 },
b7449926 1421 Ref(llval, _, align) => {
a1dfa0c6 1422 if arg.is_indirect() && align < arg.layout.align.abi {
ff7c6d11
XL
1423 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1424 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1425 // have scary latent bugs around.
1426
e1599b0c 1427 let scratch = PlaceRef::alloca(bx, arg.layout);
dfeec247
XL
1428 base::memcpy_ty(
1429 bx,
1430 scratch.llval,
1431 scratch.align,
1432 llval,
1433 align,
1434 op.layout,
1435 MemFlags::empty(),
1436 );
ff7c6d11
XL
1437 (scratch.llval, scratch.align, true)
1438 } else {
1439 (llval, align, true)
1440 }
32a655c1 1441 }
54a0048b
SL
1442 };
1443
1444 if by_ref && !arg.is_indirect() {
1445 // Have to load the argument, maybe while casting it.
f2b60f7d
FG
1446 if let PassMode::Cast(ty, _) = &arg.mode {
1447 let llty = bx.cast_backend_type(ty);
136023e0
XL
1448 let addr = bx.pointercast(llval, bx.type_ptr_to(llty));
1449 llval = bx.load(llty, addr, align.min(arg.layout.align.abi));
54a0048b 1450 } else {
ff7c6d11
XL
1451 // We can't use `PlaceRef::load` here because the argument
1452 // may have a type we don't treat as immediate, but the ABI
1453 // used for this call is passing it by-value. In that case,
1454 // the load would just produce `OperandValue::Ref` instead
1455 // of the `OperandValue::Immediate` we need for the call.
136023e0 1456 llval = bx.load(bx.backend_type(arg.layout), llval, align);
c295e0f8 1457 if let abi::Abi::Scalar(scalar) = arg.layout.abi {
ff7c6d11 1458 if scalar.is_bool() {
c295e0f8 1459 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
ff7c6d11
XL
1460 }
1461 }
dc9dc135 1462 // We store bools as `i8` so we need to truncate to `i1`.
1b1a35ee 1463 llval = bx.to_immediate(llval, arg.layout);
54a0048b
SL
1464 }
1465 }
1466
1467 llargs.push(llval);
1468 }
1469
a1dfa0c6
XL
1470 fn codegen_arguments_untupled(
1471 &mut self,
1472 bx: &mut Bx,
1473 operand: &mir::Operand<'tcx>,
1474 llargs: &mut Vec<Bx::Value>,
dfeec247 1475 args: &[ArgAbi<'tcx, Ty<'tcx>>],
c295e0f8 1476 ) -> usize {
94b46f34 1477 let tuple = self.codegen_operand(bx, operand);
54a0048b 1478
a7813a04 1479 // Handle both by-ref and immediate tuples.
b7449926 1480 if let Ref(llval, None, align) = tuple.val {
e1599b0c 1481 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
ff7c6d11 1482 for i in 0..tuple.layout.fields.count() {
2c00a5a8 1483 let field_ptr = tuple_ptr.project_field(bx, i);
a1dfa0c6
XL
1484 let field = bx.load_operand(field_ptr);
1485 self.codegen_argument(bx, field, llargs, &args[i]);
3157f602 1486 }
b7449926
XL
1487 } else if let Ref(_, Some(_), _) = tuple.val {
1488 bug!("closure arguments must be sized")
ff7c6d11
XL
1489 } else {
1490 // If the tuple is immediate, the elements are as well.
1491 for i in 0..tuple.layout.fields.count() {
2c00a5a8 1492 let op = tuple.extract_field(bx, i);
94b46f34 1493 self.codegen_argument(bx, op, llargs, &args[i]);
a7813a04 1494 }
54a0048b 1495 }
c295e0f8 1496 tuple.layout.fields.count()
54a0048b
SL
1497 }
1498
29967ef6
XL
1499 fn get_caller_location(
1500 &mut self,
1501 bx: &mut Bx,
1502 mut source_info: mir::SourceInfo,
1503 ) -> OperandRef<'tcx, Bx::Value> {
1504 let tcx = bx.tcx();
1505
1506 let mut span_to_caller_location = |span: Span| {
60c5eb7d 1507 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
29967ef6
XL
1508 let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1509 let const_loc = tcx.const_caller_location((
17df50a5 1510 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
60c5eb7d
XL
1511 caller.line as u32,
1512 caller.col_display as u32 + 1,
1513 ));
74b04a01 1514 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
29967ef6
XL
1515 };
1516
1517 // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1518 // If so, the starting `source_info.span` is in the innermost inlined
1519 // function, and will be replaced with outer callsite spans as long
1520 // as the inlined functions were `#[track_caller]`.
1521 loop {
1522 let scope_data = &self.mir.source_scopes[source_info.scope];
1523
1524 if let Some((callee, callsite_span)) = scope_data.inlined {
1525 // Stop inside the most nested non-`#[track_caller]` function,
1526 // before ever reaching its caller (which is irrelevant).
1527 if !callee.def.requires_caller_location(tcx) {
1528 return span_to_caller_location(source_info.span);
1529 }
1530 source_info.span = callsite_span;
1531 }
1532
1533 // Skip past all of the parents with `inlined: None`.
1534 match scope_data.inlined_parent_scope {
1535 Some(parent) => source_info.scope = parent,
1536 None => break,
1537 }
1538 }
1539
1540 // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1541 self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
e74abb32
XL
1542 }
1543
dfeec247 1544 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
a1dfa0c6 1545 let cx = bx.cx();
ff7c6d11 1546 if let Some(slot) = self.personality_slot {
54a0048b
SL
1547 slot
1548 } else {
dfeec247
XL
1549 let layout = cx.layout_of(
1550 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1551 );
e1599b0c 1552 let slot = PlaceRef::alloca(bx, layout);
ff7c6d11 1553 self.personality_slot = Some(slot);
32a655c1 1554 slot
54a0048b
SL
1555 }
1556 }
1557
17df50a5
XL
1558 /// Returns the landing/cleanup pad wrapper around the given basic block.
1559 // FIXME(eddyb) rename this to `eh_pad_for`.
1560 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1561 if let Some(landing_pad) = self.landing_pads[bb] {
1562 return landing_pad;
3157f602
XL
1563 }
1564
17df50a5
XL
1565 let landing_pad = self.landing_pad_for_uncached(bb);
1566 self.landing_pads[bb] = Some(landing_pad);
cc61c64b
XL
1567 landing_pad
1568 }
1569
17df50a5
XL
1570 // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1571 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1572 let llbb = self.llbb(bb);
2c00a5a8 1573 if base::wants_msvc_seh(self.cx.sess()) {
17df50a5
XL
1574 let funclet;
1575 let ret_llbb;
1576 match self.mir[bb].terminator.as_ref().map(|t| &t.kind) {
1577 // This is a basic block that we're aborting the program for,
1578 // notably in an `extern` function. These basic blocks are inserted
1579 // so that we assert that `extern` functions do indeed not panic,
1580 // and if they do we abort the process.
1581 //
1582 // On MSVC these are tricky though (where we're doing funclets). If
1583 // we were to do a cleanuppad (like below) the normal functions like
1584 // `longjmp` would trigger the abort logic, terminating the
1585 // program. Instead we insert the equivalent of `catch(...)` for C++
1586 // which magically doesn't trigger when `longjmp` files over this
1587 // frame.
1588 //
1589 // Lots more discussion can be found on #48251 but this codegen is
1590 // modeled after clang's for:
1591 //
1592 // try {
1593 // foo();
1594 // } catch (...) {
1595 // bar();
1596 // }
1597 Some(&mir::TerminatorKind::Abort) => {
2b03887a 1598 let cs_llbb =
5e7ed085 1599 Bx::append_block(self.cx, self.llfn, &format!("cs_funclet{:?}", bb));
2b03887a 1600 let cp_llbb =
5e7ed085 1601 Bx::append_block(self.cx, self.llfn, &format!("cp_funclet{:?}", bb));
2b03887a 1602 ret_llbb = cs_llbb;
17df50a5 1603
2b03887a
FG
1604 let mut cs_bx = Bx::build(self.cx, cs_llbb);
1605 let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
17df50a5
XL
1606
1607 // The "null" here is actually a RTTI type descriptor for the
1608 // C++ personality function, but `catch (...)` has no type so
1609 // it's null. The 64 here is actually a bitfield which
1610 // represents that this is a catch-all block.
2b03887a 1611 let mut cp_bx = Bx::build(self.cx, cp_llbb);
17df50a5
XL
1612 let null = cp_bx.const_null(
1613 cp_bx.type_i8p_ext(cp_bx.cx().data_layout().instruction_address_space),
1614 );
1615 let sixty_four = cp_bx.const_i32(64);
1616 funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
1617 cp_bx.br(llbb);
1618 }
1619 _ => {
2b03887a 1620 let cleanup_llbb =
5e7ed085 1621 Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb));
2b03887a
FG
1622 ret_llbb = cleanup_llbb;
1623 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
17df50a5
XL
1624 funclet = cleanup_bx.cleanup_pad(None, &[]);
1625 cleanup_bx.br(llbb);
1626 }
1627 }
1628 self.funclets[bb] = Some(funclet);
1629 ret_llbb
1630 } else {
2b03887a
FG
1631 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1632 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
3157f602 1633
17df50a5 1634 let llpersonality = self.cx.eh_personality();
9c376795 1635 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
ff7c6d11 1636
2b03887a
FG
1637 let slot = self.get_personality_slot(&mut cleanup_bx);
1638 slot.storage_live(&mut cleanup_bx);
9c376795 1639 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
ff7c6d11 1640
2b03887a
FG
1641 cleanup_bx.br(llbb);
1642 cleanup_llbb
17df50a5 1643 }
54a0048b
SL
1644 }
1645
dfeec247 1646 fn unreachable_block(&mut self) -> Bx::BasicBlock {
54a0048b 1647 self.unreachable_block.unwrap_or_else(|| {
5e7ed085
FG
1648 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1649 let mut bx = Bx::build(self.cx, llbb);
a1dfa0c6 1650 bx.unreachable();
5e7ed085
FG
1651 self.unreachable_block = Some(llbb);
1652 llbb
54a0048b
SL
1653 })
1654 }
1655
5e7ed085
FG
1656 fn double_unwind_guard(&mut self) -> Bx::BasicBlock {
1657 self.double_unwind_guard.unwrap_or_else(|| {
1658 assert!(!base::wants_msvc_seh(self.cx.sess()));
1659
1660 let llbb = Bx::append_block(self.cx, self.llfn, "abort");
1661 let mut bx = Bx::build(self.cx, llbb);
1662 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1663
1664 let llpersonality = self.cx.eh_personality();
9c376795 1665 bx.cleanup_landing_pad(llpersonality);
5e7ed085 1666
9c376795 1667 let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, LangItem::PanicCannotUnwind);
5e7ed085
FG
1668 let fn_ty = bx.fn_decl_backend_type(&fn_abi);
1669
2b03887a 1670 let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &[], None);
5e7ed085
FG
1671 bx.do_not_inline(llret);
1672
1673 bx.unreachable();
1674
1675 self.double_unwind_guard = Some(llbb);
1676 llbb
1677 })
17df50a5
XL
1678 }
1679
1680 /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1681 /// cached in `self.cached_llbbs`, or created on demand (and cached).
1682 // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1683 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1684 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
487cf647
FG
1685 self.try_llbb(bb).unwrap()
1686 }
1687
1688 /// Like `llbb`, but may fail if the basic block should be skipped.
1689 pub fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1690 match self.cached_llbbs[bb] {
1691 CachedLlbb::None => {
1692 // FIXME(eddyb) only name the block if `fewer_names` is `false`.
1693 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb));
1694 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1695 Some(llbb)
1696 }
1697 CachedLlbb::Some(llbb) => Some(llbb),
1698 CachedLlbb::Skip => None,
1699 }
32a655c1
SL
1700 }
1701
a1dfa0c6
XL
1702 fn make_return_dest(
1703 &mut self,
1704 bx: &mut Bx,
ba9703b0 1705 dest: mir::Place<'tcx>,
60c5eb7d 1706 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
dfeec247
XL
1707 llargs: &mut Vec<Bx::Value>,
1708 is_intrinsic: bool,
a1dfa0c6 1709 ) -> ReturnDest<'tcx, Bx::Value> {
dc9dc135 1710 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
ff7c6d11 1711 if fn_ret.is_ignore() {
54a0048b
SL
1712 return ReturnDest::Nothing;
1713 }
e74abb32 1714 let dest = if let Some(index) = dest.as_local() {
3157f602 1715 match self.locals[index] {
ff7c6d11 1716 LocalRef::Place(dest) => dest,
b7449926 1717 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
3157f602 1718 LocalRef::Operand(None) => {
dc9dc135
XL
1719 // Handle temporary places, specifically `Operand` ones, as
1720 // they don't have `alloca`s.
ff7c6d11 1721 return if fn_ret.is_indirect() {
3157f602
XL
1722 // Odd, but possible, case, we have an operand temporary,
1723 // but the calling convention has an indirect return.
e1599b0c 1724 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2c00a5a8 1725 tmp.storage_live(bx);
32a655c1 1726 llargs.push(tmp.llval);
ff7c6d11 1727 ReturnDest::IndirectOperand(tmp, index)
3157f602
XL
1728 } else if is_intrinsic {
1729 // Currently, intrinsics always need a location to store
dc9dc135
XL
1730 // the result, so we create a temporary `alloca` for the
1731 // result.
e1599b0c 1732 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2c00a5a8 1733 tmp.storage_live(bx);
ff7c6d11 1734 ReturnDest::IndirectOperand(tmp, index)
3157f602
XL
1735 } else {
1736 ReturnDest::DirectOperand(index)
1737 };
1738 }
1739 LocalRef::Operand(Some(_)) => {
ff7c6d11 1740 bug!("place local already assigned to");
54a0048b
SL
1741 }
1742 }
3157f602 1743 } else {
dfeec247
XL
1744 self.codegen_place(
1745 bx,
74b04a01 1746 mir::PlaceRef { local: dest.local, projection: &dest.projection },
dfeec247 1747 )
54a0048b 1748 };
ff7c6d11 1749 if fn_ret.is_indirect() {
a1dfa0c6 1750 if dest.align < dest.layout.align.abi {
ff7c6d11
XL
1751 // Currently, MIR code generation does not create calls
1752 // that store directly to fields of packed structs (in
dc9dc135 1753 // fact, the calls it creates write only to temps).
ff7c6d11
XL
1754 //
1755 // If someone changes that, please update this code path
1756 // to create a temporary.
1757 span_bug!(self.mir.span, "can't directly store to unaligned value");
8bb4bdeb 1758 }
ff7c6d11
XL
1759 llargs.push(dest.llval);
1760 ReturnDest::Nothing
54a0048b 1761 } else {
ff7c6d11 1762 ReturnDest::Store(dest)
54a0048b
SL
1763 }
1764 }
1765
ba9703b0 1766 fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
e74abb32 1767 if let Some(index) = dst.as_local() {
32a655c1 1768 match self.locals[index] {
94b46f34 1769 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
b7449926 1770 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
32a655c1 1771 LocalRef::Operand(None) => {
74b04a01 1772 let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
5099ac24 1773 assert!(!dst_layout.ty.has_erasable_regions());
e1599b0c 1774 let place = PlaceRef::alloca(bx, dst_layout);
2c00a5a8 1775 place.storage_live(bx);
94b46f34 1776 self.codegen_transmute_into(bx, src, place);
a1dfa0c6 1777 let op = bx.load_operand(place);
2c00a5a8 1778 place.storage_dead(bx);
32a655c1 1779 self.locals[index] = LocalRef::Operand(Some(op));
74b04a01 1780 self.debug_introduce_local(bx, index);
32a655c1 1781 }
ff7c6d11 1782 LocalRef::Operand(Some(op)) => {
dfeec247 1783 assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
32a655c1
SL
1784 }
1785 }
1786 } else {
74b04a01 1787 let dst = self.codegen_place(bx, dst.as_ref());
94b46f34 1788 self.codegen_transmute_into(bx, src, dst);
32a655c1
SL
1789 }
1790 }
1791
a1dfa0c6
XL
1792 fn codegen_transmute_into(
1793 &mut self,
1794 bx: &mut Bx,
1795 src: &mir::Operand<'tcx>,
dfeec247 1796 dst: PlaceRef<'tcx, Bx::Value>,
a1dfa0c6 1797 ) {
94b46f34 1798 let src = self.codegen_operand(bx, src);
fc512014
XL
1799
1800 // Special-case transmutes between scalars as simple bitcasts.
c295e0f8 1801 match (src.layout.abi, dst.layout.abi) {
fc512014
XL
1802 (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1803 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
9c376795
FG
1804 let src_is_ptr = src_scalar.primitive() == abi::Pointer;
1805 let dst_is_ptr = dst_scalar.primitive() == abi::Pointer;
1806 if src_is_ptr == dst_is_ptr {
fc512014
XL
1807 assert_eq!(src.layout.size, dst.layout.size);
1808
1809 // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1810 // conversions allow handling `bool`s the same as `u8`s.
1811 let src = bx.from_immediate(src.immediate());
9c376795
FG
1812 // LLVM also doesn't like `bitcast`s between pointers in different address spaces.
1813 let src_as_dst = if src_is_ptr {
1814 bx.pointercast(src, bx.backend_type(dst.layout))
1815 } else {
1816 bx.bitcast(src, bx.backend_type(dst.layout))
1817 };
fc512014
XL
1818 Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1819 return;
1820 }
1821 }
1822 _ => {}
1823 }
1824
a1dfa0c6
XL
1825 let llty = bx.backend_type(src.layout);
1826 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1827 let align = src.layout.align.abi.min(dst.align);
e1599b0c 1828 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
54a0048b
SL
1829 }
1830
1831 // Stores the return value of a function call into it's final location.
a1dfa0c6
XL
1832 fn store_return(
1833 &mut self,
1834 bx: &mut Bx,
1835 dest: ReturnDest<'tcx, Bx::Value>,
60c5eb7d 1836 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
dfeec247 1837 llval: Bx::Value,
a1dfa0c6 1838 ) {
54a0048b
SL
1839 use self::ReturnDest::*;
1840
1841 match dest {
1842 Nothing => (),
60c5eb7d 1843 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
3157f602 1844 IndirectOperand(tmp, index) => {
a1dfa0c6 1845 let op = bx.load_operand(tmp);
2c00a5a8 1846 tmp.storage_dead(bx);
3157f602 1847 self.locals[index] = LocalRef::Operand(Some(op));
74b04a01 1848 self.debug_introduce_local(bx, index);
54a0048b 1849 }
3157f602
XL
1850 DirectOperand(index) => {
1851 // If there is a cast, we have to store and reload.
f2b60f7d 1852 let op = if let PassMode::Cast(..) = ret_abi.mode {
60c5eb7d 1853 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2c00a5a8 1854 tmp.storage_live(bx);
60c5eb7d 1855 bx.store_arg(&ret_abi, llval, tmp);
a1dfa0c6 1856 let op = bx.load_operand(tmp);
2c00a5a8 1857 tmp.storage_dead(bx);
ff7c6d11 1858 op
54a0048b 1859 } else {
60c5eb7d 1860 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
54a0048b 1861 };
3157f602 1862 self.locals[index] = LocalRef::Operand(Some(op));
74b04a01 1863 self.debug_introduce_local(bx, index);
54a0048b
SL
1864 }
1865 }
1866 }
1867}
1868
a1dfa0c6 1869enum ReturnDest<'tcx, V> {
dc9dc135 1870 // Do nothing; the return value is indirect or ignored.
54a0048b 1871 Nothing,
dc9dc135 1872 // Store the return value to the pointer.
a1dfa0c6 1873 Store(PlaceRef<'tcx, V>),
dc9dc135 1874 // Store an indirect return value to an operand local place.
a1dfa0c6 1875 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
dc9dc135 1876 // Store a direct return value to an operand local place.
dfeec247 1877 DirectOperand(mir::Local),
54a0048b 1878}