LLVM 24.0.0git
X86FrameLowering.cpp
Go to the documentation of this file.
1//===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the X86 implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "X86FrameLowering.h"
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86InstrInfo.h"
19#include "X86Subtarget.h"
20#include "X86TargetMachine.h"
21#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/Module.h"
34#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/MC/MCSymbol.h"
37#include "llvm/Support/LEB128.h"
39#include <cstdlib>
40
41#define DEBUG_TYPE "x86-fl"
42
43STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
44STATISTIC(NumFrameExtraProbe,
45 "Number of extra stack probes generated in prologue");
46STATISTIC(NumFunctionUsingPush2Pop2, "Number of functions using push2/pop2");
47
48using namespace llvm;
49
51 const Function &Fn = MF.getFunction();
52
53 // Whole module is in V3 mode.
55 return true;
56
57 // Otherwise promote a function that may use EGPR (R16-R31), which V1/V2
58 // unwind codes cannot encode. The per-function "+egpr" feature is the signal,
59 // so an auto-dispatch APX clone gets V3 while the baseline clone stays on the
60 // module default. We conservatively promote any egpr function rather than
61 // checking for an actual EGPR save, keeping this a cheap query. (PUSH2/POP2
62 // does not need V3: V1/V2 describe a PUSH2 as two SEH_PushReg codes.)
63 return Fn.needsUnwindTableEntry() &&
64 MF.getSubtarget<X86Subtarget>().hasEGPR();
65}
66
67static const TargetRegisterClass *
69 const TargetRegisterInfo &TRI) {
70 if (X86::VK16RegClass.contains(Reg))
71 return STI.hasBWI() ? &X86::VK64RegClass : &X86::VK16RegClass;
72 return TRI.getMinimalPhysRegClass(Reg);
73}
74
76 MaybeAlign StackAlignOverride)
77 : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
78 STI.is64Bit() ? -8 : -4),
79 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
80 // Cache a bunch of frame-related predicates for this subtarget.
81 SlotSize = TRI->getSlotSize();
82 assert(SlotSize == 4 || SlotSize == 8);
83 Is64Bit = STI.is64Bit();
84 IsLP64 = STI.isTarget64BitLP64();
85 // standard x86_64 uses 64-bit frame/stack pointers, x32 - 32-bit.
86 Uses64BitFramePtr = STI.isTarget64BitLP64();
87 StackPtr = TRI->getStackRegister();
88}
89
91 return !MF.getFrameInfo().hasVarSizedObjects() &&
92 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
93 !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
94}
95
96/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
97/// call frame pseudos can be simplified. Having a FP, as in the default
98/// implementation, is not sufficient here since we can't always use it.
99/// Use a more nuanced condition.
101 const MachineFunction &MF) const {
102 return hasReservedCallFrame(MF) ||
103 MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
104 (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
105 TRI->hasBasePointer(MF);
106}
107
108// needsFrameIndexResolution - Do we need to perform FI resolution for
109// this function. Normally, this is required only when the function
110// has any stack objects. However, FI resolution actually has another job,
111// not apparent from the title - it resolves callframesetup/destroy
112// that were not simplified earlier.
113// So, this is required for x86 functions that have push sequences even
114// when there are no stack objects.
116 const MachineFunction &MF) const {
117 return MF.getFrameInfo().hasStackObjects() ||
118 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
119}
120
121/// hasFPImpl - Return true if the specified function should have a dedicated
122/// frame pointer register. This is true if the function has variable sized
123/// allocas or if frame pointer elimination is disabled.
125 const MachineFrameInfo &MFI = MF.getFrameInfo();
126 return (MF.disableFramePointerElim() || TRI->hasStackRealignment(MF) ||
128 MFI.hasOpaqueSPAdjustment() ||
131 MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
132 MFI.hasStackMap() || MFI.hasPatchPoint() ||
134}
135
136static unsigned getSUBriOpcode(bool IsLP64) {
137 return IsLP64 ? X86::SUB64ri32 : X86::SUB32ri;
138}
139
140static unsigned getADDriOpcode(bool IsLP64) {
141 return IsLP64 ? X86::ADD64ri32 : X86::ADD32ri;
142}
143
144static unsigned getSUBrrOpcode(bool IsLP64) {
145 return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
146}
147
148static unsigned getADDrrOpcode(bool IsLP64) {
149 return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
150}
151
152static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
153 return IsLP64 ? X86::AND64ri32 : X86::AND32ri;
154}
155
156static unsigned getLEArOpcode(bool IsLP64) {
157 return IsLP64 ? X86::LEA64r : X86::LEA32r;
158}
159
160// Push-Pop Acceleration (PPX) hint is used to indicate that the POP reads the
161// value written by the PUSH from the stack. The processor tracks these marked
162// instructions internally and fast-forwards register data between matching PUSH
163// and POP instructions, without going through memory or through the training
164// loop of the Fast Store Forwarding Predictor (FSFP). Instead, a more efficient
165// memory-renaming optimization can be used.
166//
167// The PPX hint is purely a performance hint. Instructions with this hint have
168// the same functional semantics as those without. PPX hints set by the
169// compiler that violate the balancing rule may turn off the PPX optimization,
170// but they will not affect program semantics.
171//
172// Hence, PPX is used for balanced spill/reloads (Exceptions and setjmp/longjmp
173// are not considered).
174//
175// PUSH2 and POP2 are instructions for (respectively) pushing/popping 2
176// GPRs at a time to/from the stack.
177static unsigned getPUSHOpcode(const X86Subtarget &ST) {
178 return ST.is64Bit() ? (ST.hasPPX() ? X86::PUSHP64r : X86::PUSH64r)
179 : X86::PUSH32r;
180}
181static unsigned getPOPOpcode(const X86Subtarget &ST) {
182 return ST.is64Bit() ? (ST.hasPPX() ? X86::POPP64r : X86::POP64r)
183 : X86::POP32r;
184}
185static unsigned getPUSH2Opcode(const X86Subtarget &ST) {
186 return ST.hasPPX() ? X86::PUSH2P : X86::PUSH2;
187}
188static unsigned getPOP2Opcode(const X86Subtarget &ST) {
189 return ST.hasPPX() ? X86::POP2P : X86::POP2;
190}
191
193 for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
194 MCRegister Reg = RegMask.PhysReg;
195
196 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
197 Reg == X86::AH || Reg == X86::AL)
198 return true;
199 }
200
201 return false;
202}
203
204/// Check if the flags need to be preserved before the terminators.
205/// This would be the case, if the eflags is live-in of the region
206/// composed by the terminators or live-out of that region, without
207/// being defined by a terminator.
208static bool
210 for (const MachineInstr &MI : MBB.terminators()) {
211 bool BreakNext = false;
212 for (const MachineOperand &MO : MI.operands()) {
213 if (!MO.isReg())
214 continue;
215 Register Reg = MO.getReg();
216 if (Reg != X86::EFLAGS)
217 continue;
218
219 // This terminator needs an eflags that is not defined
220 // by a previous another terminator:
221 // EFLAGS is live-in of the region composed by the terminators.
222 if (!MO.isDef())
223 return true;
224 // This terminator defines the eflags, i.e., we don't need to preserve it.
225 // However, we still need to check this specific terminator does not
226 // read a live-in value.
227 BreakNext = true;
228 }
229 // We found a definition of the eflags, no need to preserve them.
230 if (BreakNext)
231 return false;
232 }
233
234 // None of the terminators use or define the eflags.
235 // Check if they are live-out, that would imply we need to preserve them.
236 for (const MachineBasicBlock *Succ : MBB.successors())
237 if (Succ->isLiveIn(X86::EFLAGS))
238 return true;
239
240 return false;
241}
242
243constexpr uint64_t MaxSPChunk = (1ULL << 31) - 1;
244
245/// emitSPUpdate - Emit a series of instructions to increment / decrement the
246/// stack pointer by a constant value.
249 const DebugLoc &DL, int64_t NumBytes,
250 bool InEpilogue) const {
251 bool isSub = NumBytes < 0;
252 uint64_t Offset = isSub ? -NumBytes : NumBytes;
255
257 // We're being asked to adjust a 32-bit stack pointer by 4 GiB or more.
258 // This might be unreachable code, so don't complain now; just trap if
259 // it's reached at runtime.
260 BuildMI(MBB, MBBI, DL, TII.get(X86::TRAP));
261 return;
262 }
263
264 MachineFunction &MF = *MBB.getParent();
266 const X86TargetLowering &TLI = *STI.getTargetLowering();
267 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
268
269 // It's ok to not take into account large chunks when probing, as the
270 // allocation is split in smaller chunks anyway.
271 if (EmitInlineStackProbe && !InEpilogue) {
272
273 // This pseudo-instruction is going to be expanded, potentially using a
274 // loop, by inlineStackProbe().
275 BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset);
276 return;
277 } else if (Offset > MaxSPChunk) {
278 // Rather than emit a long series of instructions for large offsets,
279 // load the offset into a register and do one sub/add
280 unsigned Reg = 0;
281 unsigned Rax = (unsigned)(Uses64BitFramePtr ? X86::RAX : X86::EAX);
282
283 if (isSub && !isEAXLiveIn(MBB))
284 Reg = Rax;
285 else
286 Reg = getX86SubSuperRegister(TRI->findDeadCallerSavedReg(MBB, MBBI),
287 Uses64BitFramePtr ? 64 : 32);
288
289 unsigned AddSubRROpc = isSub ? getSUBrrOpcode(Uses64BitFramePtr)
291 if (Reg) {
292 BuildMI(MBB, MBBI, DL,
294 .addImm(Offset)
295 .setMIFlag(Flag);
296 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
298 .addReg(Reg);
299 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
300 return;
301 } else if (Offset > 8 * MaxSPChunk) {
302 // If we would need more than 8 add or sub instructions (a >16GB stack
303 // frame), it's worth spilling RAX to materialize this immediate.
304 // pushq %rax
305 // movabsq +-$Offset+-SlotSize, %rax
306 // addq %rsp, %rax
307 // xchg %rax, (%rsp)
308 // movq (%rsp), %rsp
309 assert(Uses64BitFramePtr && "can't have 32-bit 16GB stack frame");
310 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
312 .setMIFlag(Flag);
313 // Subtract is not commutative, so negate the offset and always use add.
314 // Subtract 8 less and add 8 more to account for the PUSH we just did.
315 if (isSub)
316 Offset = -(Offset - SlotSize);
317 else
319 BuildMI(MBB, MBBI, DL,
321 .addImm(Offset)
322 .setMIFlag(Flag);
323 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
324 .addReg(Rax)
326 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
327 // Exchange the new SP in RAX with the top of the stack.
329 BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
330 StackPtr, 0);
331 // Load new SP from the top of the stack into RSP.
332 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
333 StackPtr, 0);
334 return;
335 }
336 }
337
338 while (Offset) {
339 if (Offset == SlotSize) {
340 // Use push / pop for slot sized adjustments as a size optimization. We
341 // need to find a dead register when using pop.
342 unsigned Reg = isSub ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
343 : TRI->findDeadCallerSavedReg(MBB, MBBI);
344 if (Reg) {
345 unsigned Opc = isSub ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
346 : (Is64Bit ? X86::POP64r : X86::POP32r);
347 BuildMI(MBB, MBBI, DL, TII.get(Opc))
348 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
349 .setMIFlag(Flag);
350 return;
351 }
352 }
353
354 uint64_t ThisVal = std::min(Offset, MaxSPChunk);
355
356 BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
357 .setMIFlag(Flag);
358
359 Offset -= ThisVal;
360 }
361}
362
363MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
365 const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
366 assert(Offset != 0 && "zero offset stack adjustment requested");
367
368 // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
369 // is tricky.
370 bool UseLEA;
371 if (!InEpilogue) {
372 // Check if inserting the prologue at the beginning
373 // of MBB would require to use LEA operations.
374 // We need to use LEA operations if EFLAGS is live in, because
375 // it means an instruction will read it before it gets defined.
376 UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
377 } else {
378 // If we can use LEA for SP but we shouldn't, check that none
379 // of the terminators uses the eflags. Otherwise we will insert
380 // a ADD that will redefine the eflags and break the condition.
381 // Alternatively, we could move the ADD, but this may not be possible
382 // and is an optimization anyway.
383 UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
384 if (UseLEA && !STI.useLeaForSP())
386 // If that assert breaks, that means we do not do the right thing
387 // in canUseAsEpilogue.
389 "We shouldn't have allowed this insertion point");
390 }
391
392 MachineInstrBuilder MI;
393 // Use an NF (no-flags) variant as a smaller replacement for LEA when EFLAGS
394 // must be preserved (i.e. only when we would otherwise emit LEA). If EFLAGS
395 // is dead we prefer the plain SUB/ADD, which is shorter than the EVEX-encoded
396 // NF form. The NF stack-adjust opcodes below are 64-bit (SUB64ri32_NF/
397 // ADD64ri32_NF), so don't use them for the x32 ABI where the stack pointer is
398 // 32-bit. NF cannot reach a Win64 epilogue (which never uses LEA for the SP
399 // adjustment unless it has a frame pointer, and that path doesn't go through
400 // here), so the Windows epilogue unwinder never sees an undisassemblable NF
401 // add/sub.
402 bool UseNF = UseLEA && STI.hasNF() && Uses64BitFramePtr;
403 bool IsSub = Offset < 0;
404 uint64_t AbsOffset = IsSub ? -Offset : Offset;
405 if (UseNF) {
406 const unsigned Opc = IsSub ? X86::SUB64ri32_NF : X86::ADD64ri32_NF;
407 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
409 .addImm(AbsOffset);
410 // NF instructions define no EFLAGS, so there is nothing to mark dead.
411 } else if (UseLEA) {
414 StackPtr),
416 } else {
417 unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr)
419 int64_t Imm = AbsOffset;
420 // Prefer `add rsp, -128` over `sub rsp, 128` (and vice versa in the
421 // epilogue): 128 is the one magnitude whose negation fits the
422 // sign-extended 8-bit immediate while the value itself does not, so the
423 // flipped operation is three bytes shorter. EFLAGS is dead here (this
424 // branch clobbers it anyway). Windows CFI epilogues keep the canonical
425 // ADD: v1 unwind info describes no epilogues, so the unwinder detects
426 // one by disassembling forward for `add rsp, imm` (prologues are
427 // delimited by SizeOfProlog and never disassembled). Unwind v2/v3 do
428 // describe epilogues, but X86WinEHUnwindV2 expects the ADD spelling
429 // too.
430 if (AbsOffset == 128 &&
431 !(InEpilogue && MBB.getParent()->usesWindowsUnwindInfo())) {
432 Opc = IsSub ? getADDriOpcode(Uses64BitFramePtr)
433 : getSUBriOpcode(Uses64BitFramePtr);
434 Imm = -128;
435 }
436 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
438 .addImm(Imm);
439 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
440 }
441 return MI;
442}
443
444template <typename FoundT, typename CalcT>
445int64_t X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
447 FoundT FoundStackAdjust,
448 CalcT CalcNewOffset,
449 bool doMergeWithPrevious) const {
450 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
451 (!doMergeWithPrevious && MBBI == MBB.end()))
452 return CalcNewOffset(0);
453
454 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
455
457 // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
458 // instruction, and that there are no DBG_VALUE or other instructions between
459 // ADD/SUB/LEA and its corresponding CFI instruction.
460 /* TODO: Add support for the case where there are multiple CFI instructions
461 below the ADD/SUB/LEA, e.g.:
462 ...
463 add
464 cfi_def_cfa_offset
465 cfi_offset
466 ...
467 */
468 if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
469 PI = std::prev(PI);
470
471 int64_t Offset = 0;
472 for (;;) {
473 unsigned Opc = PI->getOpcode();
474
475 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD32ri ||
476 Opc == X86::ADD64ri32_NF) &&
477 PI->getOperand(0).getReg() == StackPtr) {
478 assert(PI->getOperand(1).getReg() == StackPtr);
479 Offset = PI->getOperand(2).getImm();
480 } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
481 PI->getOperand(0).getReg() == StackPtr &&
482 PI->getOperand(1).getReg() == StackPtr &&
483 PI->getOperand(2).getImm() == 1 &&
484 PI->getOperand(3).getReg() == X86::NoRegister &&
485 PI->getOperand(5).getReg() == X86::NoRegister) {
486 // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
487 Offset = PI->getOperand(4).getImm();
488 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB32ri ||
489 Opc == X86::SUB64ri32_NF) &&
490 PI->getOperand(0).getReg() == StackPtr) {
491 assert(PI->getOperand(1).getReg() == StackPtr);
492 Offset = -PI->getOperand(2).getImm();
493 } else
494 return CalcNewOffset(0);
495
496 FoundStackAdjust(PI, Offset);
497 if ((uint64_t)std::abs((int64_t)CalcNewOffset(Offset)) < MaxSPChunk)
498 break;
499
500 if (doMergeWithPrevious ? (PI == MBB.begin()) : (PI == MBB.end()))
501 return CalcNewOffset(0);
502
503 PI = doMergeWithPrevious ? std::prev(PI) : std::next(PI);
504 }
505
506 PI = MBB.erase(PI);
507 if (PI != MBB.end() && PI->isCFIInstruction()) {
508 auto CIs = MBB.getParent()->getFrameInstructions();
509 MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()];
512 PI = MBB.erase(PI);
513 }
514 if (!doMergeWithPrevious)
516
517 return CalcNewOffset(Offset);
518}
519
522 int64_t AddOffset,
523 bool doMergeWithPrevious) const {
524 return mergeSPUpdates(
525 MBB, MBBI, [AddOffset](int64_t Offset) { return AddOffset + Offset; },
526 doMergeWithPrevious);
527}
528
531 const DebugLoc &DL,
532 const MCCFIInstruction &CFIInst,
533 MachineInstr::MIFlag Flag) const {
534 MachineFunction &MF = *MBB.getParent();
535 unsigned CFIIndex = MF.addFrameInst(CFIInst);
536
538 MF.getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true);
539
540 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
541 .addCFIIndex(CFIIndex)
542 .setMIFlag(Flag);
543}
544
545/// Emits Dwarf Info specifying offsets of callee saved registers and
546/// frame pointer. This is called only when basic block sections are enabled.
549 MachineFunction &MF = *MBB.getParent();
550 if (!hasFP(MF)) {
552 return;
553 }
555 const Register FramePtr = TRI->getFrameRegister(MF);
556 const Register MachineFramePtr =
557 STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
558 : FramePtr;
559 unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true);
560 // Offset = space for return address + size of the frame pointer itself.
561 int64_t Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
563 MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset));
565}
566
569 const DebugLoc &DL, bool IsPrologue) const {
570 MachineFunction &MF = *MBB.getParent();
571 MachineFrameInfo &MFI = MF.getFrameInfo();
574
575 // Add callee saved registers to move list.
576 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
577
578 // Calculate offsets.
579 for (const CalleeSavedInfo &I : CSI) {
580 int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
581 MCRegister Reg = I.getReg();
582 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
583
584 if (IsPrologue) {
585 if (X86FI->getStackPtrSaveMI()) {
586 // +2*SlotSize because there is return address and ebp at the bottom
587 // of the stack.
588 // | retaddr |
589 // | ebp |
590 // | |<--ebp
591 Offset += 2 * SlotSize;
592 SmallString<64> CfaExpr;
593 CfaExpr.push_back(dwarf::DW_CFA_expression);
594 uint8_t buffer[16];
595 CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
596 CfaExpr.push_back(2);
597 Register FramePtr = TRI->getFrameRegister(MF);
598 const Register MachineFramePtr =
599 STI.isTarget64BitILP32()
601 : FramePtr;
602 unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
603 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
604 CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
606 MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
608 } else {
610 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
611 }
612 } else {
614 MCCFIInstruction::createRestore(nullptr, DwarfReg));
615 }
616 }
617 if (auto *MI = X86FI->getStackPtrSaveMI()) {
618 int FI = MI->getOperand(1).getIndex();
619 int64_t Offset = MFI.getObjectOffset(FI) + 2 * SlotSize;
620 SmallString<64> CfaExpr;
621 Register FramePtr = TRI->getFrameRegister(MF);
622 const Register MachineFramePtr =
623 STI.isTarget64BitILP32()
625 : FramePtr;
626 unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
627 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
628 uint8_t buffer[16];
629 CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
630 CfaExpr.push_back(dwarf::DW_OP_deref);
631
632 SmallString<64> DefCfaExpr;
633 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
634 DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer));
635 DefCfaExpr.append(CfaExpr.str());
636 // DW_CFA_def_cfa_expression: DW_OP_breg5 offset, DW_OP_deref
638 MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()),
640 }
641}
642
643void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
645 RegScavenger *) const {
646 const MachineFunction &MF = *MBB.getParent();
647
648 // Insertion point.
649 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
650
651 // Fake a debug loc.
652 DebugLoc DL;
653 if (MBBI != MBB.end())
654 DL = MBBI->getDebugLoc();
655
656 // Zero out FP stack if referenced. Do this outside of the loop below so that
657 // it's done only once.
658 for (MCRegister Reg : RegsToZero.set_bits()) {
659 if (!X86::RFP80RegClass.contains(Reg))
660 continue;
661
662 // Do not push zeros over x87 return values. X86FloatingPoint records
663 // returned values as implicit ST0/ST1 uses on the return instruction.
664 unsigned NumFPRegs = 8;
665 if (MBBI->hasRegisterImplicitUseOperand(X86::ST0))
666 --NumFPRegs;
667 if (MBBI->hasRegisterImplicitUseOperand(X86::ST1))
668 --NumFPRegs;
669
670 for (unsigned i = 0; i != NumFPRegs; ++i)
671 BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0));
672
673 for (unsigned i = 0; i != NumFPRegs; ++i)
674 BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0);
675 break;
676 }
677
678 // For GPRs, we only care to clear out the 32-bit register.
679 BitVector GPRsToZero(TRI->getNumRegs());
680 for (MCRegister Reg : RegsToZero.set_bits())
681 if (TRI->isGeneralPurposeRegister(MF, Reg)) {
682 GPRsToZero.set(getX86SubSuperRegister(Reg, 32));
683 RegsToZero.reset(Reg);
684 }
685
686 // Zero out the GPRs first.
687 for (MCRegister Reg : GPRsToZero.set_bits())
688 TII.buildClearRegister(Reg, MBB, MBBI, DL);
689
690 // Coalesce the aliasing XMM/YMM/ZMM views of each vector register so a lane
691 // is cleared only once, mirroring the GPR handling above.
692 auto getVectorClearReg = [&](MCRegister Reg) -> MCRegister {
693 if (!X86::VR128RegClass.contains(Reg) &&
694 !X86::VR128XRegClass.contains(Reg) &&
695 !X86::VR256RegClass.contains(Reg) &&
696 !X86::VR256XRegClass.contains(Reg) && !X86::VR512RegClass.contains(Reg))
697 return MCRegister();
698
699 // Clearing the XMM zeroes the whole lane. XMM0-15 use the compact VEX form;
700 // XMM16-31 are EVEX-only, reachable only via the ZMM form.
701 MCRegister Xmm = TRI->getSubReg(Reg, X86::sub_xmm);
702 if (!Xmm)
703 Xmm = Reg;
704 if (X86::VR128RegClass.contains(Xmm))
705 return Xmm;
706 MCRegister Zmm =
707 TRI->getMatchingSuperReg(Xmm, X86::sub_xmm, &X86::VR512RegClass);
708 assert(Zmm && "XMM16-31 must have an enclosing ZMM to clear through");
709 return Zmm;
710 };
711
712 BitVector VecRegsToZero(TRI->getNumRegs());
713 for (MCRegister Reg : RegsToZero.set_bits())
714 if (MCRegister Clear = getVectorClearReg(Reg)) {
715 VecRegsToZero.set(Clear.id());
716 RegsToZero.reset(Reg);
717 }
718
719 for (MCRegister Reg : VecRegsToZero.set_bits())
720 TII.buildClearRegister(Reg, MBB, MBBI, DL);
721
722 // Zero out the remaining registers (e.g. mask registers).
723 for (MCRegister Reg : RegsToZero.set_bits())
724 TII.buildClearRegister(Reg, MBB, MBBI, DL);
725}
726
729 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
730 std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
732 if (STI.isTargetWindowsCoreCLR()) {
733 if (InProlog) {
734 BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING))
735 .addImm(0 /* no explicit stack size */);
736 } else {
737 emitStackProbeInline(MF, MBB, MBBI, DL, false);
738 }
739 } else {
740 emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
741 }
742}
743
745 return STI.isOSWindows() && !STI.isTargetWin64();
746}
747
749 MachineBasicBlock &PrologMBB) const {
750 auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
751 return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
752 });
753 if (Where != PrologMBB.end()) {
754 DebugLoc DL = PrologMBB.findDebugLoc(Where);
755 emitStackProbeInline(MF, PrologMBB, Where, DL, true);
756 Where->eraseFromParent();
757 }
758}
759
760void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
763 const DebugLoc &DL,
764 bool InProlog) const {
766 if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
767 emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
768 else
769 emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
770}
771
772void X86FrameLowering::emitStackProbeInlineGeneric(
774 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
775 MachineInstr &AllocWithProbe = *MBBI;
776 uint64_t Offset = AllocWithProbe.getOperand(0).getImm();
777
780 assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
781 "different expansion expected for CoreCLR 64 bit");
782
783 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
784 uint64_t ProbeChunk = StackProbeSize * 8;
785
786 uint64_t MaxAlign =
787 TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
788
789 // Synthesize a loop or unroll it, depending on the number of iterations.
790 // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
791 // between the unaligned rsp and current rsp.
792 if (Offset > ProbeChunk) {
793 emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
794 MaxAlign % StackProbeSize);
795 } else {
796 emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
797 MaxAlign % StackProbeSize);
798 }
799}
800
801void X86FrameLowering::emitStackProbeInlineGenericBlock(
804 uint64_t AlignOffset) const {
805
806 // The code below is allocating one StackProbeSize at a time,
807 // then inserting a "probe" (write of 0), in order to hit any guard pages.
808 // A probe is only needed every StackProbeSize (no skipping entire pages).
809 //
810 // StackProbeSize (PAGE_SIZE)
811 // / \
812 // |----------|----------|------> rsp decreasing
813 // ^ ^ ^
814 // | | |
815 // CurrentOffset Offset (Offset + AlignOffset)
816 //
817 // Offset: size we are being asked to allocate on the stack, in bytes.
818 // AlignOffset: extra amount to allocate (< StackProbeSize),
819 // needed to satisfy any alignment for calling conventions, etc.
820
821 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
822 const bool HasFP = hasFP(MF);
823 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
824 const X86TargetLowering &TLI = *STI.getTargetLowering();
825 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
826 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
827
828 uint64_t CurrentOffset = 0;
829
830 assert(AlignOffset < StackProbeSize);
831
832 // If the offset is so small it fits within a page, there's nothing to do.
833 if (StackProbeSize < Offset + AlignOffset) {
834
835 uint64_t StackAdjustment = StackProbeSize - AlignOffset;
836 BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
837 .setMIFlag(MachineInstr::FrameSetup);
838 if (!HasFP && NeedsDwarfCFI) {
839 BuildCFI(
840 MBB, MBBI, DL,
841 MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
842 }
843
844 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
846 StackPtr, 0)
847 .addImm(0)
849 NumFrameExtraProbe++;
850 CurrentOffset = StackProbeSize - AlignOffset;
851 }
852
853 // For the next N - 1 pages, just probe.
854 while (CurrentOffset + StackProbeSize <= Offset) {
855 BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
856 .setMIFlag(MachineInstr::FrameSetup);
857
858 if (!HasFP && NeedsDwarfCFI) {
859 BuildCFI(
860 MBB, MBBI, DL,
861 MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
862 }
863 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
865 StackPtr, 0)
866 .addImm(0)
868 NumFrameExtraProbe++;
869 CurrentOffset += StackProbeSize;
870 }
871
872 const uint64_t ChunkSize = Offset - CurrentOffset;
873 // We may not require a tail allocation. For example, this can happen
874 // if Offset is a multiple of StackProbeSize, and AlignOffset = 0.
875 if (ChunkSize == 0)
876 return;
877 else if (ChunkSize == SlotSize) {
878 // Use push for slot sized adjustments as a size optimization,
879 // like emitSPUpdate does when not probing.
880 unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
881 unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
882 BuildMI(MBB, MBBI, DL, TII.get(Opc))
885 } else {
886 assert(!(ChunkSize > StackProbeSize) &&
887 "Tail allocation greater than page size");
888 BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
889 .setMIFlag(MachineInstr::FrameSetup);
890 }
891 // No need to adjust Dwarf CFA offset here, the last position of the stack has
892 // been defined
893}
894
895void X86FrameLowering::emitStackProbeInlineGenericLoop(
898 uint64_t AlignOffset) const {
899 assert(Offset && "null offset");
900
901 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
903 "Inline stack probe loop will clobber live EFLAGS.");
904
905 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
906 const bool HasFP = hasFP(MF);
907 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
908 const X86TargetLowering &TLI = *STI.getTargetLowering();
909 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
910 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
911
912 if (AlignOffset) {
913 if (AlignOffset < StackProbeSize) {
914 // Perform a first smaller allocation followed by a probe.
915 BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
916 .setMIFlag(MachineInstr::FrameSetup);
917
918 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
920 StackPtr, 0)
921 .addImm(0)
923 NumFrameExtraProbe++;
924 Offset -= AlignOffset;
925 }
926 }
927
928 // Synthesize a loop
929 NumFrameLoopProbe++;
930 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
931
932 MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
933 MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
934
936 MF.insert(MBBIter, testMBB);
937 MF.insert(MBBIter, tailMBB);
938
939 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
940 : Is64Bit ? X86::R11D
941 : X86::EAX;
942
943 // save loop bound
944 {
945 const uint64_t BoundOffset = alignDown(Offset, StackProbeSize);
946
947 // Can we calculate the loop bound using SUB with a 32-bit immediate?
948 // Note that the immediate gets sign-extended when used with a 64-bit
949 // register, so in that case we only have 31 bits to work with.
950 bool canUseSub =
951 Uses64BitFramePtr ? isUInt<31>(BoundOffset) : isUInt<32>(BoundOffset);
952
953 if (canUseSub) {
954 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
955
956 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
959 BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
960 .addReg(FinalStackProbed)
961 .addImm(BoundOffset)
963 .setOperandDead(3); // implicit-def $eflags
964 } else if (Uses64BitFramePtr) {
965 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), FinalStackProbed)
966 .addImm(-BoundOffset)
968 BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), FinalStackProbed)
969 .addReg(FinalStackProbed)
972 .setOperandDead(3); // implicit-def $eflags
973 } else {
974 llvm_unreachable("Offset too large for 32-bit stack pointer");
975 }
976
977 // while in the loop, use loop-invariant reg for CFI,
978 // instead of the stack pointer, which changes during the loop
979 if (!HasFP && NeedsDwarfCFI) {
980 // x32 uses the same DWARF register numbers as x86-64,
981 // so there isn't a register number for r11d, we must use r11 instead
982 const Register DwarfFinalStackProbed =
983 STI.isTarget64BitILP32()
984 ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
985 : FinalStackProbed;
986
989 nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
991 MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
992 }
993 }
994
995 // allocate a page
996 BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
997 /*InEpilogue=*/false)
998 .setMIFlag(MachineInstr::FrameSetup);
999
1000 // touch the page
1001 addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
1003 StackPtr, 0)
1004 .addImm(0)
1006
1007 // cmp with stack pointer bound
1008 BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1010 .addReg(FinalStackProbed)
1012
1013 // jump
1014 BuildMI(testMBB, DL, TII.get(X86::JCC_1))
1015 .addMBB(testMBB)
1018 testMBB->addSuccessor(testMBB);
1019 testMBB->addSuccessor(tailMBB);
1020
1021 // BB management
1022 tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
1024 MBB.addSuccessor(testMBB);
1025
1026 // handle tail
1027 const uint64_t TailOffset = Offset % StackProbeSize;
1028 MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
1029 if (TailOffset) {
1030 BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
1031 /*InEpilogue=*/false)
1032 .setMIFlag(MachineInstr::FrameSetup);
1033 }
1034
1035 // after the loop, switch back to stack pointer for CFI
1036 if (!HasFP && NeedsDwarfCFI) {
1037 // x32 uses the same DWARF register numbers as x86-64,
1038 // so there isn't a register number for esp, we must use rsp instead
1039 const Register DwarfStackPtr =
1040 STI.isTarget64BitILP32()
1042 : Register(StackPtr);
1043
1044 BuildCFI(*tailMBB, TailMBBIter, DL,
1046 nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
1047 }
1048
1049 // Update Live In information
1050 fullyRecomputeLiveIns({tailMBB, testMBB});
1051}
1052
1053void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
1055 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
1056 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1057 assert(STI.is64Bit() && "different expansion needed for 32 bit");
1058 assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
1059 const TargetInstrInfo &TII = *STI.getInstrInfo();
1060 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
1061
1062 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1064 "Inline stack probe loop will clobber live EFLAGS.");
1065
1066 // RAX contains the number of bytes of desired stack adjustment.
1067 // The handling here assumes this value has already been updated so as to
1068 // maintain stack alignment.
1069 //
1070 // We need to exit with RSP modified by this amount and execute suitable
1071 // page touches to notify the OS that we're growing the stack responsibly.
1072 // All stack probing must be done without modifying RSP.
1073 //
1074 // MBB:
1075 // SizeReg = RAX;
1076 // ZeroReg = 0
1077 // CopyReg = RSP
1078 // Flags, TestReg = CopyReg - SizeReg
1079 // FinalReg = !Flags.Ovf ? TestReg : ZeroReg
1080 // LimitReg = gs magic thread env access
1081 // if FinalReg >= LimitReg goto ContinueMBB
1082 // RoundBB:
1083 // RoundReg = page address of FinalReg
1084 // LoopMBB:
1085 // LoopReg = PHI(LimitReg,ProbeReg)
1086 // ProbeReg = LoopReg - PageSize
1087 // [ProbeReg] = 0
1088 // if (ProbeReg > RoundReg) goto LoopMBB
1089 // ContinueMBB:
1090 // RSP = RSP - RAX
1091 // [rest of original MBB]
1092
1093 // Set up the new basic blocks
1094 MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1095 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1096 MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1097
1098 MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
1099 MF.insert(MBBIter, RoundMBB);
1100 MF.insert(MBBIter, LoopMBB);
1101 MF.insert(MBBIter, ContinueMBB);
1102
1103 // Split MBB and move the tail portion down to ContinueMBB.
1104 MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
1105 ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
1106 ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
1107
1108 // Some useful constants
1109 const int64_t ThreadEnvironmentStackLimit = 0x10;
1110 const int64_t PageSize = 0x1000;
1111 const int64_t PageMask = ~(PageSize - 1);
1112
1113 // Registers we need. For the normal case we use virtual
1114 // registers. For the prolog expansion we use RAX, RCX and RDX.
1115 MachineRegisterInfo &MRI = MF.getRegInfo();
1116 const TargetRegisterClass *RegClass = &X86::GR64RegClass;
1117 const Register
1118 SizeReg = InProlog ? X86::RAX : MRI.createVirtualRegister(RegClass),
1119 ZeroReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1120 CopyReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1121 TestReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1122 FinalReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1123 RoundedReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1124 LimitReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1125 JoinReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1126 ProbeReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass);
1127
1128 // SP-relative offsets where we can save RCX and RDX.
1129 int64_t RCXShadowSlot = 0;
1130 int64_t RDXShadowSlot = 0;
1131
1132 // If inlining in the prolog, save RCX and RDX.
1133 if (InProlog) {
1134 // Compute the offsets. We need to account for things already
1135 // pushed onto the stack at this point: return address, frame
1136 // pointer (if used), and callee saves.
1137 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1138 const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
1139 const bool HasFP = hasFP(MF);
1140
1141 // Check if we need to spill RCX and/or RDX.
1142 // Here we assume that no earlier prologue instruction changes RCX and/or
1143 // RDX, so checking the block live-ins is enough.
1144 const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
1145 const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
1146 int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
1147 // Assign the initial slot to both registers, then change RDX's slot if both
1148 // need to be spilled.
1149 if (IsRCXLiveIn)
1150 RCXShadowSlot = InitSlot;
1151 if (IsRDXLiveIn)
1152 RDXShadowSlot = InitSlot;
1153 if (IsRDXLiveIn && IsRCXLiveIn)
1154 RDXShadowSlot += 8;
1155 // Emit the saves if needed.
1156 if (IsRCXLiveIn)
1157 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP,
1158 RCXShadowSlot)
1159 .addReg(X86::RCX);
1160 if (IsRDXLiveIn)
1161 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP,
1162 RDXShadowSlot)
1163 .addReg(X86::RDX);
1164 } else {
1165 // Not in the prolog. Copy RAX to a virtual reg.
1166 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
1167 }
1168
1169 // Add code to MBB to check for overflow and set the new target stack pointer
1170 // to zero if so.
1171 BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
1172 .addReg(ZeroReg, RegState::Undef)
1173 .addReg(ZeroReg, RegState::Undef)
1174 .setOperandDead(3); // implicit-def $eflags
1175 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
1176 BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
1177 .addReg(CopyReg)
1178 .addReg(SizeReg);
1179 BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
1180 .addReg(TestReg)
1181 .addReg(ZeroReg)
1183
1184 // FinalReg now holds final stack pointer value, or zero if
1185 // allocation would overflow. Compare against the current stack
1186 // limit from the thread environment block. Note this limit is the
1187 // lowest touched page on the stack, not the point at which the OS
1188 // will cause an overflow exception, so this is just an optimization
1189 // to avoid unnecessarily touching pages that are below the current
1190 // SP but already committed to the stack by the OS.
1191 BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
1192 .addReg(0)
1193 .addImm(1)
1194 .addReg(0)
1195 .addImm(ThreadEnvironmentStackLimit)
1196 .addReg(X86::GS);
1197 BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
1198 // Jump if the desired stack pointer is at or above the stack limit.
1199 BuildMI(&MBB, DL, TII.get(X86::JCC_1))
1200 .addMBB(ContinueMBB)
1202
1203 // Add code to roundMBB to round the final stack pointer to a page boundary.
1204 if (InProlog)
1205 RoundMBB->addLiveIn(FinalReg);
1206 BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
1207 .addReg(FinalReg)
1208 .addImm(PageMask)
1209 .setOperandDead(3); // implicit-def $eflags
1210 BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
1211
1212 // LimitReg now holds the current stack limit, RoundedReg page-rounded
1213 // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
1214 // and probe until we reach RoundedReg.
1215 if (!InProlog) {
1216 BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
1217 .addReg(LimitReg)
1218 .addMBB(RoundMBB)
1219 .addReg(ProbeReg)
1220 .addMBB(LoopMBB);
1221 }
1222
1223 if (InProlog)
1224 LoopMBB->addLiveIn(JoinReg);
1225 addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
1226 -PageSize);
1227
1228 // Probe by storing a byte onto the stack.
1229 BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
1230 .addReg(ProbeReg)
1231 .addImm(1)
1232 .addReg(0)
1233 .addImm(0)
1234 .addReg(0)
1235 .addImm(0);
1236
1237 if (InProlog)
1238 LoopMBB->addLiveIn(RoundedReg);
1239 BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
1240 .addReg(RoundedReg)
1241 .addReg(ProbeReg);
1242 BuildMI(LoopMBB, DL, TII.get(X86::JCC_1))
1243 .addMBB(LoopMBB)
1245
1246 MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
1247
1248 // If in prolog, restore RDX and RCX.
1249 if (InProlog) {
1250 if (RCXShadowSlot) // It means we spilled RCX in the prologue.
1251 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
1252 TII.get(X86::MOV64rm), X86::RCX),
1253 X86::RSP, RCXShadowSlot);
1254 if (RDXShadowSlot) // It means we spilled RDX in the prologue.
1255 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
1256 TII.get(X86::MOV64rm), X86::RDX),
1257 X86::RSP, RDXShadowSlot);
1258 }
1259
1260 // Now that the probing is done, add code to continueMBB to update
1261 // the stack pointer for real.
1262 BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
1263 .addReg(X86::RSP)
1264 .addReg(SizeReg)
1265 .setOperandDead(3); // implicit-def $eflags
1266
1267 // Add the control flow edges we need.
1268 MBB.addSuccessor(ContinueMBB);
1269 MBB.addSuccessor(RoundMBB);
1270 RoundMBB->addSuccessor(LoopMBB);
1271 LoopMBB->addSuccessor(ContinueMBB);
1272 LoopMBB->addSuccessor(LoopMBB);
1273
1274 if (InProlog) {
1275 LivePhysRegs LiveRegs;
1276 computeAndAddLiveIns(LiveRegs, *ContinueMBB);
1277 }
1278
1279 // Mark all the instructions added to the prolog as frame setup.
1280 if (InProlog) {
1281 for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
1282 BeforeMBBI->setFlag(MachineInstr::FrameSetup);
1283 }
1284 for (MachineInstr &MI : *RoundMBB) {
1286 }
1287 for (MachineInstr &MI : *LoopMBB) {
1289 }
1290 for (MachineInstr &MI :
1291 llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1293 }
1294 }
1295}
1296
1297void X86FrameLowering::emitStackProbeCall(
1299 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1300 std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
1301 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
1302
1303 // FIXME: Add indirect thunk support and remove this.
1304 if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
1305 report_fatal_error("Emitting stack probe calls on 64-bit with the large "
1306 "code model and indirect thunks not yet implemented.");
1307
1308 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1310 "Stack probe calls will clobber live EFLAGS.");
1311
1312 unsigned CallOp;
1313 if (Is64Bit)
1314 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
1315 else
1316 CallOp = X86::CALLpcrel32;
1317
1318 StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
1319
1320 MachineInstrBuilder CI;
1321 MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
1322
1323 // All current stack probes take AX and SP as input, clobber flags, and
1324 // preserve all registers. x86_64 probes leave RSP unmodified.
1326 // For the large code model, we have to call through a register. Use R11,
1327 // as it is scratch in all supported calling conventions.
1328 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
1330 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
1331 } else {
1332 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
1334 }
1335
1336 unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
1337 unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
1338 bool EmitSPSub = STI.isTargetWin64() || !STI.isOSWindows();
1339
1343 getDeadRegState(!EmitSPSub))
1345 .addReg(X86::EFLAGS,
1347
1348 MachineInstr *ModInst = CI;
1349 if (EmitSPSub) {
1350 // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
1351 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
1352 // themselves. They also does not clobber %rax so we can reuse it when
1353 // adjusting %rsp.
1354 // All other platforms do not specify a particular ABI for the stack probe
1355 // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
1356 ModInst =
1358 .addReg(SP)
1359 .addReg(AX)
1360 .setOperandDead(3); // implicit-def $eflags
1361 }
1362
1363 // DebugInfo variable locations -- if there's an instruction number for the
1364 // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
1365 // modifies SP.
1366 if (InstrNum) {
1367 if (EmitSPSub) {
1368 // Label destination operand of the subtract.
1369 MF.makeDebugValueSubstitution(*InstrNum,
1370 {ModInst->getDebugInstrNum(), 0});
1371 } else {
1372 // Label the call. The operand number is the penultimate operand, zero
1373 // based.
1374 unsigned SPDefOperand = ModInst->getNumOperands() - 2;
1376 *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
1377 }
1378 }
1379
1380 if (InProlog) {
1381 // Apply the frame setup flag to all inserted instrs.
1382 for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
1383 ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
1384 }
1385}
1386
1387static unsigned calculateSetFPREG(uint64_t SPAdjust) {
1388 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
1389 // and might require smaller successive adjustments.
1390 const uint64_t Win64MaxSEHOffset = 128;
1391 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
1392 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
1393 return SEHFrameOffset & -16;
1394}
1395
1396// If we're forcing a stack realignment we can't rely on just the frame
1397// info, we need to know the ABI stack alignment as well in case we
1398// have a call out. Otherwise just make sure we have some alignment - we'll
1399// go with the minimum SlotSize.
1401X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
1402 const MachineFrameInfo &MFI = MF.getFrameInfo();
1403 Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
1404 Align StackAlign = getStackAlign();
1405 bool HasRealign = MF.getFunction().hasFnAttribute("stackrealign");
1406 if (HasRealign) {
1407 if (MFI.hasCalls())
1408 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
1409 else if (MaxAlign < SlotSize)
1410 MaxAlign = Align(SlotSize);
1411 }
1412
1414 MaxAlign = std::max(MaxAlign, Align(16));
1415
1416 return MaxAlign.value();
1417}
1418
1419void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
1421 const DebugLoc &DL, Register Reg,
1422 uint64_t MaxAlign) const {
1423 uint64_t Val = -MaxAlign;
1424 unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1425
1426 MachineFunction &MF = *MBB.getParent();
1427 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1428 const X86TargetLowering &TLI = *STI.getTargetLowering();
1429 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1430 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1431
1432 // We want to make sure that (in worst case) less than StackProbeSize bytes
1433 // are not probed after the AND. This assumption is used in
1434 // emitStackProbeInlineGeneric.
1435 if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1436 {
1437 NumFrameLoopProbe++;
1438 MachineBasicBlock *entryMBB =
1440 MachineBasicBlock *headMBB =
1442 MachineBasicBlock *bodyMBB =
1444 MachineBasicBlock *footMBB =
1446
1448 MF.insert(MBBIter, entryMBB);
1449 MF.insert(MBBIter, headMBB);
1450 MF.insert(MBBIter, bodyMBB);
1451 MF.insert(MBBIter, footMBB);
1452 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
1453 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
1454 : Is64Bit ? X86::R11D
1455 : X86::EAX;
1456
1457 // Setup entry block
1458 {
1459
1460 entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1461 BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1464 MachineInstr *MI =
1465 BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1466 .addReg(FinalStackProbed)
1467 .addImm(Val)
1469
1470 // The EFLAGS implicit def is dead.
1471 MI->getOperand(3).setIsDead();
1472
1473 BuildMI(entryMBB, DL,
1474 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1475 .addReg(FinalStackProbed)
1478 BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1479 .addMBB(&MBB)
1482 entryMBB->addSuccessor(headMBB);
1483 entryMBB->addSuccessor(&MBB);
1484 }
1485
1486 // Loop entry block
1487
1488 {
1489 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1490 BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1492 .addImm(StackProbeSize)
1494 .setOperandDead(3); // implicit-def $eflags
1495
1496 BuildMI(headMBB, DL,
1497 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1499 .addReg(FinalStackProbed)
1501
1502 // jump to the footer if StackPtr < FinalStackProbed
1503 BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1504 .addMBB(footMBB)
1507
1508 headMBB->addSuccessor(bodyMBB);
1509 headMBB->addSuccessor(footMBB);
1510 }
1511
1512 // setup loop body
1513 {
1514 addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1516 StackPtr, 0)
1517 .addImm(0)
1519
1520 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1521 BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1523 .addImm(StackProbeSize)
1525 .setOperandDead(3); // implicit-def $eflags
1526
1527 // cmp with stack pointer bound
1528 BuildMI(bodyMBB, DL,
1529 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1530 .addReg(FinalStackProbed)
1533
1534 // jump back while FinalStackProbed < StackPtr
1535 BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1536 .addMBB(bodyMBB)
1539 bodyMBB->addSuccessor(bodyMBB);
1540 bodyMBB->addSuccessor(footMBB);
1541 }
1542
1543 // setup loop footer
1544 {
1545 BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1546 .addReg(FinalStackProbed)
1548 addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1550 StackPtr, 0)
1551 .addImm(0)
1553 footMBB->addSuccessor(&MBB);
1554 }
1555
1556 fullyRecomputeLiveIns({footMBB, bodyMBB, headMBB, &MBB});
1557 }
1558 } else {
1559 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
1560 .addReg(Reg)
1561 .addImm(Val)
1563
1564 // The EFLAGS implicit def is dead.
1565 MI->getOperand(3).setIsDead();
1566 }
1567}
1568
1570 // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
1571 // clobbered by any interrupt handler.
1572 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1573 "MF used frame lowering for wrong subtarget");
1574 const Function &Fn = MF.getFunction();
1575 const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
1576 return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
1577}
1578
1579bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1580 return !MF.usesWindowsUnwindInfo() && MF.needsFrameMoves();
1581}
1582
1583/// Return true if an opcode is part of the REP group of instructions
1584static bool isOpcodeRep(unsigned Opcode) {
1585 switch (Opcode) {
1586 case X86::REPNE_PREFIX:
1587 case X86::REP_MOVSB_32:
1588 case X86::REP_MOVSB_64:
1589 case X86::REP_MOVSD_32:
1590 case X86::REP_MOVSD_64:
1591 case X86::REP_MOVSQ_32:
1592 case X86::REP_MOVSQ_64:
1593 case X86::REP_MOVSW_32:
1594 case X86::REP_MOVSW_64:
1595 case X86::REP_PREFIX:
1596 case X86::REP_STOSB_32:
1597 case X86::REP_STOSB_64:
1598 case X86::REP_STOSD_32:
1599 case X86::REP_STOSD_64:
1600 case X86::REP_STOSQ_32:
1601 case X86::REP_STOSQ_64:
1602 case X86::REP_STOSW_32:
1603 case X86::REP_STOSW_64:
1604 return true;
1605 default:
1606 break;
1607 }
1608 return false;
1609}
1610
1611/// Returns the number of bytes between the end of the fixed and callee-save
1612/// area and the first local object, which PEI leaves as padding when it aligns
1613/// the local objects relative to the incoming stack pointer.
1615 int64_t FixedEnd = 0;
1616 int64_t LocalsTop = std::numeric_limits<int64_t>::max();
1617 for (int I : seq(MFI.getObjectIndexBegin(), MFI.getObjectIndexEnd())) {
1620 continue;
1621
1622 int64_t ObjOffset = MFI.getObjectOffset(I);
1623 int64_t ObjSize = MFI.getObjectSize(I);
1624 // Offsets are negative, measured from the incoming stack pointer.
1625 if (MFI.isFixedObjectIndex(I))
1626 FixedEnd = std::max(FixedEnd, -ObjOffset);
1627 else
1628 LocalsTop = std::min<int64_t>(LocalsTop, -ObjOffset - ObjSize);
1629 }
1630 if (LocalsTop == std::numeric_limits<int64_t>::max())
1631 return 0;
1632
1633 assert(LocalsTop >= FixedEnd && "Local object overlaps the fixed area");
1634 return LocalsTop - FixedEnd;
1635}
1636
1637/// emitPrologue - Push callee-saved registers onto the stack, which
1638/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
1639/// space for local variables. Also emit labels used by the exception handler to
1640/// generate the exception handling frames.
1641
1642/*
1643 Here's a gist of what gets emitted:
1644
1645 ; Establish frame pointer, if needed
1646 [if needs FP]
1647 push %rbp
1648 .cfi_def_cfa_offset 16
1649 .cfi_offset %rbp, -16
1650 .seh_pushreg %rpb
1651 mov %rsp, %rbp
1652 .cfi_def_cfa_register %rbp
1653
1654 ; Spill general-purpose registers
1655 [for all callee-saved GPRs]
1656 pushq %<reg>
1657 [if not needs FP]
1658 .cfi_def_cfa_offset (offset from RETADDR)
1659 .seh_pushreg %<reg>
1660
1661 ; If the required stack alignment > default stack alignment
1662 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
1663 ; of unknown size in the stack frame.
1664 [if stack needs re-alignment]
1665 and $MASK, %rsp
1666
1667 ; Allocate space for locals
1668 [if target is Windows and allocated space > 4096 bytes]
1669 ; Windows needs special care for allocations larger
1670 ; than one page.
1671 mov $NNN, %rax
1672 call ___chkstk_ms/___chkstk
1673 sub %rax, %rsp
1674 [else]
1675 sub $NNN, %rsp
1676
1677 [if needs FP]
1678 .seh_stackalloc (size of XMM spill slots)
1679 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
1680 [else]
1681 .seh_stackalloc NNN
1682
1683 ; Spill XMMs
1684 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
1685 ; they may get spilled on any platform, if the current function
1686 ; calls @llvm.eh.unwind.init
1687 [if needs FP]
1688 [for all callee-saved XMM registers]
1689 movaps %<xmm reg>, -MMM(%rbp)
1690 [for all callee-saved XMM registers]
1691 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
1692 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
1693 [else]
1694 [for all callee-saved XMM registers]
1695 movaps %<xmm reg>, KKK(%rsp)
1696 [for all callee-saved XMM registers]
1697 .seh_savexmm %<xmm reg>, KKK
1698
1699 .seh_endprologue
1700
1701 [if needs base pointer]
1702 mov %rsp, %rbx
1703 [if needs to restore base pointer]
1704 mov %rsp, -MMM(%rbp)
1705
1706 ; Emit CFI info
1707 [if needs FP]
1708 [for all callee-saved registers]
1709 .cfi_offset %<reg>, (offset from %rbp)
1710 [else]
1711 .cfi_def_cfa_offset (offset from RETADDR)
1712 [for all callee-saved registers]
1713 .cfi_offset %<reg>, (offset from %rsp)
1714
1715 Notes:
1716 - .seh directives are emitted only for Windows 64 ABI
1717 - .cv_fpo directives are emitted on win32 when emitting CodeView
1718 - .cfi directives are emitted for all other ABIs
1719 - for 32-bit code, substitute %e?? registers for %r??
1720*/
1721
1723 MachineBasicBlock &MBB) const {
1724 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1725 "MF used frame lowering for wrong subtarget");
1727 MachineFrameInfo &MFI = MF.getFrameInfo();
1728 const Function &Fn = MF.getFunction();
1730 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
1731 uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate.
1732 bool IsFunclet = MBB.isEHFuncletEntry();
1734 if (Fn.hasPersonalityFn())
1735 Personality = classifyEHPersonality(Fn.getPersonalityFn());
1736 bool FnHasClrFunclet =
1737 MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
1738 bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
1739 bool HasFP = hasFP(MF);
1740 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
1741 bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
1742 // FIXME: Emit FPO data for EH funclets.
1743 bool NeedsWinFPO = !IsFunclet && STI.isTargetWin32() &&
1745 bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1746 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1747 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
1748 Register FramePtr = TRI->getFrameRegister(MF);
1749 const Register MachineFramePtr =
1750 STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
1751 : FramePtr;
1752 Register BasePtr = TRI->getBaseRegister();
1753 bool HasWinCFI = false;
1754
1755 // Helpers to emit Windows x64 unwind SEH pseudos with the correct placement.
1756 // V1/V2: pseudo goes after the real instruction.
1757 // V3: pseudo goes before the real instruction.
1758 // Usage:
1759 // EmitSEHBefore([&]{ BuildMI(...SEH_PushReg...); });
1760 // BuildMI(... real instruction ...);
1761 // EmitSEHAfter([&]{ BuildMI(...SEH_PushReg...); });
1762 auto EmitSEHBefore = [&](auto EmitFn) {
1763 if (NeedsWinCFI && IsWin64UnwindV3) {
1764 HasWinCFI = true;
1765 EmitFn();
1766 }
1767 };
1768 auto EmitSEHAfter = [&](auto EmitFn) {
1769 if (NeedsWinCFI && !IsWin64UnwindV3) {
1770 HasWinCFI = true;
1771 EmitFn();
1772 }
1773 };
1774
1775 // Debug location must be unknown since the first debug location is used
1776 // to determine the end of the prologue.
1777 DebugLoc DL;
1778 Register ArgBaseReg;
1779
1780 // Emit extra prolog for argument stack slot reference.
1781 if (auto *MI = X86FI->getStackPtrSaveMI()) {
1782 // MI is lea instruction that created in X86ArgumentStackSlotPass.
1783 // Creat extra prolog for stack realignment.
1784 ArgBaseReg = MI->getOperand(0).getReg();
1785 // leal 4(%esp), %basereg
1786 // .cfi_def_cfa %basereg, 0
1787 // andl $-128, %esp
1788 // pushl -4(%basereg)
1789 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::LEA64r : X86::LEA32r),
1790 ArgBaseReg)
1792 .addImm(1)
1793 .addUse(X86::NoRegister)
1795 .addUse(X86::NoRegister)
1797 if (NeedsDwarfCFI) {
1798 // .cfi_def_cfa %basereg, 0
1799 unsigned DwarfStackPtr = TRI->getDwarfRegNum(ArgBaseReg, true);
1800 BuildCFI(MBB, MBBI, DL,
1801 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 0),
1803 }
1804 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1805 int64_t Offset = -(int64_t)SlotSize;
1806 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm))
1807 .addReg(ArgBaseReg)
1808 .addImm(1)
1809 .addReg(X86::NoRegister)
1810 .addImm(Offset)
1811 .addReg(X86::NoRegister)
1813 }
1814
1815 // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1816 // tail call.
1817 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1818 if (TailCallArgReserveSize && IsWin64Prologue)
1819 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
1820
1821 const bool EmitStackProbeCall =
1822 STI.getTargetLowering()->hasStackProbeSymbol(MF);
1823 unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
1824
1825 if (HasFP && X86FI->hasSwiftAsyncContext()) {
1828 if (STI.swiftAsyncContextIsDynamicallySet()) {
1829 // The special symbol below is absolute and has a *value* suitable to be
1830 // combined with the frame pointer directly.
1831 BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1832 .addUse(MachineFramePtr)
1833 .addUse(X86::RIP)
1834 .addImm(1)
1835 .addUse(X86::NoRegister)
1836 .addExternalSymbol("swift_async_extendedFramePointerFlags",
1838 .addUse(X86::NoRegister);
1839 break;
1840 }
1841 [[fallthrough]];
1842
1844 assert(
1845 !IsWin64Prologue &&
1846 "win64 prologue does not set the bit 60 in the saved frame pointer");
1847 BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1848 .addUse(MachineFramePtr)
1849 .addImm(60)
1851 break;
1852
1854 break;
1855 }
1856 }
1857
1858 // Re-align the stack on 64-bit if the x86-interrupt calling convention is
1859 // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
1860 // stack alignment.
1862 Fn.arg_size() == 2) {
1863 // Update the stack pointer by pushing a register. This is the instruction
1864 // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1865 // Hard-coding the update to a push avoids emitting a second
1866 // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1867 // probing isn't needed anyways for an 8-byte update.
1868 // Pushing a register leaves us in a similar situation to a regular
1869 // function call where we know that the address at (rsp-8) is writeable.
1870 // That way we avoid any off-by-ones with stack probing for additional
1871 // stack pointer updates later on.
1872 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1873 .addReg(X86::RAX, RegState::Undef)
1875 }
1876
1877 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
1878 // function, and use up to 128 bytes of stack space, don't have a frame
1879 // pointer, calls, or dynamic alloca then we do not need to adjust the
1880 // stack pointer (we fit in the Red Zone). We also check that we don't
1881 // push and pop from the stack.
1882 if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
1883 !MFI.hasVarSizedObjects() && // No dynamic alloca.
1884 !MFI.adjustsStack() && // No calls.
1885 !EmitStackProbeCall && // No stack probes.
1886 !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
1887 !MF.shouldSplitStack()) { // Regular stack
1888 uint64_t MinSize =
1890 if (HasFP)
1891 MinSize += SlotSize;
1892 X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
1893 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
1894 MFI.setStackSize(StackSize);
1895 }
1896
1897 // Insert stack pointer adjustment for later moving of return addr. Only
1898 // applies to tail call optimized functions where the callee argument stack
1899 // size is bigger than the callers.
1900 if (TailCallArgReserveSize != 0) {
1901 BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
1902 /*InEpilogue=*/false)
1903 .setMIFlag(MachineInstr::FrameSetup);
1904 }
1905
1906 // Mapping for machine moves:
1907 //
1908 // DST: VirtualFP AND
1909 // SRC: VirtualFP => DW_CFA_def_cfa_offset
1910 // ELSE => DW_CFA_def_cfa
1911 //
1912 // SRC: VirtualFP AND
1913 // DST: Register => DW_CFA_def_cfa_register
1914 //
1915 // ELSE
1916 // OFFSET < 0 => DW_CFA_offset_extended_sf
1917 // REG < 64 => DW_CFA_offset + Reg
1918 // ELSE => DW_CFA_offset_extended
1919
1920 uint64_t NumBytes = 0;
1921 int stackGrowth = -SlotSize;
1922
1923 // Find the funclet establisher parameter
1924 MCRegister Establisher;
1925 if (IsClrFunclet)
1926 Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1927 else if (IsFunclet)
1928 Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1929
1930 if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1931 // Immediately spill establisher into the home slot.
1932 // The runtime cares about this.
1933 // MOV64mr %rdx, 16(%rsp)
1934 unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1935 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, 16)
1936 .addReg(Establisher)
1938 MBB.addLiveIn(Establisher);
1939 }
1940
1941 if (HasFP) {
1942 assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
1943
1944 // Calculate required stack adjustment.
1945 uint64_t FrameSize = StackSize - SlotSize;
1946 NumBytes =
1947 FrameSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
1948
1949 // Callee-saved registers are pushed on stack before the stack is realigned,
1950 // and the realignment itself already provides the local objects' alignment,
1951 // so leave out the padding PEI put in front of them for it.
1952 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue) {
1953 uint64_t Padding = getUnusedLocalAreaPadding(MFI);
1954 assert(Padding <= NumBytes && "Padding exceeds the local area");
1955 NumBytes = alignTo(NumBytes - Padding, MaxAlign);
1956 }
1957
1958 // Save EBP/RBP into the appropriate stack slot.
1959 auto EmitSEHPushFramePtr = [&]() {
1960 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1963 };
1964 EmitSEHBefore(EmitSEHPushFramePtr);
1965 BuildMI(MBB, MBBI, DL,
1967 .addReg(MachineFramePtr, RegState::Kill)
1969 EmitSEHAfter(EmitSEHPushFramePtr);
1970
1971 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1972 // Mark the place where EBP/RBP was saved.
1973 // Define the current CFA rule to use the provided offset.
1974 assert(StackSize);
1975 BuildCFI(MBB, MBBI, DL,
1977 nullptr, -2 * stackGrowth + (int)TailCallArgReserveSize),
1979
1980 // Change the rule for the FramePtr to be an "offset" rule.
1981 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1982 BuildCFI(MBB, MBBI, DL,
1983 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
1984 2 * stackGrowth -
1985 (int)TailCallArgReserveSize),
1987 }
1988
1989 if (!IsFunclet) {
1990 if (X86FI->hasSwiftAsyncContext()) {
1991 assert(!IsWin64Prologue &&
1992 "win64 prologue does not store async context right below rbp");
1993 const auto &Attrs = MF.getFunction().getAttributes();
1994
1995 // Before we update the live frame pointer we have to ensure there's a
1996 // valid (or null) asynchronous context in its slot just before FP in
1997 // the frame record, so store it now.
1998 auto EmitSEHPushR14 = [&]() {
1999 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2000 .addImm(X86::R14)
2002 };
2003 EmitSEHBefore(EmitSEHPushR14);
2004 if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
2005 // We have an initial context in r14, store it just before the frame
2006 // pointer.
2007 MBB.addLiveIn(X86::R14);
2008 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2009 .addReg(X86::R14)
2011 } else {
2012 // No initial context, store null so that there's no pointer that
2013 // could be misused.
2014 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i32))
2015 .addImm(0)
2017 }
2018
2019 // Update CFA offset for the async-context push.
2020 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
2021 BuildCFI(
2022 MBB, MBBI, DL,
2023 MCCFIInstruction::createAdjustCfaOffset(nullptr, -stackGrowth),
2025 }
2026
2027 EmitSEHAfter(EmitSEHPushR14);
2028
2029 BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
2030 .addUse(X86::RSP)
2031 .addImm(1)
2032 .addUse(X86::NoRegister)
2033 .addImm(8)
2034 .addUse(X86::NoRegister)
2036
2037 // Switch to an FP-relative CFA before adjusting RSP below.
2038 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
2039 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2040 BuildCFI(MBB, MBBI, DL,
2041 MCCFIInstruction::cfiDefCfa(nullptr, DwarfFramePtr,
2042 -2 * stackGrowth +
2043 (int)TailCallArgReserveSize),
2045 }
2046
2047 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri32), X86::RSP)
2048 .addUse(X86::RSP)
2049 .addImm(8)
2051 }
2052
2053 if (!IsWin64Prologue && !IsFunclet) {
2054 // Update EBP with the new base value.
2055 if (!X86FI->hasSwiftAsyncContext())
2056 BuildMI(MBB, MBBI, DL,
2057 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
2058 FramePtr)
2061
2062 if (NeedsDwarfCFI) {
2063 if (ArgBaseReg.isValid()) {
2064 SmallString<64> CfaExpr;
2065 CfaExpr.push_back(dwarf::DW_CFA_expression);
2066 uint8_t buffer[16];
2067 unsigned DwarfReg = TRI->getDwarfRegNum(MachineFramePtr, true);
2068 CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
2069 CfaExpr.push_back(2);
2070 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
2071 CfaExpr.push_back(0);
2072 // DW_CFA_expression: reg5 DW_OP_breg5 +0
2073 BuildCFI(MBB, MBBI, DL,
2074 MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
2076 } else if (!X86FI->hasSwiftAsyncContext()) {
2077 // Mark effective beginning of when frame pointer becomes valid.
2078 // Define the current CFA to use the EBP/RBP register.
2079 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2080 BuildCFI(
2081 MBB, MBBI, DL,
2082 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
2084 }
2085 }
2086
2087 if (NeedsWinFPO) {
2088 // .cv_fpo_setframe $FramePtr
2089 // NeedsWinFPO is Win32 only, so we're never using Unwind v3, hence it
2090 // is always inserted afterwards.
2091 assert(!IsWin64UnwindV3);
2092 HasWinCFI = true;
2093 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2095 .addImm(0)
2097 }
2098 }
2099 }
2100 } else {
2101 assert(!IsFunclet && "funclets without FPs not yet implemented");
2102 NumBytes =
2103 StackSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
2104 }
2105
2106 // Update the offset adjustment, which is mainly used by codeview to translate
2107 // from ESP to VFRAME relative local variable offsets.
2108 if (!IsFunclet) {
2109 if (HasFP && TRI->hasStackRealignment(MF))
2110 MFI.setOffsetAdjustment(-NumBytes);
2111 else
2112 MFI.setOffsetAdjustment(-StackSize);
2113 }
2114
2115 // For EH funclets, only allocate enough space for outgoing calls. Save the
2116 // NumBytes value that we would've used for the parent frame.
2117 unsigned ParentFrameNumBytes = NumBytes;
2118 if (IsFunclet)
2119 NumBytes = getWinEHFuncletFrameSize(MF);
2120
2121 // Skip the callee-saved push instructions.
2122 bool PushedRegs = false;
2123 int StackOffset = 2 * stackGrowth;
2125 auto IsCSPush = [&](const MachineBasicBlock::iterator &MBBI) {
2126 if (MBBI == MBB.end() || !MBBI->getFlag(MachineInstr::FrameSetup))
2127 return false;
2128 unsigned Opc = MBBI->getOpcode();
2129 return Opc == X86::PUSH32r || Opc == X86::PUSH64r || Opc == X86::PUSHP64r ||
2130 Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2131 };
2132
2133 while (IsCSPush(MBBI)) {
2134 PushedRegs = true;
2135 Register Reg = MBBI->getOperand(0).getReg();
2136 LastCSPush = MBBI;
2137 unsigned Opc = LastCSPush->getOpcode();
2138 bool IsPush2 = Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2139
2140 // V3: emit SEH pseudo before the real instruction.
2141 EmitSEHBefore([&]() {
2142 if (IsPush2) {
2143 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Push2Regs))
2144 .addImm(Reg)
2145 .addImm(LastCSPush->getOperand(1).getReg())
2147 } else {
2148 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2149 .addImm(Reg)
2151 }
2152 });
2153 ++MBBI;
2154
2155 if (!HasFP && NeedsDwarfCFI) {
2156 // Mark callee-saved push instruction.
2157 // Define the current CFA rule to use the provided offset.
2158 assert(StackSize);
2159 // Compared to push, push2 introduces more stack offset (one more
2160 // register).
2161 if (IsPush2)
2162 StackOffset += stackGrowth;
2163 BuildCFI(MBB, MBBI, DL,
2166 StackOffset += stackGrowth;
2167 }
2168
2169 // V1/V2: emit SEH pseudo after the real instruction.
2170 EmitSEHAfter([&]() {
2171 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2172 .addImm(Reg)
2174 if (IsPush2)
2175 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2176 .addImm(LastCSPush->getOperand(1).getReg())
2178 });
2179 }
2180
2181 // Realign stack after we pushed callee-saved registers (so that we'll be
2182 // able to calculate their offsets from the frame pointer).
2183 // Don't do this for Win64, it needs to realign the stack after the prologue.
2184 if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) &&
2185 !ArgBaseReg.isValid()) {
2186 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2187 auto EmitSEHStackAlign = [&]() {
2188 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
2189 .addImm(MaxAlign)
2191 };
2192 EmitSEHBefore(EmitSEHStackAlign);
2193 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
2194 EmitSEHAfter(EmitSEHStackAlign);
2195 }
2196
2197 // If there is an SUB32ri of ESP immediately before this instruction, merge
2198 // the two. This can be the case when tail call elimination is enabled and
2199 // the callee has more arguments than the caller.
2200 NumBytes = mergeSPUpdates(
2201 MBB, MBBI, [NumBytes](int64_t Offset) { return NumBytes - Offset; },
2202 true);
2203
2204 // Adjust stack pointer: ESP -= numbytes.
2205
2206 // Windows and cygwin/mingw require a prologue helper routine when allocating
2207 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
2208 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
2209 // stack and adjust the stack pointer in one go. The 64-bit version of
2210 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
2211 // responsible for adjusting the stack pointer. Touching the stack at 4K
2212 // increments is necessary to ensure that the guard pages used by the OS
2213 // virtual memory manager are allocated in correct sequence.
2214 uint64_t AlignedNumBytes = NumBytes;
2215 if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
2216 AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
2217
2218 auto EmitSEHStackAlloc = [&]() {
2219 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2220 .addImm(NumBytes)
2222 };
2223 if (NumBytes)
2224 EmitSEHBefore(EmitSEHStackAlloc);
2225
2226 if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
2227 assert(!X86FI->getUsesRedZone() &&
2228 "The Red Zone is not accounted for in stack probes");
2229
2230 // Check whether EAX is livein for this block.
2231 bool isEAXAlive = isEAXLiveIn(MBB);
2232
2233 if (isEAXAlive) {
2234 if (Is64Bit) {
2235 // Save RAX
2236 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2237 .addReg(X86::RAX, RegState::Kill)
2239 } else {
2240 // Save EAX
2241 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
2242 .addReg(X86::EAX, RegState::Kill)
2244 }
2245 }
2246
2247 if (Is64Bit) {
2248 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
2249 // Function prologue is responsible for adjusting the stack pointer.
2250 int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
2252 X86::RAX)
2253 .addImm(Alloc)
2255 } else {
2256 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
2257 // We'll also use 4 already allocated bytes for EAX.
2258 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
2259 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
2261 }
2262
2263 // Call __chkstk, __chkstk_ms, or __alloca.
2264 emitStackProbe(MF, MBB, MBBI, DL, true);
2265
2266 if (isEAXAlive) {
2267 // Restore RAX/EAX
2269 if (Is64Bit)
2270 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
2271 StackPtr, NumBytes - 8);
2272 else
2273 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
2274 StackPtr, NumBytes - 4);
2275 MI->setFlag(MachineInstr::FrameSetup);
2276 MBB.insert(MBBI, MI);
2277 }
2278 } else if (NumBytes) {
2279 emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
2280 }
2281
2282 if (NumBytes)
2283 EmitSEHAfter(EmitSEHStackAlloc);
2284
2285 int SEHFrameOffset = 0;
2286 Register SPOrEstablisher;
2287 if (IsFunclet) {
2288 if (IsClrFunclet) {
2289 // The establisher parameter passed to a CLR funclet is actually a pointer
2290 // to the (mostly empty) frame of its nearest enclosing funclet; we have
2291 // to find the root function establisher frame by loading the PSPSym from
2292 // the intermediate frame.
2293 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2294 MachinePointerInfo NoInfo;
2295 MBB.addLiveIn(Establisher);
2296 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
2297 Establisher, PSPSlotOffset)
2300 ;
2301 // Save the root establisher back into the current funclet's (mostly
2302 // empty) frame, in case a sub-funclet or the GC needs it.
2303 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
2304 PSPSlotOffset)
2305 .addReg(Establisher)
2307 NoInfo,
2310 }
2311 SPOrEstablisher = Establisher;
2312 } else {
2313 SPOrEstablisher = StackPtr;
2314 }
2315
2316 if (IsWin64Prologue && HasFP) {
2317 // Set RBP to a small fixed offset from RSP. In the funclet case, we base
2318 // this calculation on the incoming establisher, which holds the value of
2319 // RSP from the parent frame at the end of the prologue.
2320 SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
2321
2322 // If this is not a funclet, emit the CFI describing our frame pointer.
2323 if (NeedsWinCFI && !IsFunclet) {
2324 assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
2325 HasWinCFI = true;
2326 if (isAsynchronousEHPersonality(Personality) || MF.hasEHFunclets()) {
2327 if (TRI->hasBasePointer(MF))
2330 else
2331 MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
2332 }
2333 }
2334
2335 auto EmitSEHSetFrame = [&]() {
2336 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2338 .addImm(SEHFrameOffset)
2340 };
2341
2342 if (!IsFunclet)
2343 EmitSEHBefore(EmitSEHSetFrame);
2344
2345 if (SEHFrameOffset)
2346 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
2347 SPOrEstablisher, SEHFrameOffset);
2348 else
2349 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
2350 .addReg(SPOrEstablisher);
2351
2352 if (!IsFunclet)
2353 EmitSEHAfter(EmitSEHSetFrame);
2354 } else if (IsFunclet && STI.is32Bit()) {
2355 // Reset EBP / ESI to something good for funclets.
2357 // If we're a catch funclet, we can be returned to via catchret. Save ESP
2358 // into the registration node so that the runtime will restore it for us.
2359 if (!MBB.isCleanupFuncletEntry()) {
2360 assert(Personality == EHPersonality::MSVC_CXX);
2361 Register FrameReg;
2363 int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
2364 // ESP is the first field, so no extra displacement is needed.
2365 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
2366 EHRegOffset)
2367 .addReg(X86::ESP);
2368 }
2369 }
2370
2371 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
2372 const MachineInstr &FrameInstr = *MBBI;
2373
2374 if (NeedsWinCFI) {
2375 int FI;
2376 if (Register Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
2377 if (X86::FR64RegClass.contains(Reg)) {
2378 int Offset;
2379 Register IgnoredFrameReg;
2380 if (IsWin64Prologue && IsFunclet)
2381 Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
2382 else
2383 Offset =
2384 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2385 SEHFrameOffset;
2386
2387 assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
2388 auto EmitSEHSaveXMM = [&]() {
2389 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
2390 .addImm(Reg)
2391 .addImm(Offset)
2393 };
2394 EmitSEHBefore(EmitSEHSaveXMM);
2395 ++MBBI;
2396 EmitSEHAfter(EmitSEHSaveXMM);
2397 continue;
2398 }
2399 }
2400 }
2401 ++MBBI;
2402 }
2403
2404 if (NeedsWinCFI && HasWinCFI) {
2405 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
2407 }
2408
2409 if (FnHasClrFunclet && !IsFunclet) {
2410 // Save the so-called Initial-SP (i.e. the value of the stack pointer
2411 // immediately after the prolog) into the PSPSlot so that funclets
2412 // and the GC can recover it.
2413 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2414 auto PSPInfo = MachinePointerInfo::getFixedStack(
2416 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
2417 PSPSlotOffset)
2422 }
2423
2424 // Realign stack after we spilled callee-saved registers (so that we'll be
2425 // able to calculate their offsets from the frame pointer).
2426 // Win64 requires aligning the stack after the prologue.
2427 if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
2428 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2429 BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
2430 }
2431
2432 // We already dealt with stack realignment and funclets above.
2433 if (IsFunclet && STI.is32Bit())
2434 return;
2435
2436 // If we need a base pointer, set it up here. It's whatever the value
2437 // of the stack pointer is at this point. Any variable size objects
2438 // will be allocated after this, so we can still use the base pointer
2439 // to reference locals.
2440 if (TRI->hasBasePointer(MF)) {
2441 // Update the base pointer with the current stack pointer.
2442 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
2443 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
2444 .addReg(SPOrEstablisher)
2446 if (X86FI->getRestoreBasePointer()) {
2447 // Stash value of base pointer. Saving RSP instead of EBP shortens
2448 // dependence chain. Used by SjLj EH.
2449 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2450 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), FramePtr,
2452 .addReg(SPOrEstablisher)
2454 }
2455
2456 if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
2457 // Stash the value of the frame pointer relative to the base pointer for
2458 // Win32 EH. This supports Win32 EH, which does the inverse of the above:
2459 // it recovers the frame pointer from the base pointer rather than the
2460 // other way around.
2461 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2462 Register UsedReg;
2463 int Offset =
2464 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2465 .getFixed();
2466 assert(UsedReg == BasePtr);
2467 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, Offset)
2470 }
2471 }
2472 if (ArgBaseReg.isValid()) {
2473 // Save argument base pointer.
2474 auto *MI = X86FI->getStackPtrSaveMI();
2475 int FI = MI->getOperand(1).getIndex();
2476 unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
2477 // movl %basereg, offset(%ebp)
2478 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), FI)
2479 .addReg(ArgBaseReg)
2481 }
2482
2483 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
2484 // Mark end of stack pointer adjustment.
2485 if (!HasFP && NumBytes) {
2486 // Define the current CFA rule to use the provided offset.
2487 assert(StackSize);
2488 BuildCFI(
2489 MBB, MBBI, DL,
2490 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
2492 }
2493
2494 // Emit DWARF info specifying the offsets of the callee-saved registers.
2496 }
2497
2498 // X86 Interrupt handling function cannot assume anything about the direction
2499 // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
2500 // in each prologue of interrupt handler function.
2501 //
2502 // Create "cld" instruction only in these cases:
2503 // 1. The interrupt handling function uses any of the "rep" instructions.
2504 // 2. Interrupt handling function calls another function.
2505 // 3. If there are any inline asm blocks, as we do not know what they do
2506 //
2507 // TODO: We should also emit cld if we detect the use of std, but as of now,
2508 // the compiler does not even emit that instruction or even define it, so in
2509 // practice, this would only happen with inline asm, which we cover anyway.
2511 bool NeedsCLD = false;
2512
2513 for (const MachineBasicBlock &B : MF) {
2514 for (const MachineInstr &MI : B) {
2515 if (MI.isCall()) {
2516 NeedsCLD = true;
2517 break;
2518 }
2519
2520 if (isOpcodeRep(MI.getOpcode())) {
2521 NeedsCLD = true;
2522 break;
2523 }
2524
2525 if (MI.isInlineAsm()) {
2526 // TODO: Parse asm for rep instructions or call sites?
2527 // For now, let's play it safe and emit a cld instruction
2528 // just in case.
2529 NeedsCLD = true;
2530 break;
2531 }
2532 }
2533 }
2534
2535 if (NeedsCLD) {
2536 BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
2538 }
2539 }
2540
2541 // At this point we know if the function has WinCFI or not.
2542 MF.setHasWinCFI(HasWinCFI);
2543}
2544
2546 const MachineFunction &MF) const {
2547 // We can't use LEA instructions for adjusting the stack pointer if we don't
2548 // have a frame pointer in the Win64 ABI. Only ADD instructions may be used
2549 // to deallocate the stack.
2550 // This means that we can use LEA for SP in two situations:
2551 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
2552 // 2. We *have* a frame pointer which means we are permitted to use LEA.
2553 return !MF.usesWindowsUnwindInfo() || hasFP(MF);
2554}
2555
2557 switch (MI.getOpcode()) {
2558 case X86::CATCHRET:
2559 case X86::CLEANUPRET:
2560 return true;
2561 default:
2562 return false;
2563 }
2564 llvm_unreachable("impossible");
2565}
2566
2567// CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
2568// stack. It holds a pointer to the bottom of the root function frame. The
2569// establisher frame pointer passed to a nested funclet may point to the
2570// (mostly empty) frame of its parent funclet, but it will need to find
2571// the frame of the root function to access locals. To facilitate this,
2572// every funclet copies the pointer to the bottom of the root function
2573// frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
2574// same offset for the PSPSym in the root function frame that's used in the
2575// funclets' frames allows each funclet to dynamically accept any ancestor
2576// frame as its establisher argument (the runtime doesn't guarantee the
2577// immediate parent for some reason lost to history), and also allows the GC,
2578// which uses the PSPSym for some bookkeeping, to find it in any funclet's
2579// frame with only a single offset reported for the entire method.
2580unsigned
2581X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
2582 const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
2584 int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2585 /*IgnoreSPUpdates*/ true)
2586 .getFixed();
2587 assert(Offset >= 0 && SPReg == TRI->getStackRegister());
2588 return static_cast<unsigned>(Offset);
2589}
2590
2591unsigned
2592X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2593 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2594 // This is the size of the pushed CSRs.
2595 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2596 // This is the size of callee saved XMMs.
2597 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2598 unsigned XMMSize =
2599 WinEHXMMSlotInfo.size() * TRI->getSpillSize(X86::VR128RegClass);
2600 // This is the amount of stack a funclet needs to allocate.
2601 unsigned UsedSize;
2602 EHPersonality Personality =
2604 if (Personality == EHPersonality::CoreCLR) {
2605 // CLR funclets need to hold enough space to include the PSPSym, at the
2606 // same offset from the stack pointer (immediately after the prolog) as it
2607 // resides at in the main function.
2608 UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
2609 } else {
2610 // Other funclets just need enough stack for outgoing call arguments.
2611 UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
2612 }
2613 // RBP is not included in the callee saved register block. After pushing RBP,
2614 // everything is 16 byte aligned. Everything we allocate before an outgoing
2615 // call must also be 16 byte aligned.
2616 unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
2617 // Subtract out the size of the callee saved registers. This is how much stack
2618 // each funclet will allocate.
2619 return FrameSizeMinusRBP + XMMSize - CSSize;
2620}
2621
2622static bool isTailCallOpcode(unsigned Opc) {
2623 return Opc == X86::TCRETURNri || Opc == X86::TCRETURN_WIN64ri ||
2624 Opc == X86::TCRETURN_HIPE32ri || Opc == X86::TCRETURNdi ||
2625 Opc == X86::TCRETURNmi || Opc == X86::TCRETURNri64 ||
2626 Opc == X86::TCRETURNri64_ImpCall || Opc == X86::TCRETURNdi64 ||
2627 Opc == X86::TCRETURNmi64 || Opc == X86::TCRETURN_WINmi64;
2628}
2629
2631 MachineBasicBlock &MBB) const {
2632 const MachineFrameInfo &MFI = MF.getFrameInfo();
2634 MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
2635 MachineBasicBlock::iterator MBBI = Terminator;
2636 DebugLoc DL;
2637 if (MBBI != MBB.end())
2638 DL = MBBI->getDebugLoc();
2639 // standard x86_64 uses 64-bit frame/stack pointers, x32 - 32-bit.
2640 const bool Is64BitILP32 = STI.isTarget64BitILP32();
2641 Register FramePtr = TRI->getFrameRegister(MF);
2642 Register MachineFramePtr =
2643 Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
2644
2645 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
2646 bool NeedsWin64CFI =
2647 IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
2648 // For V3 unwind, epilog SEH pseudos are emitted inline before each
2649 // unwind-effecting instruction.
2650 bool IsWin64UnwindV3 =
2651 NeedsWin64CFI && MF.hasWinCFI() && requireWinX64UnwindV3(MF);
2652 bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
2653
2654 // Get the number of bytes to allocate from the FrameInfo.
2655 uint64_t StackSize = MFI.getStackSize();
2656 uint64_t MaxAlign = calculateMaxStackAlign(MF);
2657 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2658 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
2659 bool HasFP = hasFP(MF);
2660 uint64_t NumBytes = 0;
2661
2662 bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
2664 !MF.getTarget().getTargetTriple().isUEFI()) &&
2665 MF.needsFrameMoves();
2666
2667 Register ArgBaseReg;
2668 if (auto *MI = X86FI->getStackPtrSaveMI()) {
2669 unsigned Opc = X86::LEA32r;
2670 Register StackReg = X86::ESP;
2671 ArgBaseReg = MI->getOperand(0).getReg();
2672 if (STI.is64Bit()) {
2673 Opc = X86::LEA64r;
2674 StackReg = X86::RSP;
2675 }
2676 // leal -4(%basereg), %esp
2677 // .cfi_def_cfa %esp, 4
2678 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackReg)
2679 .addUse(ArgBaseReg)
2680 .addImm(1)
2681 .addUse(X86::NoRegister)
2682 .addImm(-(int64_t)SlotSize)
2683 .addUse(X86::NoRegister)
2685 if (NeedsDwarfCFI) {
2686 unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackReg, true);
2687 BuildCFI(MBB, MBBI, DL,
2688 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2690 --MBBI;
2691 }
2692 --MBBI;
2693 }
2694
2695 if (IsFunclet) {
2696 assert(HasFP && "EH funclets without FP not yet implemented");
2697 NumBytes = getWinEHFuncletFrameSize(MF);
2698 } else if (HasFP) {
2699 // Calculate required stack adjustment.
2700 uint64_t FrameSize = StackSize - SlotSize;
2701 NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
2702
2703 // Callee-saved registers were pushed on stack before the stack was
2704 // realigned.
2705 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
2706 NumBytes = alignTo(FrameSize, MaxAlign);
2707 } else {
2708 NumBytes = StackSize - CSSize - TailCallArgReserveSize;
2709 }
2710 uint64_t SEHStackAllocAmt = NumBytes;
2711
2712 unsigned SEHFrameOffset = 0;
2713 if (IsWin64Prologue && HasFP)
2714 SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
2715
2716 // AfterPop is the position to insert .cfi_restore.
2718 if (HasFP) {
2719 if (X86FI->hasSwiftAsyncContext()) {
2720 // Discard the context.
2721 int64_t Offset = mergeSPAdd(MBB, MBBI, 16, true);
2722 emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/ true);
2723 }
2724 // Pop EBP.
2725 if (IsWin64UnwindV3)
2726 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2729 BuildMI(MBB, MBBI, DL,
2731 MachineFramePtr)
2733
2734 // We need to reset FP to its untagged state on return. Bit 60 is currently
2735 // used to show the presence of an extended frame.
2736 if (X86FI->hasSwiftAsyncContext()) {
2737 BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8), MachineFramePtr)
2738 .addUse(MachineFramePtr)
2739 .addImm(60)
2741 }
2742
2743 if (NeedsDwarfCFI) {
2744 if (!ArgBaseReg.isValid()) {
2745 unsigned DwarfStackPtr =
2746 TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
2747 BuildCFI(MBB, MBBI, DL,
2748 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2750 }
2751 if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
2752 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2753 BuildCFI(MBB, AfterPop, DL,
2754 MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
2756 --MBBI;
2757 --AfterPop;
2758 }
2759 --MBBI;
2760 }
2761 }
2762
2763 MachineBasicBlock::iterator FirstCSPop = MBBI;
2764 // Skip the callee-saved pop instructions.
2765 while (MBBI != MBB.begin()) {
2766 MachineBasicBlock::iterator PI = std::prev(MBBI);
2767 unsigned Opc = PI->getOpcode();
2768
2769 if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
2770 if (!PI->getFlag(MachineInstr::FrameDestroy) ||
2771 (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::BTR64ri8 &&
2772 Opc != X86::ADD64ri32 && Opc != X86::POPP64r && Opc != X86::POP2 &&
2773 Opc != X86::POP2P && Opc != X86::LEA64r && Opc != X86::SEH_PushReg &&
2774 Opc != X86::SEH_Push2Regs && Opc != X86::SEH_StackAlloc &&
2775 Opc != X86::ADD64ri32_NF))
2776 break;
2777 FirstCSPop = PI;
2778 }
2779
2780 --MBBI;
2781 }
2782 if (ArgBaseReg.isValid()) {
2783 // Restore argument base pointer.
2784 auto *MI = X86FI->getStackPtrSaveMI();
2785 int FI = MI->getOperand(1).getIndex();
2786 unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm;
2787 // movl offset(%ebp), %basereg
2788 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVrm), ArgBaseReg), FI)
2790 }
2791 MBBI = FirstCSPop;
2792
2793 if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
2794 emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
2795
2796 if (MBBI != MBB.end())
2797 DL = MBBI->getDebugLoc();
2798 // If there is an ADD32ri or SUB32ri of ESP immediately before this
2799 // instruction, merge the two instructions.
2800 if (NumBytes || MFI.hasVarSizedObjects())
2801 NumBytes = mergeSPAdd(MBB, MBBI, NumBytes, true);
2802
2803 if (IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI()) {
2804 // Find the XMM restores that were tagged with FrameDestroy, now that we
2805 // know the offset we can emit the SEH pseudos for them.
2806 auto EpilogStart = MBBI;
2807 {
2808 auto ScanIt = MBBI;
2809 while (ScanIt != MBB.begin()) {
2810 auto PI = std::prev(ScanIt);
2811 int FI;
2812 if (PI->getFlag(MachineInstr::FrameDestroy) &&
2813 TII.isLoadFromStackSlot(*PI, FI)) {
2814 Register Reg = PI->getOperand(0).getReg();
2815 if (X86::FR64RegClass.contains(Reg)) {
2816 Register IgnoredFrameReg;
2817 int Offset =
2818 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2819 SEHFrameOffset;
2820 BuildMI(MBB, PI, DL, TII.get(X86::SEH_SaveXMM))
2821 .addImm(Reg)
2822 .addImm(Offset)
2824 // std::prev(PI) is the SEH_SaveXMM we just inserted (before PI).
2825 // We start ScanIt from that point so that the next
2826 // std::prev(ScanIt) will examine the instruction before the pseudo,
2827 // i.e. the next potential XMM restore further up the block.
2828 EpilogStart = std::prev(PI);
2829 ScanIt = EpilogStart;
2830 continue;
2831 }
2832 }
2833 break;
2834 }
2835 }
2836
2837 // For V3, SEH_BeginEpilogue must be emitted before any epilog SEH pseudos.
2838 BuildMI(MBB, EpilogStart, DL, TII.get(X86::SEH_BeginEpilogue))
2840 }
2841
2842 // If dynamic alloca is used, then reset esp to point to the last callee-saved
2843 // slot before popping them off! Same applies for the case, when stack was
2844 // realigned. Don't do this if this was a funclet epilogue, since the funclets
2845 // will not do realignment or dynamic stack allocation.
2846 if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
2847 !IsFunclet) {
2848 if (TRI->hasStackRealignment(MF))
2849 MBBI = FirstCSPop;
2850 uint64_t LEAAmount =
2851 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
2852
2853 if (X86FI->hasSwiftAsyncContext())
2854 LEAAmount -= 16;
2855
2856 // There are only two legal forms of epilogue:
2857 // - add SEHAllocationSize, %rsp
2858 // - lea SEHAllocationSize(%FramePtr), %rsp
2859 //
2860 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
2861 // However, we may use this sequence if we have a frame pointer because the
2862 // effects of the prologue can safely be undone.
2863 if (IsWin64UnwindV3) {
2864 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2866 .addImm(SEHFrameOffset)
2868 if (SEHStackAllocAmt)
2869 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2870 .addImm(SEHStackAllocAmt)
2872 }
2873 if (LEAAmount != 0) {
2876 LEAAmount);
2877 --MBBI;
2878 } else {
2879 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
2881 --MBBI;
2882 }
2883 } else if (NumBytes) {
2884 // Adjust stack pointer back: ESP += numbytes.
2885 if (IsWin64UnwindV3)
2886 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2887 .addImm(NumBytes)
2889 emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2890 if (!HasFP && NeedsDwarfCFI) {
2891 // Define the current CFA rule to use the provided offset.
2892 BuildCFI(MBB, MBBI, DL,
2894 nullptr, CSSize + TailCallArgReserveSize + SlotSize),
2896 }
2897 --MBBI;
2898 }
2899
2900 // For V1/V2, emit SEH_BeginEpilogue after stack restore code.
2901 if (!IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI())
2902 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_BeginEpilogue))
2904
2905 if (!HasFP && NeedsDwarfCFI) {
2906 MBBI = FirstCSPop;
2907 int64_t Offset = -(int64_t)CSSize - SlotSize;
2908 // Mark callee-saved pop instruction.
2909 // Define the current CFA rule to use the provided offset.
2910 while (MBBI != MBB.end()) {
2912 unsigned Opc = PI->getOpcode();
2913 ++MBBI;
2914 if (Opc == X86::POP32r || Opc == X86::POP64r || Opc == X86::POPP64r ||
2915 Opc == X86::POP2 || Opc == X86::POP2P) {
2916 Offset += SlotSize;
2917 // Compared to pop, pop2 introduces more stack offset (one more
2918 // register).
2919 if (Opc == X86::POP2 || Opc == X86::POP2P)
2920 Offset += SlotSize;
2921 BuildCFI(MBB, MBBI, DL,
2924 }
2925 }
2926 }
2927
2928 // Emit DWARF info specifying the restores of the callee-saved registers.
2929 // For epilogue with return inside or being other block without successor,
2930 // no need to generate .cfi_restore for callee-saved registers.
2931 if (NeedsDwarfCFI && !MBB.succ_empty())
2932 emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
2933
2934 if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
2935 // Add the return addr area delta back since we are not tail calling.
2936 int64_t Delta = X86FI->getTCReturnAddrDelta();
2937 assert(Delta <= 0 && "TCDelta should never be positive");
2938 if (Delta) {
2939 // Check for possible merge with preceding ADD instruction.
2940 int64_t Offset = mergeSPAdd(MBB, Terminator, -Delta, true);
2941 emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
2942 }
2943 }
2944
2945 // Emit tilerelease for AMX/ACE kernel.
2948 BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
2949
2950 if (NeedsWin64CFI && MF.hasWinCFI())
2951 BuildMI(MBB, Terminator, DL, TII.get(X86::SEH_EndEpilogue))
2953}
2954
2956 int FI,
2957 Register &FrameReg) const {
2958 const MachineFrameInfo &MFI = MF.getFrameInfo();
2959
2960 bool IsFixed = MFI.isFixedObjectIndex(FI);
2961 // We can't calculate offset from frame pointer if the stack is realigned,
2962 // so enforce usage of stack/base pointer. The base pointer is used when we
2963 // have dynamic allocas in addition to dynamic realignment.
2964 if (TRI->hasBasePointer(MF))
2965 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2966 else if (TRI->hasStackRealignment(MF))
2967 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
2968 else
2969 FrameReg = TRI->getFrameRegister(MF);
2970
2971 // Offset will hold the offset from the stack pointer at function entry to the
2972 // object.
2973 // We need to factor in additional offsets applied during the prologue to the
2974 // frame, base, and stack pointer depending on which is used.
2975 int64_t Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
2977 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2978 uint64_t StackSize = MFI.getStackSize();
2979 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
2980 int64_t FPDelta = 0;
2981
2982 // In an x86 interrupt, remove the offset we added to account for the return
2983 // address from any stack object allocated in the caller's frame. Interrupts
2984 // do not have a standard return address. Fixed objects in the current frame,
2985 // such as SSE register spills, should not get this treatment.
2987 Offset >= 0) {
2989 }
2990
2991 if (IsWin64Prologue) {
2992 assert(!MFI.hasCalls() || (StackSize % 16) == 8);
2993
2994 // Calculate required stack adjustment.
2995 uint64_t FrameSize = StackSize - SlotSize;
2996 // If required, include space for extra hidden slot for stashing base
2997 // pointer.
2998 if (X86FI->getRestoreBasePointer())
2999 FrameSize += SlotSize;
3000 uint64_t NumBytes = FrameSize - CSSize;
3001
3002 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
3003 if (FI && FI == X86FI->getFAIndex())
3004 return StackOffset::getFixed(-SEHFrameOffset);
3005
3006 // FPDelta is the offset from the "traditional" FP location of the old base
3007 // pointer followed by return address and the location required by the
3008 // restricted Win64 prologue.
3009 // Add FPDelta to all offsets below that go through the frame pointer.
3010 FPDelta = FrameSize - SEHFrameOffset;
3011 assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
3012 "FPDelta isn't aligned per the Win64 ABI!");
3013 }
3014
3015 if (FrameReg == TRI->getFramePtr()) {
3016 // Skip saved EBP/RBP
3017 Offset += SlotSize;
3018
3019 // Account for restricted Windows prologue.
3020 Offset += FPDelta;
3021
3022 // Skip the RETADDR move area
3023 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
3024 if (TailCallReturnAddrDelta < 0)
3025 Offset -= TailCallReturnAddrDelta;
3026
3028 }
3029
3030 // FrameReg is either the stack pointer or a base pointer. But the base is
3031 // located at the end of the statically known StackSize so the distinction
3032 // doesn't really matter.
3033 if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
3034 assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
3035 return StackOffset::getFixed(Offset + StackSize);
3036}
3037
3039 Register &FrameReg) const {
3040 const MachineFrameInfo &MFI = MF.getFrameInfo();
3042 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
3043 const auto it = WinEHXMMSlotInfo.find(FI);
3044
3045 if (it == WinEHXMMSlotInfo.end())
3046 return getFrameIndexReference(MF, FI, FrameReg).getFixed();
3047
3048 FrameReg = TRI->getStackRegister();
3049 return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
3050 it->second;
3051}
3052
3055 Register &FrameReg,
3056 int Adjustment) const {
3057 const MachineFrameInfo &MFI = MF.getFrameInfo();
3058 FrameReg = TRI->getStackRegister();
3059 return StackOffset::getFixed(MFI.getObjectOffset(FI) -
3060 getOffsetOfLocalArea() + Adjustment);
3061}
3062
3065 int FI, Register &FrameReg,
3066 bool IgnoreSPUpdates) const {
3067
3068 const MachineFrameInfo &MFI = MF.getFrameInfo();
3069 // Does not include any dynamic realign.
3070 const uint64_t StackSize = MFI.getStackSize();
3071 // LLVM arranges the stack as follows:
3072 // ...
3073 // ARG2
3074 // ARG1
3075 // RETADDR
3076 // PUSH RBP <-- RBP points here
3077 // PUSH CSRs
3078 // ~~~~~~~ <-- possible stack realignment (non-win64)
3079 // ...
3080 // STACK OBJECTS
3081 // ... <-- RSP after prologue points here
3082 // ~~~~~~~ <-- possible stack realignment (win64)
3083 //
3084 // if (hasVarSizedObjects()):
3085 // ... <-- "base pointer" (ESI/RBX) points here
3086 // DYNAMIC ALLOCAS
3087 // ... <-- RSP points here
3088 //
3089 // Case 1: In the simple case of no stack realignment and no dynamic
3090 // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
3091 // with fixed offsets from RSP.
3092 //
3093 // Case 2: In the case of stack realignment with no dynamic allocas, fixed
3094 // stack objects are addressed with RBP and regular stack objects with RSP.
3095 //
3096 // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
3097 // to address stack arguments for outgoing calls and nothing else. The "base
3098 // pointer" points to local variables, and RBP points to fixed objects.
3099 //
3100 // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
3101 // answer we give is relative to the SP after the prologue, and not the
3102 // SP in the middle of the function.
3103
3104 if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
3105 !STI.isTargetWin64())
3106 return getFrameIndexReference(MF, FI, FrameReg);
3107
3108 // If !hasReservedCallFrame the function might have SP adjustement in the
3109 // body. So, even though the offset is statically known, it depends on where
3110 // we are in the function.
3111 if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
3112 return getFrameIndexReference(MF, FI, FrameReg);
3113
3114 // We don't handle tail calls, and shouldn't be seeing them either.
3116 "we don't handle this case!");
3117
3118 // This is how the math works out:
3119 //
3120 // %rsp grows (i.e. gets lower) left to right. Each box below is
3121 // one word (eight bytes). Obj0 is the stack slot we're trying to
3122 // get to.
3123 //
3124 // ----------------------------------
3125 // | BP | Obj0 | Obj1 | ... | ObjN |
3126 // ----------------------------------
3127 // ^ ^ ^ ^
3128 // A B C E
3129 //
3130 // A is the incoming stack pointer.
3131 // (B - A) is the local area offset (-8 for x86-64) [1]
3132 // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
3133 //
3134 // |(E - B)| is the StackSize (absolute value, positive). For a
3135 // stack that grown down, this works out to be (B - E). [3]
3136 //
3137 // E is also the value of %rsp after stack has been set up, and we
3138 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
3139 // (C - E) == (C - A) - (B - A) + (B - E)
3140 // { Using [1], [2] and [3] above }
3141 // == getObjectOffset - LocalAreaOffset + StackSize
3142
3143 return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
3144}
3145
3148 std::vector<CalleeSavedInfo> &CSI) const {
3149 MachineFrameInfo &MFI = MF.getFrameInfo();
3151
3152 unsigned CalleeSavedFrameSize = 0;
3153 unsigned XMMCalleeSavedFrameSize = 0;
3154 auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
3155 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
3156
3157 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
3158
3159 if (TailCallReturnAddrDelta < 0) {
3160 // create RETURNADDR area
3161 // arg
3162 // arg
3163 // RETADDR
3164 // { ...
3165 // RETADDR area
3166 // ...
3167 // }
3168 // [EBP]
3169 MFI.CreateFixedObject(-TailCallReturnAddrDelta,
3170 TailCallReturnAddrDelta - SlotSize, true);
3171 }
3172
3173 // Spill the BasePtr if it's used.
3174 if (this->TRI->hasBasePointer(MF)) {
3175 // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
3176 if (MF.hasEHFunclets()) {
3178 X86FI->setHasSEHFramePtrSave(true);
3179 X86FI->setSEHFramePtrSaveIndex(FI);
3180 }
3181 }
3182
3183 bool IsFPRemovedFromCSI = false;
3184 if (hasFP(MF)) {
3185 // emitPrologue always spills frame register the first thing.
3186 SpillSlotOffset -= SlotSize;
3187 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3188
3189 // The async context lives directly before the frame pointer, and we
3190 // allocate a second slot to preserve stack alignment.
3191 if (X86FI->hasSwiftAsyncContext()) {
3192 SpillSlotOffset -= SlotSize;
3193 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3194 SpillSlotOffset -= SlotSize;
3195 }
3196
3197 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
3198 // the frame register, we can delete it from CSI list and not have to worry
3199 // about avoiding it later.
3200 Register FPReg = TRI->getFrameRegister(MF);
3201 for (unsigned i = 0; i < CSI.size(); ++i) {
3202 if (TRI->regsOverlap(CSI[i].getReg(), FPReg)) {
3203 CSI.erase(CSI.begin() + i);
3204 IsFPRemovedFromCSI = true;
3205 break;
3206 }
3207 }
3208 }
3209
3210 // Strategy:
3211 // 1. Use push2 when
3212 // a) number of CSR > 1 if no need padding
3213 // b) number of CSR > 2 if need padding
3214 // c) stack alignment >= 16 bytes
3215 // 2. When the number of CSR push is odd
3216 // a. Start to use push2 from the 1st push if stack is 16B aligned.
3217 // b. Start to use push2 from the 2nd push if stack is not 16B aligned.
3218 // 3. When the number of CSR push is even, start to use push2 from the 1st
3219 // push and make the stack 16B aligned before the push
3220 unsigned NumRegsForPush2 = 0;
3221 if (STI.hasPush2Pop2() && getStackAlignment() >= 16) {
3222 unsigned NumCSGPR = llvm::count_if(CSI, [](const CalleeSavedInfo &I) {
3223 return X86::GR64RegClass.contains(I.getReg());
3224 });
3225 bool UsePush2Pop2 = !IsFPRemovedFromCSI ? NumCSGPR > 2 : NumCSGPR > 1;
3226 NumRegsForPush2 =
3227 UsePush2Pop2
3228 ? alignDown(IsFPRemovedFromCSI ? NumCSGPR : NumCSGPR - 1, 2)
3229 : 0;
3230 }
3231
3232 // Assign slots for GPRs. It increases frame size.
3233 for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
3234 MCRegister Reg = I.getReg();
3235
3236 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3237 continue;
3238
3239 // A CSR is a candidate for push2/pop2 when it's slot offset is 16B aligned
3240 // or only an odd number of registers in the candidates.
3241 if (X86FI->getNumCandidatesForPush2Pop2() < NumRegsForPush2 &&
3242 (SpillSlotOffset % 16 == 0 ||
3243 X86FI->getNumCandidatesForPush2Pop2() % 2))
3244 X86FI->addCandidateForPush2Pop2(Reg);
3245
3246 SpillSlotOffset -= SlotSize;
3247 CalleeSavedFrameSize += SlotSize;
3248
3249 int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3250 I.setFrameIdx(SlotIndex);
3251 }
3252
3253 // Adjust the offset of spill slot as we know the accurate callee saved frame
3254 // size.
3255 if (X86FI->getRestoreBasePointer()) {
3256 SpillSlotOffset -= SlotSize;
3257 CalleeSavedFrameSize += SlotSize;
3258
3259 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3260 // TODO: saving the slot index is better?
3261 X86FI->setRestoreBasePointer(CalleeSavedFrameSize);
3262 }
3263 assert(X86FI->getNumCandidatesForPush2Pop2() % 2 == 0 &&
3264 "Expect even candidates for push2/pop2");
3265 if (X86FI->getNumCandidatesForPush2Pop2())
3266 ++NumFunctionUsingPush2Pop2;
3267 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
3268 MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
3269
3270 // Assign slots for XMMs.
3271 for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
3272 MCRegister Reg = I.getReg();
3273 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3274 continue;
3275
3277 unsigned Size = TRI->getSpillSize(*RC);
3278 // The slot is fixed relative to the incoming stack pointer, so it cannot be
3279 // aligned beyond what that guarantees, even if the stack is realigned.
3280 Align Alignment = std::min(TRI->getSpillAlign(*RC), getStackAlign());
3281 // ensure alignment
3282 assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
3283 SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
3284
3285 // spill into slot
3286 SpillSlotOffset -= Size;
3287 int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
3288 I.setFrameIdx(SlotIndex);
3289 MFI.ensureMaxAlignment(Alignment);
3290
3291 // Save the start offset and size of XMM in stack frame for funclets.
3292 if (X86::VR128RegClass.contains(Reg)) {
3293 WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
3294 XMMCalleeSavedFrameSize += Size;
3295 }
3296 }
3297
3298 return true;
3299}
3300
3304 DebugLoc DL = MBB.findDebugLoc(MI);
3305
3306 // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
3307 // for us, and there are no XMM CSRs on Win32.
3308 if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
3309 return true;
3310
3311 // Push GPRs. It increases frame size.
3312 const MachineFunction &MF = *MBB.getParent();
3314
3315 // Update LiveIn of the basic block and decide whether we can add a kill flag
3316 // to the use.
3317 auto UpdateLiveInCheckCanKill = [&](Register Reg) {
3318 const MachineRegisterInfo &MRI = MF.getRegInfo();
3319 // Do not set a kill flag on values that are also marked as live-in. This
3320 // happens with the @llvm-returnaddress intrinsic and with arguments
3321 // passed in callee saved registers.
3322 // Omitting the kill flags is conservatively correct even if the live-in
3323 // is not used after all.
3324 if (MRI.isLiveIn(Reg))
3325 return false;
3326 MBB.addLiveIn(Reg);
3327 // Check if any subregister is live-in
3328 for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg)
3329 if (MRI.isLiveIn(*AReg))
3330 return false;
3331 return true;
3332 };
3333 auto UpdateLiveInGetKillRegState = [&](Register Reg) {
3334 return getKillRegState(UpdateLiveInCheckCanKill(Reg));
3335 };
3336
3337 for (auto RI = CSI.rbegin(), RE = CSI.rend(); RI != RE; ++RI) {
3338 MCRegister Reg = RI->getReg();
3339 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3340 continue;
3341
3342 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3343 MCRegister Reg2 = (++RI)->getReg();
3345 .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
3346 .addReg(Reg2, UpdateLiveInGetKillRegState(Reg2))
3348 } else {
3349 BuildMI(MBB, MI, DL, TII.get(getPUSHOpcode(STI)))
3350 .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
3352 }
3353 }
3354
3355 if (X86FI->getRestoreBasePointer()) {
3356 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
3357 Register BaseReg = this->TRI->getBaseRegister();
3358 BuildMI(MBB, MI, DL, TII.get(Opc))
3359 .addReg(BaseReg, getKillRegState(true))
3361 }
3362
3363 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
3364 // It can be done by spilling XMMs to stack frame.
3365 for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
3366 MCRegister Reg = I.getReg();
3367 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3368 continue;
3369
3370 // Add the callee-saved register as live-in. It's killed at the spill.
3371 MBB.addLiveIn(Reg);
3373
3374 TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, Register(),
3376 }
3377
3378 return true;
3379}
3380
3381void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
3383 MachineInstr *CatchRet) const {
3384 // SEH shouldn't use catchret.
3386 MBB.getParent()->getFunction().getPersonalityFn())) &&
3387 "SEH should not use CATCHRET");
3388 const DebugLoc &DL = CatchRet->getDebugLoc();
3389 MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
3390
3391 // Fill EAX/RAX with the address of the target block.
3392 if (STI.is64Bit()) {
3393 // LEA64r CatchRetTarget(%rip), %rax
3394 BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
3395 .addReg(X86::RIP)
3396 .addImm(0)
3397 .addReg(0)
3398 .addMBB(CatchRetTarget)
3399 .addReg(0);
3400 } else {
3401 // MOV32ri $CatchRetTarget, %eax
3402 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
3403 .addMBB(CatchRetTarget);
3404 }
3405
3406 // Record that we've taken the address of CatchRetTarget and no longer just
3407 // reference it in a terminator.
3408 CatchRetTarget->setMachineBlockAddressTaken();
3409}
3410
3414 if (CSI.empty())
3415 return false;
3416
3417 if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
3418 // Don't restore CSRs in 32-bit EH funclets. Matches
3419 // spillCalleeSavedRegisters.
3420 if (STI.is32Bit())
3421 return true;
3422 // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
3423 // funclets. emitEpilogue transforms these to normal jumps.
3424 if (MI->getOpcode() == X86::CATCHRET) {
3425 const Function &F = MBB.getParent()->getFunction();
3426 bool IsSEH = isAsynchronousEHPersonality(
3427 classifyEHPersonality(F.getPersonalityFn()));
3428 if (IsSEH)
3429 return true;
3430 }
3431 }
3432
3433 DebugLoc DL = MBB.findDebugLoc(MI);
3434 MachineFunction &MF = *MBB.getParent();
3436
3437 bool NeedsWin64CFI = MF.needsWinCFI();
3438 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
3439
3440 // Reload XMMs from stack frame.
3441 for (const CalleeSavedInfo &I : CSI) {
3442 MCRegister Reg = I.getReg();
3443 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3444 continue;
3445
3447 TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, Register(), 0,
3449 }
3450
3451 // Clear the stack slot for spill base pointer register.
3452 if (X86FI->getRestoreBasePointer()) {
3453 if (IsWin64UnwindV3)
3454 BuildMI(MBB, MI, DL, TII.get(X86::SEH_PushReg))
3455 .addImm(this->TRI->getBaseRegister())
3457 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
3458 Register BaseReg = this->TRI->getBaseRegister();
3459 BuildMI(MBB, MI, DL, TII.get(Opc), BaseReg)
3461 }
3462
3463 // POP GPRs.
3464 for (auto I = CSI.begin(), E = CSI.end(); I != E; ++I) {
3465 MCRegister Reg = I->getReg();
3466 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3467 continue;
3468
3469 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3470 MCRegister Reg2 = (++I)->getReg();
3471 if (IsWin64UnwindV3) {
3472 // Name the pair in PUSH2 order: the epilog op must describe the PUSH2
3473 // that this POP2 undoes.
3474 BuildMI(MBB, MI, DL, TII.get(X86::SEH_Push2Regs))
3475 .addImm(Reg2)
3476 .addImm(Reg)
3478 }
3479 BuildMI(MBB, MI, DL, TII.get(getPOP2Opcode(STI)), Reg)
3480 .addReg(Reg2, RegState::Define)
3482 } else {
3483 if (IsWin64UnwindV3)
3484 BuildMI(MBB, MI, DL, TII.get(X86::SEH_PushReg))
3485 .addImm(Reg)
3487 BuildMI(MBB, MI, DL, TII.get(getPOPOpcode(STI)), Reg)
3489 }
3490 }
3491
3492 return true;
3493}
3494
3496 BitVector &SavedRegs,
3497 RegScavenger *RS) const {
3499
3500 // Spill the BasePtr if it's used.
3501 if (TRI->hasBasePointer(MF)) {
3502 Register BasePtr = TRI->getBaseRegister();
3503 if (STI.isTarget64BitILP32())
3504 BasePtr = getX86SubSuperRegister(BasePtr, 64);
3505 SavedRegs.set(BasePtr);
3506 }
3507 if (STI.hasUserReservedRegisters()) {
3508 for (int Reg = SavedRegs.find_first(); Reg != -1;
3509 Reg = SavedRegs.find_next(Reg)) {
3510 if (STI.isRegisterReservedByUser(Reg)) {
3511 SavedRegs.reset(Reg);
3512 }
3513 }
3514 }
3515}
3516
3517static bool HasNestArgument(const MachineFunction *MF) {
3518 const Function &F = MF->getFunction();
3519 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3520 I++) {
3521 if (I->hasNestAttr() && !I->use_empty())
3522 return true;
3523 }
3524 return false;
3525}
3526
3527/// GetScratchRegister - Get a temp register for performing work in the
3528/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
3529/// and the properties of the function either one or two registers will be
3530/// needed. Set primary to true for the first register, false for the second.
3531static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64,
3532 const MachineFunction &MF, bool Primary) {
3533 CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
3534
3535 // Erlang stuff.
3536 if (CallingConvention == CallingConv::HiPE) {
3537 if (Is64Bit)
3538 return Primary ? X86::R14 : X86::R13;
3539 else
3540 return Primary ? X86::EBX : X86::EDI;
3541 }
3542
3543 if (Is64Bit) {
3544 if (IsLP64)
3545 return Primary ? X86::R11 : X86::R12;
3546 else
3547 return Primary ? X86::R11D : X86::R12D;
3548 }
3549
3550 bool IsNested = HasNestArgument(&MF);
3551
3552 if (CallingConvention == CallingConv::X86_FastCall ||
3553 CallingConvention == CallingConv::Fast ||
3554 CallingConvention == CallingConv::Tail) {
3555 if (IsNested)
3556 report_fatal_error("Segmented stacks does not support fastcall with "
3557 "nested function.");
3558 return Primary ? X86::EAX : X86::ECX;
3559 }
3560 if (IsNested)
3561 return Primary ? X86::EDX : X86::EAX;
3562 return Primary ? X86::ECX : X86::EAX;
3563}
3564
3565// The stack limit in the TCB is set to this many bytes above the actual stack
3566// limit.
3568
3570 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3571 MachineFrameInfo &MFI = MF.getFrameInfo();
3572 uint64_t StackSize;
3573 unsigned TlsReg, TlsOffset;
3574 DebugLoc DL;
3575
3576 // To support shrink-wrapping we would need to insert the new blocks
3577 // at the right place and update the branches to PrologueMBB.
3578 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3579
3580 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3581 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3582 "Scratch register is live-in");
3583
3584 if (MF.getFunction().isVarArg())
3585 report_fatal_error("Segmented stacks do not support vararg functions.");
3586 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
3587 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
3588 !STI.isTargetDragonFly())
3589 report_fatal_error("Segmented stacks not supported on this platform.");
3590
3591 // Eventually StackSize will be calculated by a link-time pass; which will
3592 // also decide whether checking code needs to be injected into this particular
3593 // prologue.
3594 StackSize = MFI.getStackSize();
3595
3596 if (!MFI.needsSplitStackProlog())
3597 return;
3598
3602 bool IsNested = false;
3603
3604 // We need to know if the function has a nest argument only in 64 bit mode.
3605 if (Is64Bit)
3606 IsNested = HasNestArgument(&MF);
3607
3608 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
3609 // allocMBB needs to be last (terminating) instruction.
3610
3611 for (const auto &LI : PrologueMBB.liveins()) {
3612 allocMBB->addLiveIn(LI);
3613 checkMBB->addLiveIn(LI);
3614 }
3615
3616 if (IsNested)
3617 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
3618
3619 MF.push_front(allocMBB);
3620 MF.push_front(checkMBB);
3621
3622 // When the frame size is less than 256 we just compare the stack
3623 // boundary directly to the value of the stack pointer, per gcc.
3624 bool CompareStackPointer = StackSize < kSplitStackAvailable;
3625
3626 // Read the limit off the current stacklet off the stack_guard location.
3627 if (Is64Bit) {
3628 if (STI.isTargetLinux()) {
3629 TlsReg = X86::FS;
3630 TlsOffset = IsLP64 ? 0x70 : 0x40;
3631 } else if (STI.isTargetDarwin()) {
3632 TlsReg = X86::GS;
3633 TlsOffset = 0x60 + 90 * 8; // See pthread_machdep.h. Steal TLS slot 90.
3634 } else if (STI.isTargetWin64()) {
3635 TlsReg = X86::GS;
3636 TlsOffset = 0x28; // pvArbitrary, reserved for application use
3637 } else if (STI.isTargetFreeBSD()) {
3638 TlsReg = X86::FS;
3639 TlsOffset = 0x18;
3640 } else if (STI.isTargetDragonFly()) {
3641 TlsReg = X86::FS;
3642 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
3643 } else {
3644 report_fatal_error("Segmented stacks not supported on this platform.");
3645 }
3646
3647 if (CompareStackPointer)
3648 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
3649 else
3650 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r),
3651 ScratchReg)
3652 .addReg(X86::RSP)
3653 .addImm(1)
3654 .addReg(0)
3655 .addImm(-StackSize)
3656 .addReg(0);
3657
3658 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm))
3659 .addReg(ScratchReg)
3660 .addReg(0)
3661 .addImm(1)
3662 .addReg(0)
3663 .addImm(TlsOffset)
3664 .addReg(TlsReg);
3665 } else {
3666 if (STI.isTargetLinux()) {
3667 TlsReg = X86::GS;
3668 TlsOffset = 0x30;
3669 } else if (STI.isTargetDarwin()) {
3670 TlsReg = X86::GS;
3671 TlsOffset = 0x48 + 90 * 4;
3672 } else if (STI.isTargetWin32()) {
3673 TlsReg = X86::FS;
3674 TlsOffset = 0x14; // pvArbitrary, reserved for application use
3675 } else if (STI.isTargetDragonFly()) {
3676 TlsReg = X86::FS;
3677 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
3678 } else if (STI.isTargetFreeBSD()) {
3679 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
3680 } else {
3681 report_fatal_error("Segmented stacks not supported on this platform.");
3682 }
3683
3684 if (CompareStackPointer)
3685 ScratchReg = X86::ESP;
3686 else
3687 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg)
3688 .addReg(X86::ESP)
3689 .addImm(1)
3690 .addReg(0)
3691 .addImm(-StackSize)
3692 .addReg(0);
3693
3694 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
3695 STI.isTargetDragonFly()) {
3696 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
3697 .addReg(ScratchReg)
3698 .addReg(0)
3699 .addImm(0)
3700 .addReg(0)
3701 .addImm(TlsOffset)
3702 .addReg(TlsReg);
3703 } else if (STI.isTargetDarwin()) {
3704
3705 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
3706 unsigned ScratchReg2;
3707 bool SaveScratch2;
3708 if (CompareStackPointer) {
3709 // The primary scratch register is available for holding the TLS offset.
3710 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3711 SaveScratch2 = false;
3712 } else {
3713 // Need to use a second register to hold the TLS offset
3714 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
3715
3716 // Unfortunately, with fastcc the second scratch register may hold an
3717 // argument.
3718 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
3719 }
3720
3721 // If Scratch2 is live-in then it needs to be saved.
3722 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
3723 "Scratch register is live-in and not saved");
3724
3725 if (SaveScratch2)
3726 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
3727 .addReg(ScratchReg2, RegState::Kill);
3728
3729 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
3730 .addImm(TlsOffset);
3731 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
3732 .addReg(ScratchReg)
3733 .addReg(ScratchReg2)
3734 .addImm(1)
3735 .addReg(0)
3736 .addImm(0)
3737 .addReg(TlsReg);
3738
3739 if (SaveScratch2)
3740 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
3741 }
3742 }
3743
3744 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
3745 // It jumps to normal execution of the function body.
3746 BuildMI(checkMBB, DL, TII.get(X86::JCC_1))
3747 .addMBB(&PrologueMBB)
3749
3750 // On 32 bit we first push the arguments size and then the frame size. On 64
3751 // bit, we pass the stack frame size in r10 and the argument size in r11.
3752 if (Is64Bit) {
3753 // Functions with nested arguments use R10, so it needs to be saved across
3754 // the call to _morestack
3755
3756 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
3757 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
3758 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
3759 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
3760
3761 if (IsNested)
3762 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
3763
3764 BuildMI(allocMBB, DL, TII.get(X86::getMOVriOpcode(IsLP64, StackSize)),
3765 Reg10)
3766 .addImm(StackSize);
3767 BuildMI(allocMBB, DL,
3769 Reg11)
3770 .addImm(X86FI->getArgumentStackSize());
3771 } else {
3772 BuildMI(allocMBB, DL, TII.get(X86::PUSH32i))
3773 .addImm(X86FI->getArgumentStackSize());
3774 BuildMI(allocMBB, DL, TII.get(X86::PUSH32i)).addImm(StackSize);
3775 }
3776
3777 // __morestack is in libgcc
3779 // Under the large code model, we cannot assume that __morestack lives
3780 // within 2^31 bytes of the call site, so we cannot use pc-relative
3781 // addressing. We cannot perform the call via a temporary register,
3782 // as the rax register may be used to store the static chain, and all
3783 // other suitable registers may be either callee-save or used for
3784 // parameter passing. We cannot use the stack at this point either
3785 // because __morestack manipulates the stack directly.
3786 //
3787 // To avoid these issues, perform an indirect call via a read-only memory
3788 // location containing the address.
3789 //
3790 // This solution is not perfect, as it assumes that the .rodata section
3791 // is laid out within 2^31 bytes of each function body, but this seems
3792 // to be sufficient for JIT.
3793 // FIXME: Add retpoline support and remove the error here..
3794 if (STI.useIndirectThunkCalls())
3795 report_fatal_error("Emitting morestack calls on 64-bit with the large "
3796 "code model and thunks not yet implemented.");
3797 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
3798 .addReg(X86::RIP)
3799 .addImm(0)
3800 .addReg(0)
3801 .addExternalSymbol("__morestack_addr")
3802 .addReg(0);
3803 } else {
3804 if (Is64Bit)
3805 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
3806 .addExternalSymbol("__morestack");
3807 else
3808 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
3809 .addExternalSymbol("__morestack");
3810 }
3811
3812 if (IsNested)
3813 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
3814 else
3815 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
3816
3817 allocMBB->addSuccessor(&PrologueMBB);
3818
3819 checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
3820 checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
3821
3822#ifdef EXPENSIVE_CHECKS
3823 MF.verify();
3824#endif
3825}
3826
3827/// Lookup an ERTS parameter in the !hipe.literals named metadata node.
3828/// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
3829/// to fields it needs, through a named metadata node "hipe.literals" containing
3830/// name-value pairs.
3831static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD,
3832 const StringRef LiteralName) {
3833 for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
3834 MDNode *Node = HiPELiteralsMD->getOperand(i);
3835 if (Node->getNumOperands() != 2)
3836 continue;
3837 MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
3838 ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
3839 if (!NodeName || !NodeVal)
3840 continue;
3841 ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
3842 if (ValConst && NodeName->getString() == LiteralName) {
3843 return ValConst->getZExtValue();
3844 }
3845 }
3846
3847 report_fatal_error("HiPE literal " + LiteralName +
3848 " required but not provided");
3849}
3850
3851// Return true if there are no non-ehpad successors to MBB and there are no
3852// non-meta instructions between MBBI and MBB.end().
3855 return llvm::all_of(
3856 MBB.successors(),
3857 [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
3858 std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
3859 return MI.isMetaInstruction();
3860 });
3861}
3862
3863/// Erlang programs may need a special prologue to handle the stack size they
3864/// might need at runtime. That is because Erlang/OTP does not implement a C
3865/// stack but uses a custom implementation of hybrid stack/heap architecture.
3866/// (for more information see Eric Stenman's Ph.D. thesis:
3867/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
3868///
3869/// CheckStack:
3870/// temp0 = sp - MaxStack
3871/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3872/// OldStart:
3873/// ...
3874/// IncStack:
3875/// call inc_stack # doubles the stack space
3876/// temp0 = sp - MaxStack
3877/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3879 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3880 MachineFrameInfo &MFI = MF.getFrameInfo();
3881 DebugLoc DL;
3882
3883 // To support shrink-wrapping we would need to insert the new blocks
3884 // at the right place and update the branches to PrologueMBB.
3885 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3886
3887 // HiPE-specific values
3888 NamedMDNode *HiPELiteralsMD =
3889 MF.getFunction().getParent()->getNamedMetadata("hipe.literals");
3890 if (!HiPELiteralsMD)
3892 "Can't generate HiPE prologue without runtime parameters");
3893 const unsigned HipeLeafWords = getHiPELiteral(
3894 HiPELiteralsMD, Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
3895 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
3896 const unsigned Guaranteed = HipeLeafWords * SlotSize;
3897 unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs
3898 ? MF.getFunction().arg_size() - CCRegisteredArgs
3899 : 0;
3900 unsigned MaxStack = MFI.getStackSize() + CallerStkArity * SlotSize + SlotSize;
3901
3902 assert(STI.isTargetLinux() &&
3903 "HiPE prologue is only supported on Linux operating systems.");
3904
3905 // Compute the largest caller's frame that is needed to fit the callees'
3906 // frames. This 'MaxStack' is computed from:
3907 //
3908 // a) the fixed frame size, which is the space needed for all spilled temps,
3909 // b) outgoing on-stack parameter areas, and
3910 // c) the minimum stack space this function needs to make available for the
3911 // functions it calls (a tunable ABI property).
3912 if (MFI.hasCalls()) {
3913 unsigned MoreStackForCalls = 0;
3914
3915 for (auto &MBB : MF) {
3916 for (auto &MI : MBB) {
3917 if (!MI.isCall())
3918 continue;
3919
3920 // Get callee operand.
3921 const MachineOperand &MO = MI.getOperand(0);
3922
3923 // Only take account of global function calls (no closures etc.).
3924 if (!MO.isGlobal())
3925 continue;
3926
3927 const Function *F = dyn_cast<Function>(MO.getGlobal());
3928 if (!F)
3929 continue;
3930
3931 // Do not update 'MaxStack' for primitive and built-in functions
3932 // (encoded with names either starting with "erlang."/"bif_" or not
3933 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
3934 // "_", such as the BIF "suspend_0") as they are executed on another
3935 // stack.
3936 if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
3937 F->getName().find_first_of("._") == StringRef::npos)
3938 continue;
3939
3940 unsigned CalleeStkArity = F->arg_size() > CCRegisteredArgs
3941 ? F->arg_size() - CCRegisteredArgs
3942 : 0;
3943 if (HipeLeafWords - 1 > CalleeStkArity)
3944 MoreStackForCalls =
3945 std::max(MoreStackForCalls,
3946 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
3947 }
3948 }
3949 MaxStack += MoreStackForCalls;
3950 }
3951
3952 // If the stack frame needed is larger than the guaranteed then runtime checks
3953 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
3954 if (MaxStack > Guaranteed) {
3955 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
3956 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
3957
3958 for (const auto &LI : PrologueMBB.liveins()) {
3959 stackCheckMBB->addLiveIn(LI);
3960 incStackMBB->addLiveIn(LI);
3961 }
3962
3963 MF.push_front(incStackMBB);
3964 MF.push_front(stackCheckMBB);
3965
3966 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
3967 unsigned LEAop, CMPop, CALLop;
3968 SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
3969 if (Is64Bit) {
3970 SPReg = X86::RSP;
3971 PReg = X86::RBP;
3972 LEAop = X86::LEA64r;
3973 CMPop = X86::CMP64rm;
3974 CALLop = X86::CALL64pcrel32;
3975 } else {
3976 SPReg = X86::ESP;
3977 PReg = X86::EBP;
3978 LEAop = X86::LEA32r;
3979 CMPop = X86::CMP32rm;
3980 CALLop = X86::CALLpcrel32;
3981 }
3982
3983 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3984 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3985 "HiPE prologue scratch register is live-in");
3986
3987 // Create new MBB for StackCheck:
3988 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
3989 -MaxStack);
3990 // SPLimitOffset is in a fixed heap location (pointed by BP).
3991 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
3992 PReg, SPLimitOffset);
3993 BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1))
3994 .addMBB(&PrologueMBB)
3996
3997 // Create new MBB for IncStack:
3998 BuildMI(incStackMBB, DL, TII.get(CALLop)).addExternalSymbol("inc_stack_0");
3999 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
4000 -MaxStack);
4001 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
4002 PReg, SPLimitOffset);
4003 BuildMI(incStackMBB, DL, TII.get(X86::JCC_1))
4004 .addMBB(incStackMBB)
4006
4007 stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
4008 stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
4009 incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
4010 incStackMBB->addSuccessor(incStackMBB, {1, 100});
4011 }
4012#ifdef EXPENSIVE_CHECKS
4013 MF.verify();
4014#endif
4015}
4016
4017bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
4019 const DebugLoc &DL,
4020 int Offset) const {
4021 if (Offset <= 0)
4022 return false;
4023
4024 if (Offset % SlotSize)
4025 return false;
4026
4027 int NumPops = Offset / SlotSize;
4028 // This is only worth it if we have at most 2 pops.
4029 if (NumPops != 1 && NumPops != 2)
4030 return false;
4031
4032 // Handle only the trivial case where the adjustment follows a call, ignoring
4033 // debug instructions. This is the most common one, anyway.
4034 if (MBBI == MBB.begin())
4035 return false;
4037 if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
4038 return false;
4039
4040 unsigned Regs[2];
4041 unsigned FoundRegs = 0;
4042
4043 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4044 const MachineOperand &RegMask = Prev->getOperand(1);
4045
4046 auto &RegClass =
4047 Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
4048 // Try to find up to NumPops free registers.
4049 for (auto Candidate : RegClass) {
4050 // Poor man's liveness:
4051 // Since we're immediately after a call, any register that is clobbered
4052 // by the call and not defined by it can be considered dead.
4053 if (!RegMask.clobbersPhysReg(Candidate))
4054 continue;
4055
4056 // Don't clobber reserved registers
4057 if (MRI.isReserved(Candidate))
4058 continue;
4059
4060 bool IsDef = false;
4061 for (const MachineOperand &MO : Prev->implicit_operands()) {
4062 if (MO.isReg() && MO.isDef() &&
4063 TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
4064 IsDef = true;
4065 break;
4066 }
4067 }
4068
4069 if (IsDef)
4070 continue;
4071
4072 Regs[FoundRegs++] = Candidate;
4073 if (FoundRegs == (unsigned)NumPops)
4074 break;
4075 }
4076
4077 if (FoundRegs == 0)
4078 return false;
4079
4080 // If we found only one free register, but need two, reuse the same one twice.
4081 while (FoundRegs < (unsigned)NumPops)
4082 Regs[FoundRegs++] = Regs[0];
4083
4084 for (int i = 0; i < NumPops; ++i)
4085 BuildMI(MBB, MBBI, DL, TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r),
4086 Regs[i]);
4087
4088 return true;
4089}
4090
4094 bool reserveCallFrame = hasReservedCallFrame(MF);
4095 unsigned Opcode = I->getOpcode();
4096 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
4097 DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
4098 uint64_t Amount = TII.getFrameSize(*I);
4099 uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
4100 I = MBB.erase(I);
4101 auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
4102
4103 // Try to avoid emitting dead SP adjustments if the block end is unreachable,
4104 // typically because the function is marked noreturn (abort, throw,
4105 // assert_fail, etc).
4106 if (isDestroy && blockEndIsUnreachable(MBB, I))
4107 return I;
4108
4109 if (!reserveCallFrame) {
4110 // If the stack pointer can be changed after prologue, turn the
4111 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
4112 // adjcallstackdown instruction into 'add ESP, <amt>'
4113
4114 // We need to keep the stack aligned properly. To do this, we round the
4115 // amount of space needed for the outgoing arguments up to the next
4116 // alignment boundary.
4117 Amount = alignTo(Amount, getStackAlign());
4118
4119 const Function &F = MF.getFunction();
4120 bool WindowsCFI = MF.usesWindowsUnwindInfo();
4121 bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
4122
4123 // If we have any exception handlers in this function, and we adjust
4124 // the SP before calls, we may need to indicate this to the unwinder
4125 // using GNU_ARGS_SIZE. Note that this may be necessary even when
4126 // Amount == 0, because the preceding function may have set a non-0
4127 // GNU_ARGS_SIZE.
4128 // TODO: We don't need to reset this between subsequent functions,
4129 // if it didn't change.
4130 bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
4131
4132 if (HasDwarfEHHandlers && !isDestroy &&
4134 BuildCFI(MBB, InsertPos, DL,
4135 MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
4136
4137 if (Amount == 0)
4138 return I;
4139
4140 // Factor out the amount that gets handled inside the sequence
4141 // (Pushes of argument for frame setup, callee pops for frame destroy)
4142 Amount -= InternalAmt;
4143
4144 // TODO: This is needed only if we require precise CFA.
4145 // If this is a callee-pop calling convention, emit a CFA adjust for
4146 // the amount the callee popped.
4147 if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
4148 BuildCFI(MBB, InsertPos, DL,
4149 MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
4150
4151 // Add Amount to SP to destroy a frame, or subtract to setup.
4152 int64_t StackAdjustment = isDestroy ? Amount : -Amount;
4153 int64_t CfaAdjustment = StackAdjustment;
4154
4155 if (StackAdjustment) {
4156 // Merge with any previous or following adjustment instruction. Note: the
4157 // instructions merged with here do not have CFI, so their stack
4158 // adjustments do not feed into CfaAdjustment
4159
4160 auto CalcCfaAdjust = [&CfaAdjustment](MachineBasicBlock::iterator PI,
4161 int64_t Offset) {
4162 CfaAdjustment += Offset;
4163 };
4164 auto CalcNewOffset = [&StackAdjustment](int64_t Offset) {
4165 return StackAdjustment + Offset;
4166 };
4167 StackAdjustment =
4168 mergeSPUpdates(MBB, InsertPos, CalcCfaAdjust, CalcNewOffset, true);
4169 StackAdjustment =
4170 mergeSPUpdates(MBB, InsertPos, CalcCfaAdjust, CalcNewOffset, false);
4171
4172 if (StackAdjustment) {
4173 if (!(F.hasMinSize() &&
4174 adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
4175 BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
4176 /*InEpilogue=*/false);
4177 }
4178 }
4179
4180 if (DwarfCFI && !hasFP(MF) && CfaAdjustment) {
4181 // If we don't have FP, but need to generate unwind information,
4182 // we need to set the correct CFA offset after the stack adjustment.
4183 // How much we adjust the CFA offset depends on whether we're emitting
4184 // CFI only for EH purposes or for debugging. EH only requires the CFA
4185 // offset to be correct at each call site, while for debugging we want
4186 // it to be more precise.
4187
4188 // TODO: When not using precise CFA, we also need to adjust for the
4189 // InternalAmt here.
4190 BuildCFI(
4191 MBB, InsertPos, DL,
4192 MCCFIInstruction::createAdjustCfaOffset(nullptr, -CfaAdjustment));
4193 }
4194
4195 return I;
4196 }
4197
4198 if (InternalAmt) {
4201 while (CI != B && !std::prev(CI)->isCall())
4202 --CI;
4203 BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
4204 }
4205
4206 return I;
4207}
4208
4210 assert(MBB.getParent() && "Block is not attached to a function!");
4211 const MachineFunction &MF = *MBB.getParent();
4212 if (!MBB.isLiveIn(X86::EFLAGS))
4213 return true;
4214
4215 // If stack probes have to loop inline or call, that will clobber EFLAGS.
4216 // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
4218 const X86TargetLowering &TLI = *STI.getTargetLowering();
4219 if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
4220 return false;
4221
4223 return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
4224}
4225
4227 assert(MBB.getParent() && "Block is not attached to a function!");
4228
4229 // Win64 has strict requirements in terms of epilogue and we are
4230 // not taking a chance at messing with them.
4231 // I.e., unless this block is already an exit block, we can't use
4232 // it as an epilogue.
4233 if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
4234 return false;
4235
4236 // Swift async context epilogue has a BTR instruction that clobbers parts of
4237 // EFLAGS.
4238 const MachineFunction &MF = *MBB.getParent();
4241
4242 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
4243 return true;
4244
4245 // If we cannot use LEA to adjust SP, we may need to use ADD, which
4246 // clobbers the EFLAGS. Check that we do not need to preserve it,
4247 // otherwise, conservatively assume this is not
4248 // safe to insert the epilogue here.
4250}
4251
4253 // If we may need to emit frameless compact unwind information, give
4254 // up as this is currently broken: PR25614.
4255 bool CompactUnwind =
4257 return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
4258 !CompactUnwind) &&
4259 // The lowering of segmented stack and HiPE only support entry
4260 // blocks as prologue blocks: PR26107. This limitation may be
4261 // lifted if we fix:
4262 // - adjustForSegmentedStacks
4263 // - adjustForHiPEPrologue
4265 !MF.shouldSplitStack();
4266}
4267
4270 const DebugLoc &DL, bool RestoreSP) const {
4271 assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
4272 assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
4273 assert(STI.is32Bit() && !Uses64BitFramePtr &&
4274 "restoring EBP/ESI on non-32-bit target");
4275
4276 MachineFunction &MF = *MBB.getParent();
4277 Register FramePtr = TRI->getFrameRegister(MF);
4278 Register BasePtr = TRI->getBaseRegister();
4279 WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
4281 MachineFrameInfo &MFI = MF.getFrameInfo();
4282
4283 // FIXME: Don't set FrameSetup flag in catchret case.
4284
4285 int FI = FuncInfo.EHRegNodeFrameIndex;
4286 int EHRegSize = MFI.getObjectSize(FI);
4287
4288 if (RestoreSP) {
4289 // MOV32rm -EHRegSize(%ebp), %esp
4290 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
4291 X86::EBP, -EHRegSize)
4293 }
4294
4295 Register UsedReg;
4296 int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
4297 int EndOffset = -EHRegOffset - EHRegSize;
4298 FuncInfo.EHRegNodeEndOffset = EndOffset;
4299
4300 if (UsedReg == FramePtr) {
4301 // ADD $offset, %ebp
4302 unsigned ADDri = getADDriOpcode(false);
4303 BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
4305 .addImm(EndOffset)
4307 ->getOperand(3)
4308 .setIsDead();
4309 assert(EndOffset >= 0 &&
4310 "end of registration object above normal EBP position!");
4311 } else if (UsedReg == BasePtr) {
4312 // LEA offset(%ebp), %esi
4313 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
4314 FramePtr, EndOffset)
4316 // MOV32rm SavedEBPOffset(%esi), %ebp
4317 assert(X86FI->getHasSEHFramePtrSave());
4318 int Offset =
4319 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
4320 .getFixed();
4321 assert(UsedReg == BasePtr);
4322 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
4323 UsedReg, Offset)
4325 } else {
4326 llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
4327 }
4328 return MBBI;
4329}
4330
4332 return TRI->getSlotSize();
4333}
4334
4339
4343 Register FrameRegister = RI->getFrameRegister(MF);
4344 if (getInitialCFARegister(MF) == FrameRegister &&
4346 DwarfFrameBase FrameBase;
4347 FrameBase.Kind = DwarfFrameBase::CFA;
4348 FrameBase.Location.Offset =
4350 return FrameBase;
4351 }
4352
4353 return DwarfFrameBase{DwarfFrameBase::Register, {FrameRegister}};
4354}
4355
4356namespace {
4357// Struct used by orderFrameObjects to help sort the stack objects.
4358struct X86FrameSortingObject {
4359 bool IsValid = false; // true if we care about this Object.
4360 unsigned ObjectIndex = 0; // Index of Object into MFI list.
4361 unsigned ObjectSize = 0; // Size of Object in bytes.
4362 Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
4363 unsigned ObjectNumUses = 0; // Object static number of uses.
4364};
4365
4366// The comparison function we use for std::sort to order our local
4367// stack symbols. The current algorithm is to use an estimated
4368// "density". This takes into consideration the size and number of
4369// uses each object has in order to roughly minimize code size.
4370// So, for example, an object of size 16B that is referenced 5 times
4371// will get higher priority than 4 4B objects referenced 1 time each.
4372// It's not perfect and we may be able to squeeze a few more bytes out of
4373// it (for example : 0(esp) requires fewer bytes, symbols allocated at the
4374// fringe end can have special consideration, given their size is less
4375// important, etc.), but the algorithmic complexity grows too much to be
4376// worth the extra gains we get. This gets us pretty close.
4377// The final order leaves us with objects with highest priority going
4378// at the end of our list.
4379struct X86FrameSortingComparator {
4380 inline bool operator()(const X86FrameSortingObject &A,
4381 const X86FrameSortingObject &B) const {
4382 uint64_t DensityAScaled, DensityBScaled;
4383
4384 // For consistency in our comparison, all invalid objects are placed
4385 // at the end. This also allows us to stop walking when we hit the
4386 // first invalid item after it's all sorted.
4387 if (!A.IsValid)
4388 return false;
4389 if (!B.IsValid)
4390 return true;
4391
4392 // The density is calculated by doing :
4393 // (double)DensityA = A.ObjectNumUses / A.ObjectSize
4394 // (double)DensityB = B.ObjectNumUses / B.ObjectSize
4395 // Since this approach may cause inconsistencies in
4396 // the floating point <, >, == comparisons, depending on the floating
4397 // point model with which the compiler was built, we're going
4398 // to scale both sides by multiplying with
4399 // A.ObjectSize * B.ObjectSize. This ends up factoring away
4400 // the division and, with it, the need for any floating point
4401 // arithmetic.
4402 DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
4403 static_cast<uint64_t>(B.ObjectSize);
4404 DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
4405 static_cast<uint64_t>(A.ObjectSize);
4406
4407 // If the two densities are equal, prioritize highest alignment
4408 // objects. This allows for similar alignment objects
4409 // to be packed together (given the same density).
4410 // There's room for improvement here, also, since we can pack
4411 // similar alignment (different density) objects next to each
4412 // other to save padding. This will also require further
4413 // complexity/iterations, and the overall gain isn't worth it,
4414 // in general. Something to keep in mind, though.
4415 if (DensityAScaled == DensityBScaled)
4416 return A.ObjectAlignment < B.ObjectAlignment;
4417
4418 return DensityAScaled < DensityBScaled;
4419 }
4420};
4421} // namespace
4422
4423// Order the symbols in the local stack.
4424// We want to place the local stack objects in some sort of sensible order.
4425// The heuristic we use is to try and pack them according to static number
4426// of uses and size of object in order to minimize code size.
4428 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
4429 const MachineFrameInfo &MFI = MF.getFrameInfo();
4430
4431 // Don't waste time if there's nothing to do.
4432 if (ObjectsToAllocate.empty())
4433 return;
4434
4435 // Create an array of all MFI objects. We won't need all of these
4436 // objects, but we're going to create a full array of them to make
4437 // it easier to index into when we're counting "uses" down below.
4438 // We want to be able to easily/cheaply access an object by simply
4439 // indexing into it, instead of having to search for it every time.
4440 std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
4441
4442 // Walk the objects we care about and mark them as such in our working
4443 // struct.
4444 for (auto &Obj : ObjectsToAllocate) {
4445 SortingObjects[Obj].IsValid = true;
4446 SortingObjects[Obj].ObjectIndex = Obj;
4447 SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
4448 // Set the size.
4449 int ObjectSize = MFI.getObjectSize(Obj);
4450 if (ObjectSize == 0)
4451 // Variable size. Just use 4.
4452 SortingObjects[Obj].ObjectSize = 4;
4453 else
4454 SortingObjects[Obj].ObjectSize = ObjectSize;
4455 }
4456
4457 // Count the number of uses for each object.
4458 for (auto &MBB : MF) {
4459 for (auto &MI : MBB) {
4460 if (MI.isDebugInstr())
4461 continue;
4462 for (const MachineOperand &MO : MI.operands()) {
4463 // Check to see if it's a local stack symbol.
4464 if (!MO.isFI())
4465 continue;
4466 int Index = MO.getIndex();
4467 // Check to see if it falls within our range, and is tagged
4468 // to require ordering.
4469 if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
4470 SortingObjects[Index].IsValid)
4471 SortingObjects[Index].ObjectNumUses++;
4472 }
4473 }
4474 }
4475
4476 // Sort the objects using X86FrameSortingAlgorithm (see its comment for
4477 // info).
4478 llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
4479
4480 // Now modify the original list to represent the final order that
4481 // we want. The order will depend on whether we're going to access them
4482 // from the stack pointer or the frame pointer. For SP, the list should
4483 // end up with the END containing objects that we want with smaller offsets.
4484 // For FP, it should be flipped.
4485 int i = 0;
4486 for (auto &Obj : SortingObjects) {
4487 // All invalid items are sorted at the end, so it's safe to stop.
4488 if (!Obj.IsValid)
4489 break;
4490 ObjectsToAllocate[i++] = Obj.ObjectIndex;
4491 }
4492
4493 // Flip it if we're accessing off of the FP.
4494 if (!TRI->hasStackRealignment(MF) && hasFP(MF))
4495 std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
4496}
4497
4498unsigned
4500 // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
4501 unsigned Offset = 16;
4502 // RBP is immediately pushed.
4503 Offset += SlotSize;
4504 // All callee-saved registers are then pushed.
4505 Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
4506 // Every funclet allocates enough stack space for the largest outgoing call.
4507 Offset += getWinEHFuncletFrameSize(MF);
4508 return Offset;
4509}
4510
4512 MachineFunction &MF, RegScavenger *RS) const {
4513 // Mark the function as not having WinCFI. We will set it back to true in
4514 // emitPrologue if it gets called and emits CFI.
4515 MF.setHasWinCFI(false);
4516
4517 MachineFrameInfo &MFI = MF.getFrameInfo();
4518 // If the frame is big enough that we might need to scavenge a register to
4519 // handle huge offsets, reserve a stack slot for that now.
4520 if (!isInt<32>(MFI.estimateStackSize(MF))) {
4521 int FI = MFI.CreateStackObject(SlotSize, Align(SlotSize), false);
4522 RS->addScavengingFrameIndex(FI);
4523 }
4524
4525 // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
4526 // aligned. The format doesn't support misaligned stack adjustments.
4527 if (MF.usesWindowsUnwindInfo())
4529
4530 // If this function isn't doing Win64-style C++ EH, we don't need to do
4531 // anything.
4532 if (STI.is64Bit() && MF.hasEHFunclets() &&
4535 adjustFrameForMsvcCxxEh(MF);
4536 }
4537}
4538
4539void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
4540 // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
4541 // relative to RSP after the prologue. Find the offset of the last fixed
4542 // object, so that we can allocate a slot immediately following it. If there
4543 // were no fixed objects, use offset -SlotSize, which is immediately after the
4544 // return address. Fixed objects have negative frame indices.
4545 MachineFrameInfo &MFI = MF.getFrameInfo();
4546 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
4547 int64_t MinFixedObjOffset = -SlotSize;
4548 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
4549 MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
4550
4551 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
4552 for (WinEHHandlerType &H : TBME.HandlerArray) {
4553 int FrameIndex = H.CatchObj.FrameIndex;
4554 if ((FrameIndex != INT_MAX) && MFI.getObjectOffset(FrameIndex) == 0) {
4555 // Ensure alignment.
4556 unsigned Align = MFI.getObjectAlign(FrameIndex).value();
4557 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
4558 MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
4559 MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
4560 }
4561 }
4562 }
4563
4564 // Ensure alignment.
4565 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
4566 int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
4567 int UnwindHelpFI =
4568 MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
4569 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
4570
4571 // Store -2 into UnwindHelp on function entry. We have to scan forwards past
4572 // other frame setup instructions.
4573 MachineBasicBlock &MBB = MF.front();
4574 auto MBBI = MBB.begin();
4575 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
4576 ++MBBI;
4577
4579 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
4580 UnwindHelpFI)
4581 .addImm(-2);
4582}
4583
4585 MachineFunction &MF, RegScavenger *RS) const {
4586 auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4587
4588 if (STI.is32Bit() && MF.hasEHFunclets())
4590 // We have emitted prolog and epilog. Don't need stack pointer saving
4591 // instruction any more.
4592 if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) {
4593 MI->eraseFromParent();
4594 X86FI->setStackPtrSaveMI(nullptr);
4595 }
4596}
4597
4599 MachineFunction &MF) const {
4600 // 32-bit functions have to restore stack pointers when control is transferred
4601 // back to the parent function. These blocks are identified as eh pads that
4602 // are not funclet entries.
4603 bool IsSEH = isAsynchronousEHPersonality(
4605 for (MachineBasicBlock &MBB : MF) {
4606 bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
4607 if (NeedsRestore)
4609 /*RestoreSP=*/IsSEH);
4610 }
4611}
4612
4613// Compute the alignment gap between current SP after spilling FP/BP and the
4614// next properly aligned stack offset.
4616 const TargetRegisterClass *RC,
4617 unsigned NumSpilledRegs) {
4619 unsigned AllocSize = TRI->getSpillSize(*RC) * NumSpilledRegs;
4620 Align StackAlign = MF.getSubtarget().getFrameLowering()->getStackAlign();
4621 unsigned AlignedSize = alignTo(AllocSize, StackAlign);
4622 return AlignedSize - AllocSize;
4623}
4624
4625void X86FrameLowering::spillFPBPUsingSP(MachineFunction &MF,
4627 Register FP, Register BP,
4628 int SPAdjust) const {
4629 assert(FP.isValid() || BP.isValid());
4630
4631 MachineBasicBlock *MBB = BeforeMI->getParent();
4632 DebugLoc DL = BeforeMI->getDebugLoc();
4633
4634 // Spill FP.
4635 if (FP.isValid()) {
4636 BuildMI(*MBB, BeforeMI, DL,
4637 TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>())))
4638 .addReg(FP);
4639 }
4640
4641 // Spill BP.
4642 if (BP.isValid()) {
4643 BuildMI(*MBB, BeforeMI, DL,
4644 TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>())))
4645 .addReg(BP);
4646 }
4647
4648 // Make sure SP is aligned.
4649 if (SPAdjust)
4650 emitSPUpdate(*MBB, BeforeMI, DL, -SPAdjust, false);
4651
4652 // Emit unwinding information.
4653 if (FP.isValid() && needsDwarfCFI(MF)) {
4654 // Emit .cfi_remember_state to remember old frame.
4655 unsigned CFIIndex =
4657 BuildMI(*MBB, BeforeMI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
4658 .addCFIIndex(CFIIndex);
4659
4660 // Setup new CFA value with DW_CFA_def_cfa_expression:
4661 // DW_OP_breg7+offset, DW_OP_deref, DW_OP_consts 16, DW_OP_plus
4662 SmallString<64> CfaExpr;
4663 uint8_t buffer[16];
4664 int Offset = SPAdjust;
4665 if (BP.isValid())
4666 Offset += TRI->getSpillSize(*TRI->getMinimalPhysRegClass(BP));
4667 // If BeforeMI is a frame setup instruction, we need to adjust the position
4668 // and offset of the new cfi instruction.
4669 if (TII.isFrameSetup(*BeforeMI)) {
4670 Offset += alignTo(TII.getFrameSize(*BeforeMI), getStackAlign());
4671 BeforeMI = std::next(BeforeMI);
4672 }
4673 Register StackPtr = TRI->getStackRegister();
4674 if (STI.isTarget64BitILP32())
4676 unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackPtr, true);
4677 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfStackPtr));
4678 CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
4679 CfaExpr.push_back(dwarf::DW_OP_deref);
4680 CfaExpr.push_back(dwarf::DW_OP_consts);
4681 CfaExpr.append(buffer, buffer + encodeSLEB128(SlotSize * 2, buffer));
4682 CfaExpr.push_back((uint8_t)dwarf::DW_OP_plus);
4683
4684 SmallString<64> DefCfaExpr;
4685 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
4686 DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer));
4687 DefCfaExpr.append(CfaExpr.str());
4688 BuildCFI(*MBB, BeforeMI, DL,
4689 MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()),
4691 }
4692}
4693
4694void X86FrameLowering::restoreFPBPUsingSP(MachineFunction &MF,
4696 Register FP, Register BP,
4697 int SPAdjust) const {
4698 assert(FP.isValid() || BP.isValid());
4699
4700 // Adjust SP so it points to spilled FP or BP.
4701 MachineBasicBlock *MBB = AfterMI->getParent();
4702 MachineBasicBlock::iterator Pos = std::next(AfterMI);
4703 DebugLoc DL = AfterMI->getDebugLoc();
4704 if (SPAdjust)
4705 emitSPUpdate(*MBB, Pos, DL, SPAdjust, false);
4706
4707 // Restore BP.
4708 if (BP.isValid()) {
4709 BuildMI(*MBB, Pos, DL,
4710 TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())), BP);
4711 }
4712
4713 // Restore FP.
4714 if (FP.isValid()) {
4715 BuildMI(*MBB, Pos, DL,
4716 TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())), FP);
4717
4718 // Emit unwinding information.
4719 if (needsDwarfCFI(MF)) {
4720 // Restore original frame with .cfi_restore_state.
4721 unsigned CFIIndex =
4723 BuildMI(*MBB, Pos, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
4724 .addCFIIndex(CFIIndex);
4725 }
4726 }
4727}
4728
4729void X86FrameLowering::saveAndRestoreFPBPUsingSP(
4731 MachineBasicBlock::iterator AfterMI, bool SpillFP, bool SpillBP) const {
4732 assert(SpillFP || SpillBP);
4733
4734 Register FP, BP;
4735 const TargetRegisterClass *RC;
4736 unsigned NumRegs = 0;
4737
4738 if (SpillFP) {
4739 FP = TRI->getFrameRegister(MF);
4740 if (STI.isTarget64BitILP32())
4742 RC = TRI->getMinimalPhysRegClass(FP);
4743 ++NumRegs;
4744 }
4745 if (SpillBP) {
4746 BP = TRI->getBaseRegister();
4747 if (STI.isTarget64BitILP32())
4748 BP = Register(getX86SubSuperRegister(BP, 64));
4749 RC = TRI->getMinimalPhysRegClass(BP);
4750 ++NumRegs;
4751 }
4752 int SPAdjust = computeFPBPAlignmentGap(MF, RC, NumRegs);
4753
4754 spillFPBPUsingSP(MF, BeforeMI, FP, BP, SPAdjust);
4755 restoreFPBPUsingSP(MF, AfterMI, FP, BP, SPAdjust);
4756}
4757
4758bool X86FrameLowering::skipSpillFPBP(
4760 if (MI->getOpcode() == X86::LCMPXCHG16B_SAVE_RBX) {
4761 // The pseudo instruction LCMPXCHG16B_SAVE_RBX is generated in the form
4762 // SaveRbx = COPY RBX
4763 // SaveRbx = LCMPXCHG16B_SAVE_RBX ..., SaveRbx, implicit-def rbx
4764 // And later LCMPXCHG16B_SAVE_RBX is expanded to restore RBX from SaveRbx.
4765 // We should skip this instruction sequence.
4766 int FI;
4767 Register Reg;
4768 while (!(MI->getOpcode() == TargetOpcode::COPY &&
4769 MI->getOperand(1).getReg() == X86::RBX) &&
4770 !((Reg = TII.isStoreToStackSlot(*MI, FI)) && Reg == X86::RBX))
4771 ++MI;
4772 return true;
4773 }
4774 return false;
4775}
4776
4778 const TargetRegisterInfo *TRI, bool &AccessFP,
4779 bool &AccessBP) {
4780 AccessFP = AccessBP = false;
4781 if (FP) {
4782 if (MI.findRegisterUseOperandIdx(FP, TRI, false) != -1 ||
4783 MI.findRegisterDefOperandIdx(FP, TRI, false, true) != -1)
4784 AccessFP = true;
4785 }
4786 if (BP) {
4787 if (MI.findRegisterUseOperandIdx(BP, TRI, false) != -1 ||
4788 MI.findRegisterDefOperandIdx(BP, TRI, false, true) != -1)
4789 AccessBP = true;
4790 }
4791 return AccessFP || AccessBP;
4792}
4793
4794// Invoke instruction has been lowered to normal function call. We try to figure
4795// out if MI comes from Invoke.
4796// Do we have any better method?
4797static bool isInvoke(const MachineInstr &MI, bool InsideEHLabels) {
4798 if (!MI.isCall())
4799 return false;
4800 if (InsideEHLabels)
4801 return true;
4802
4803 const MachineBasicBlock *MBB = MI.getParent();
4804 if (!MBB->hasEHPadSuccessor())
4805 return false;
4806
4807 // Check if there is another call instruction from MI to the end of MBB.
4809 for (++MBBI; MBBI != ME; ++MBBI)
4810 if (MBBI->isCall())
4811 return false;
4812 return true;
4813}
4814
4815/// Given the live range of FP or BP (DefMI, KillMI), check if there is any
4816/// interfered stack access in the range, usually generated by register spill.
4817void X86FrameLowering::checkInterferedAccess(
4819 MachineBasicBlock::reverse_iterator KillMI, bool SpillFP,
4820 bool SpillBP) const {
4821 if (DefMI == KillMI)
4822 return;
4823 if (TRI->hasBasePointer(MF)) {
4824 if (!SpillBP)
4825 return;
4826 } else {
4827 if (!SpillFP)
4828 return;
4829 }
4830
4831 auto MI = KillMI;
4832 while (MI != DefMI) {
4833 if (any_of(MI->operands(),
4834 [](const MachineOperand &MO) { return MO.isFI(); }))
4835 MF.getContext().reportError(SMLoc(),
4836 "Interference usage of base pointer/frame "
4837 "pointer.");
4838 MI++;
4839 }
4840}
4841
4842/// If a function uses base pointer and the base pointer is clobbered by inline
4843/// asm, RA doesn't detect this case, and after the inline asm, the base pointer
4844/// contains garbage value.
4845/// For example if a 32b x86 function uses base pointer esi, and esi is
4846/// clobbered by following inline asm
4847/// asm("rep movsb" : "+D"(ptr), "+S"(x), "+c"(c)::"memory");
4848/// We need to save esi before the asm and restore it after the asm.
4849///
4850/// The problem can also occur to frame pointer if there is a function call, and
4851/// the callee uses a different calling convention and clobbers the fp.
4852///
4853/// Because normal frame objects (spill slots) are accessed through fp/bp
4854/// register, so we can't spill fp/bp to normal spill slots.
4855///
4856/// FIXME: There are 2 possible enhancements:
4857/// 1. In many cases there are different physical registers not clobbered by
4858/// inline asm, we can use one of them as base pointer. Or use a virtual
4859/// register as base pointer and let RA allocate a physical register to it.
4860/// 2. If there is no other instructions access stack with fp/bp from the
4861/// inline asm to the epilog, and no cfi requirement for a correct fp, we can
4862/// skip the save and restore operations.
4864 Register FP, BP;
4866 if (TFI.hasFP(MF))
4867 FP = TRI->getFrameRegister(MF);
4868 if (TRI->hasBasePointer(MF))
4869 BP = TRI->getBaseRegister();
4870
4871 // Currently only inline asm and function call can clobbers fp/bp. So we can
4872 // do some quick test and return early.
4873 if (!MF.hasInlineAsm()) {
4875 if (!X86FI->getFPClobberedByCall())
4876 FP = 0;
4877 if (!X86FI->getBPClobberedByCall())
4878 BP = 0;
4879 }
4880 if (!FP && !BP)
4881 return;
4882
4883 for (MachineBasicBlock &MBB : MF) {
4884 bool InsideEHLabels = false;
4885 auto MI = MBB.rbegin(), ME = MBB.rend();
4886 auto TermMI = MBB.getFirstTerminator();
4887 if (TermMI == MBB.begin())
4888 continue;
4889 MI = *(std::prev(TermMI));
4890
4891 while (MI != ME) {
4892 // Skip frame setup/destroy instructions.
4893 // Skip Invoke (call inside try block) instructions.
4894 // Skip instructions handled by target.
4895 if (MI->getFlag(MachineInstr::MIFlag::FrameSetup) ||
4897 isInvoke(*MI, InsideEHLabels) || skipSpillFPBP(MF, MI)) {
4898 ++MI;
4899 continue;
4900 }
4901
4902 if (MI->getOpcode() == TargetOpcode::EH_LABEL) {
4903 InsideEHLabels = !InsideEHLabels;
4904 ++MI;
4905 continue;
4906 }
4907
4908 bool AccessFP, AccessBP;
4909 // Check if fp or bp is used in MI.
4910 if (!isFPBPAccess(*MI, FP, BP, TRI, AccessFP, AccessBP)) {
4911 ++MI;
4912 continue;
4913 }
4914
4915 // Look for the range [DefMI, KillMI] in which fp or bp is defined and
4916 // used.
4917 bool FPLive = false, BPLive = false;
4918 bool SpillFP = false, SpillBP = false;
4919 auto DefMI = MI, KillMI = MI;
4920 do {
4921 SpillFP |= AccessFP;
4922 SpillBP |= AccessBP;
4923
4924 // Maintain FPLive and BPLive.
4925 if (FPLive && MI->findRegisterDefOperandIdx(FP, TRI, false, true) != -1)
4926 FPLive = false;
4927 if (FP && MI->findRegisterUseOperandIdx(FP, TRI, false) != -1)
4928 FPLive = true;
4929 if (BPLive && MI->findRegisterDefOperandIdx(BP, TRI, false, true) != -1)
4930 BPLive = false;
4931 if (BP && MI->findRegisterUseOperandIdx(BP, TRI, false) != -1)
4932 BPLive = true;
4933
4934 DefMI = MI++;
4935 } while ((MI != ME) &&
4936 (FPLive || BPLive ||
4937 isFPBPAccess(*MI, FP, BP, TRI, AccessFP, AccessBP)));
4938
4939 // Don't need to save/restore if FP is accessed through llvm.frameaddress.
4940 if (FPLive && !SpillBP)
4941 continue;
4942
4943 // If the bp is clobbered by a call, we should save and restore outside of
4944 // the frame setup instructions.
4945 if (KillMI->isCall() && DefMI != ME) {
4946 auto FrameSetup = std::next(DefMI);
4947 // Look for frame setup instruction toward the start of the BB.
4948 // If we reach another call instruction, it means no frame setup
4949 // instruction for the current call instruction.
4950 while (FrameSetup != ME && !TII.isFrameSetup(*FrameSetup) &&
4951 !FrameSetup->isCall())
4952 ++FrameSetup;
4953 // If a frame setup instruction is found, we need to find out the
4954 // corresponding frame destroy instruction.
4955 if (FrameSetup != ME && TII.isFrameSetup(*FrameSetup) &&
4956 (TII.getFrameSize(*FrameSetup) ||
4957 TII.getFrameAdjustment(*FrameSetup))) {
4958 while (!TII.isFrameInstr(*KillMI))
4959 --KillMI;
4960 DefMI = FrameSetup;
4961 MI = DefMI;
4962 ++MI;
4963 }
4964 }
4965
4966 checkInterferedAccess(MF, DefMI, KillMI, SpillFP, SpillBP);
4967
4968 // Call target function to spill and restore FP and BP registers.
4969 saveAndRestoreFPBPUsingSP(MF, &(*DefMI), &(*KillMI), SpillFP, SpillBP);
4970 }
4971 }
4972}
MachineInstrBuilder MachineInstrBuilder & DefMI
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static const uint64_t kSplitStackAvailable
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
unsigned Opc
static bool isTailCallOpcode(unsigned Opc)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static bool is64Bit(const char *name)
static unsigned calculateSetFPREG(uint64_t SPAdjust)
static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary)
GetScratchRegister - Get a temp register for performing work in the segmented stack and the Erlang/Hi...
static unsigned getADDriOpcode(bool IsLP64)
static unsigned getPUSH2Opcode(const X86Subtarget &ST)
static uint64_t getUnusedLocalAreaPadding(const MachineFrameInfo &MFI)
Returns the number of bytes between the end of the fixed and callee-save area and the first local obj...
static unsigned getLEArOpcode(bool IsLP64)
static unsigned getSUBriOpcode(bool IsLP64)
static bool flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB)
Check if the flags need to be preserved before the terminators.
static bool isFPBPAccess(const MachineInstr &MI, Register FP, Register BP, const TargetRegisterInfo *TRI, bool &AccessFP, bool &AccessBP)
static const TargetRegisterClass * getCalleeSavedSpillRC(MCRegister Reg, const X86Subtarget &STI, const TargetRegisterInfo &TRI)
static bool isOpcodeRep(unsigned Opcode)
Return true if an opcode is part of the REP group of instructions.
static unsigned getANDriOpcode(bool IsLP64, int64_t Imm)
static bool isEAXLiveIn(MachineBasicBlock &MBB)
static int computeFPBPAlignmentGap(MachineFunction &MF, const TargetRegisterClass *RC, unsigned NumSpilledRegs)
static unsigned getADDrrOpcode(bool IsLP64)
static bool HasNestArgument(const MachineFunction *MF)
static unsigned getPOPOpcode(const X86Subtarget &ST)
static bool isInvoke(const MachineInstr &MI, bool InsideEHLabels)
static unsigned getPOP2Opcode(const X86Subtarget &ST)
static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD, const StringRef LiteralName)
Lookup an ERTS parameter in the !hipe.literals named metadata node.
static bool blockEndIsUnreachable(const MachineBasicBlock &MBB, MachineBasicBlock::const_iterator MBBI)
static unsigned getSUBrrOpcode(bool IsLP64)
static unsigned getPUSHOpcode(const X86Subtarget &ST)
constexpr uint64_t MaxSPChunk
static const unsigned FramePtr
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
reverse_iterator rend() const
Definition ArrayRef.h:133
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
reverse_iterator rbegin() const
Definition ArrayRef.h:132
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:325
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
A debug info location.
Definition DebugLoc.h:126
unsigned size() const
Definition DenseMap.h:717
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Constant * getPersonalityFn() const
Get the personality function associated with this function.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
size_t arg_size() const
Definition Function.h:895
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition Function.h:667
const Argument * const_arg_iterator
Definition Function.h:74
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Module * getParent()
Get the module that this global value is contained inside of...
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:637
static MCCFIInstruction createGnuArgsSize(MCSymbol *L, int64_t Size, SMLoc Loc={})
A special wrapper for .cfi_escape that indicates GNU_ARGS_SIZE.
Definition MCDwarf.h:767
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition MCDwarf.h:727
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:630
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:672
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:747
OpType getOperation() const
Definition MCDwarf.h:835
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:645
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:758
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition MCDwarf.h:653
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:752
const MCObjectFileInfo * getObjectFileInfo() const
Definition MCContext.h:413
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:411
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
MCSection * getCompactUnwindSection() const
MCRegAliasIterator enumerates all registers aliasing Reg.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
Metadata node.
Definition Metadata.h:1087
A single uniqued string.
Definition Metadata.h:734
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
MachineInstrBundleIterator< const MachineInstr > const_iterator
iterator_range< livein_iterator > liveins() const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Live
Register is known to be (at least partially) live.
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool needsSplitStackProlog() const
Return true if this function requires a split stack prolog, even if it uses no stack space.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
LLVM_ABI void ensureMaxAlignment(Align Alignment)
Make sure the function's frame is at least Align bytes aligned.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool hasOpaqueSPAdjustment() const
Returns true if the function contains opaque dynamic stack adjustments.
void setCVBytesOfCalleeSavedRegisters(unsigned S)
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasCopyImplyingStackAdjustment() const
Returns true if the function contains operations which will lower down to instructions which manipula...
bool hasStackObjects() const
Return true if there are any stack objects in this function.
LLVM_ABI int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_front(MachineBasicBlock *MBB)
const char * createExternalSymbolName(StringRef Name)
Allocate a string and populate it with the given external symbol name.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
bool needsWinCFI() const
True if this function uses SEH unwind opcodes and needs an unwind table entry.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool usesWindowsUnwindInfo() const
True if this function describes its unwind information with Windows SEH unwind opcodes (....
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
BasicBlockListType::iterator iterator
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
unsigned getNumOperands() const
Retuns the total number of operands.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI bool isLiveIn(Register Reg) const
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:320
WinX64EHUnwindMode getWinX64EHUnwindMode() const
Get how unwind information should be generated for x64 Windows.
Definition Module.cpp:1052
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition Module.cpp:636
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
A tuple of MDNodes.
Definition Metadata.h:1806
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
virtual bool hasInlineStackProbe(const MachineFunction &MF) const
const Triple & getTargetTriple() const
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
SwiftAsyncFramePointerMode SwiftAsyncFramePointer
Control when and how the Swift async frame pointer bit should be set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
bool isUEFI() const
Tests whether the OS is UEFI.
Definition Triple.h:777
bool isOSWindows() const
Tests whether the OS is Windows.
Definition Triple.h:780
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:472
Value * getValue() const
Definition Metadata.h:511
bool has128ByteRedZone(const MachineFunction &MF) const
Return true if the function has a redzone (accessible bytes past the frame of the top of stack functi...
void spillFPBP(MachineFunction &MF) const override
If a function uses base pointer and the base pointer is clobbered by inline asm, RA doesn't detect th...
bool canSimplifyCallFramePseudos(const MachineFunction &MF) const override
canSimplifyCallFramePseudos - If there is a reserved call frame, the call frame pseudos can be simpli...
bool needsFrameIndexResolution(const MachineFunction &MF) const override
X86FrameLowering(const X86Subtarget &STI, MaybeAlign StackAlignOverride)
const X86RegisterInfo * TRI
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool hasFPImpl(const MachineFunction &MF) const override
hasFPImpl - Return true if the specified function should have a dedicated frame pointer register.
MachineBasicBlock::iterator restoreWin32EHStackPointers(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool RestoreSP=false) const
Sets up EBP and optionally ESI based on the incoming EBP value.
int getInitialCFAOffset(const MachineFunction &MF) const override
Return initial CFA offset value i.e.
bool canUseAsPrologue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a prologue for the target.
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
void emitStackProbe(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog, std::optional< MachineFunction::DebugInstrOperandPair > InstrNum=std::nullopt) const
Emit target stack probe code.
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool IsPrologue) const
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int64_t mergeSPAdd(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, int64_t AddOffset, bool doMergeWithPrevious) const
Equivalent to: mergeSPUpdates(MBB, MBBI, [AddOffset](int64_t Offset) { return AddOffset + Offset; }...
StackOffset getFrameIndexReferenceSP(const MachineFunction &MF, int FI, Register &SPReg, int Adjustment) const
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologMBB) const override
Replace a StackProbe inline-stub with the actual probe code inline.
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
const X86InstrInfo & TII
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &DL, int64_t NumBytes, bool InEpilogue) const
Emit a series of instructions to increment / decrement the stack pointer by a constant value.
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
bool Is64Bit
Is64Bit implies that x86_64 instructions are available.
Register getInitialCFARegister(const MachineFunction &MF) const override
Return initial CFA register value i.e.
bool Uses64BitFramePtr
True if the 64-bit frame or stack pointer should be used.
unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const override
void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const override
Adjust the prologue to have the function use segmented stacks.
DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const override
Return the frame base information to be encoded in the DWARF subprogram debug info.
void emitCalleeSavedFrameMovesFullCFA(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const override
Emits Dwarf Info specifying offsets of callee saved registers and frame pointer.
int getWin64EHFrameIndexRef(const MachineFunction &MF, int FI, Register &SPReg) const
bool canUseLEAForSPInEpilogue(const MachineFunction &MF) const
Check that LEA can be used on SP in an epilogue sequence for MF.
bool stackProbeFunctionModifiesSP() const override
Does the stack probe function call return with a modified stack pointer?
void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &ObjectsToAllocate) const override
Order the symbols in the local stack.
void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag Flag=MachineInstr::NoFlags) const
Wraps up getting a CFI index and building a MachineInstr for it.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
StackOffset getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, Register &FrameReg, bool IgnoreSPUpdates) const override
Same as getFrameIndexReference, except that the stack pointer (as opposed to the frame pointer) will ...
void restoreWinEHStackPointersInParent(MachineFunction &MF) const
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
void adjustForHiPEPrologue(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const override
Erlang programs may need a special prologue to handle the stack size they might need at runtime.
const X86Subtarget & STI
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
bool isCandidateForPush2Pop2(Register Reg) const
ACEProgModelEnum getACEProgModel() const
void setRestoreBasePointer(const MachineFunction *MF)
DenseMap< int, unsigned > & getWinEHXMMSlotInfo()
MachineInstr * getStackPtrSaveMI() const
AMXProgModelEnum getAMXProgModel() const
void setStackPtrSaveMI(MachineInstr *MI)
void setCalleeSavedFrameSize(unsigned bytes)
const X86TargetLowering * getTargetLowering() const override
bool isTargetWindowsCoreCLR() const
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint16_t StackAdjustment(const RuntimeFunction &RF)
StackAdjustment - calculated stack adjustment in words.
Definition ARMWinEH.h:200
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ HiPE
Used by the High-Performance Erlang Compiler (HiPE).
Definition CallingConv.h:53
@ X86_INTR
x86 hardware interrupt context.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
constexpr MCPhysReg SP
@ MO_GOTPCREL
MO_GOTPCREL - On a symbol operand this indicates that the immediate is offset to the GOT entry for th...
unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm)
Return a MOVri opcode for materializing Imm into a 32- or 64-bit GPR.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
MCRegister getX86SubSuperRegister(MCRegister Reg, unsigned Size, bool High=false)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr RegState getDeadRegState(bool B)
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
static bool isFuncletReturnInstr(const MachineInstr &MI)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
@ DeploymentBased
Determine whether to set the bit statically or dynamically based on the deployment target.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
bool requireWinX64UnwindV3(const MachineFunction &MF)
Returns true when MF must use Windows x64 Unwind V3: the module is in V3 mode, or the function needs ...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition LEB128.h:24
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
constexpr RegState getUndefRegState(bool B)
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
static const MachineInstrBuilder & addRegOffset(const MachineInstrBuilder &MIB, Register Reg, int Offset)
addRegOffset - This function is used to add a memory reference of the form [Reg + Offset],...
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Pair of physical register and lane mask.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
union llvm::TargetFrameLowering::DwarfFrameBase::@004076321055032247336074224075335064105264310375 Location
enum llvm::TargetFrameLowering::DwarfFrameBase::FrameBaseKind Kind
SmallVector< WinEHTryBlockMapEntry, 4 > TryBlockMap
SmallVector< WinEHHandlerType, 1 > HandlerArray