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, false, 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, false, 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),
415 StackPtr, false, Offset);
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 }
554 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
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();
572 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
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 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
807 const bool HasFP = hasFP(MF);
808 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
809 const X86TargetLowering &TLI = *STI.getTargetLowering();
810 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
811 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
812
813 uint64_t CurrentOffset = 0;
814
815 assert(AlignOffset < StackProbeSize);
816
817 // If the offset is so small it fits within a page, there's nothing to do.
818 if (StackProbeSize < Offset + AlignOffset) {
819
820 uint64_t StackAdjustment = StackProbeSize - AlignOffset;
821 BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
822 .setMIFlag(MachineInstr::FrameSetup);
823 if (!HasFP && NeedsDwarfCFI) {
824 BuildCFI(
825 MBB, MBBI, DL,
826 MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
827 }
828
829 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
831 StackPtr, false, 0)
832 .addImm(0)
834 NumFrameExtraProbe++;
835 CurrentOffset = StackProbeSize - AlignOffset;
836 }
837
838 // For the next N - 1 pages, just probe. I tried to take advantage of
839 // natural probes but it implies much more logic and there was very few
840 // interesting natural probes to interleave.
841 while (CurrentOffset + StackProbeSize < Offset) {
842 BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
843 .setMIFlag(MachineInstr::FrameSetup);
844
845 if (!HasFP && NeedsDwarfCFI) {
846 BuildCFI(
847 MBB, MBBI, DL,
848 MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
849 }
850 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
852 StackPtr, false, 0)
853 .addImm(0)
855 NumFrameExtraProbe++;
856 CurrentOffset += StackProbeSize;
857 }
858
859 // No need to probe the tail, it is smaller than a Page.
860 uint64_t ChunkSize = Offset - CurrentOffset;
861 if (ChunkSize == SlotSize) {
862 // Use push for slot sized adjustments as a size optimization,
863 // like emitSPUpdate does when not probing.
864 unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
865 unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
866 BuildMI(MBB, MBBI, DL, TII.get(Opc))
869 } else {
870 BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
871 .setMIFlag(MachineInstr::FrameSetup);
872 }
873 // No need to adjust Dwarf CFA offset here, the last position of the stack has
874 // been defined
875}
876
877void X86FrameLowering::emitStackProbeInlineGenericLoop(
880 uint64_t AlignOffset) const {
881 assert(Offset && "null offset");
882
883 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
885 "Inline stack probe loop will clobber live EFLAGS.");
886
887 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
888 const bool HasFP = hasFP(MF);
889 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
890 const X86TargetLowering &TLI = *STI.getTargetLowering();
891 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
892 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
893
894 if (AlignOffset) {
895 if (AlignOffset < StackProbeSize) {
896 // Perform a first smaller allocation followed by a probe.
897 BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
898 .setMIFlag(MachineInstr::FrameSetup);
899
900 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
902 StackPtr, false, 0)
903 .addImm(0)
905 NumFrameExtraProbe++;
906 Offset -= AlignOffset;
907 }
908 }
909
910 // Synthesize a loop
911 NumFrameLoopProbe++;
912 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
913
914 MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
915 MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
916
918 MF.insert(MBBIter, testMBB);
919 MF.insert(MBBIter, tailMBB);
920
921 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
922 : Is64Bit ? X86::R11D
923 : X86::EAX;
924
925 // save loop bound
926 {
927 const uint64_t BoundOffset = alignDown(Offset, StackProbeSize);
928
929 // Can we calculate the loop bound using SUB with a 32-bit immediate?
930 // Note that the immediate gets sign-extended when used with a 64-bit
931 // register, so in that case we only have 31 bits to work with.
932 bool canUseSub =
933 Uses64BitFramePtr ? isUInt<31>(BoundOffset) : isUInt<32>(BoundOffset);
934
935 if (canUseSub) {
936 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
937
938 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
941 BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
942 .addReg(FinalStackProbed)
943 .addImm(BoundOffset)
945 } else if (Uses64BitFramePtr) {
946 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), FinalStackProbed)
947 .addImm(-BoundOffset)
949 BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), FinalStackProbed)
950 .addReg(FinalStackProbed)
953 } else {
954 llvm_unreachable("Offset too large for 32-bit stack pointer");
955 }
956
957 // while in the loop, use loop-invariant reg for CFI,
958 // instead of the stack pointer, which changes during the loop
959 if (!HasFP && NeedsDwarfCFI) {
960 // x32 uses the same DWARF register numbers as x86-64,
961 // so there isn't a register number for r11d, we must use r11 instead
962 const Register DwarfFinalStackProbed =
963 STI.isTarget64BitILP32()
964 ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
965 : FinalStackProbed;
966
969 nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
971 MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
972 }
973 }
974
975 // allocate a page
976 BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
977 /*InEpilogue=*/false)
978 .setMIFlag(MachineInstr::FrameSetup);
979
980 // touch the page
981 addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
983 StackPtr, false, 0)
984 .addImm(0)
986
987 // cmp with stack pointer bound
988 BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
990 .addReg(FinalStackProbed)
992
993 // jump
994 BuildMI(testMBB, DL, TII.get(X86::JCC_1))
995 .addMBB(testMBB)
998 testMBB->addSuccessor(testMBB);
999 testMBB->addSuccessor(tailMBB);
1000
1001 // BB management
1002 tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
1004 MBB.addSuccessor(testMBB);
1005
1006 // handle tail
1007 const uint64_t TailOffset = Offset % StackProbeSize;
1008 MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
1009 if (TailOffset) {
1010 BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
1011 /*InEpilogue=*/false)
1012 .setMIFlag(MachineInstr::FrameSetup);
1013 }
1014
1015 // after the loop, switch back to stack pointer for CFI
1016 if (!HasFP && NeedsDwarfCFI) {
1017 // x32 uses the same DWARF register numbers as x86-64,
1018 // so there isn't a register number for esp, we must use rsp instead
1019 const Register DwarfStackPtr =
1020 STI.isTarget64BitILP32()
1022 : Register(StackPtr);
1023
1024 BuildCFI(*tailMBB, TailMBBIter, DL,
1026 nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
1027 }
1028
1029 // Update Live In information
1030 fullyRecomputeLiveIns({tailMBB, testMBB});
1031}
1032
1033void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
1035 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
1036 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1037 assert(STI.is64Bit() && "different expansion needed for 32 bit");
1038 assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
1039 const TargetInstrInfo &TII = *STI.getInstrInfo();
1040 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
1041
1042 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1044 "Inline stack probe loop will clobber live EFLAGS.");
1045
1046 // RAX contains the number of bytes of desired stack adjustment.
1047 // The handling here assumes this value has already been updated so as to
1048 // maintain stack alignment.
1049 //
1050 // We need to exit with RSP modified by this amount and execute suitable
1051 // page touches to notify the OS that we're growing the stack responsibly.
1052 // All stack probing must be done without modifying RSP.
1053 //
1054 // MBB:
1055 // SizeReg = RAX;
1056 // ZeroReg = 0
1057 // CopyReg = RSP
1058 // Flags, TestReg = CopyReg - SizeReg
1059 // FinalReg = !Flags.Ovf ? TestReg : ZeroReg
1060 // LimitReg = gs magic thread env access
1061 // if FinalReg >= LimitReg goto ContinueMBB
1062 // RoundBB:
1063 // RoundReg = page address of FinalReg
1064 // LoopMBB:
1065 // LoopReg = PHI(LimitReg,ProbeReg)
1066 // ProbeReg = LoopReg - PageSize
1067 // [ProbeReg] = 0
1068 // if (ProbeReg > RoundReg) goto LoopMBB
1069 // ContinueMBB:
1070 // RSP = RSP - RAX
1071 // [rest of original MBB]
1072
1073 // Set up the new basic blocks
1074 MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1075 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1076 MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1077
1078 MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
1079 MF.insert(MBBIter, RoundMBB);
1080 MF.insert(MBBIter, LoopMBB);
1081 MF.insert(MBBIter, ContinueMBB);
1082
1083 // Split MBB and move the tail portion down to ContinueMBB.
1084 MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
1085 ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
1086 ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
1087
1088 // Some useful constants
1089 const int64_t ThreadEnvironmentStackLimit = 0x10;
1090 const int64_t PageSize = 0x1000;
1091 const int64_t PageMask = ~(PageSize - 1);
1092
1093 // Registers we need. For the normal case we use virtual
1094 // registers. For the prolog expansion we use RAX, RCX and RDX.
1095 MachineRegisterInfo &MRI = MF.getRegInfo();
1096 const TargetRegisterClass *RegClass = &X86::GR64RegClass;
1097 const Register
1098 SizeReg = InProlog ? X86::RAX : MRI.createVirtualRegister(RegClass),
1099 ZeroReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1100 CopyReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1101 TestReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1102 FinalReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1103 RoundedReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1104 LimitReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1105 JoinReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1106 ProbeReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass);
1107
1108 // SP-relative offsets where we can save RCX and RDX.
1109 int64_t RCXShadowSlot = 0;
1110 int64_t RDXShadowSlot = 0;
1111
1112 // If inlining in the prolog, save RCX and RDX.
1113 if (InProlog) {
1114 // Compute the offsets. We need to account for things already
1115 // pushed onto the stack at this point: return address, frame
1116 // pointer (if used), and callee saves.
1117 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1118 const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
1119 const bool HasFP = hasFP(MF);
1120
1121 // Check if we need to spill RCX and/or RDX.
1122 // Here we assume that no earlier prologue instruction changes RCX and/or
1123 // RDX, so checking the block live-ins is enough.
1124 const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
1125 const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
1126 int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
1127 // Assign the initial slot to both registers, then change RDX's slot if both
1128 // need to be spilled.
1129 if (IsRCXLiveIn)
1130 RCXShadowSlot = InitSlot;
1131 if (IsRDXLiveIn)
1132 RDXShadowSlot = InitSlot;
1133 if (IsRDXLiveIn && IsRCXLiveIn)
1134 RDXShadowSlot += 8;
1135 // Emit the saves if needed.
1136 if (IsRCXLiveIn)
1137 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
1138 RCXShadowSlot)
1139 .addReg(X86::RCX);
1140 if (IsRDXLiveIn)
1141 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
1142 RDXShadowSlot)
1143 .addReg(X86::RDX);
1144 } else {
1145 // Not in the prolog. Copy RAX to a virtual reg.
1146 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
1147 }
1148
1149 // Add code to MBB to check for overflow and set the new target stack pointer
1150 // to zero if so.
1151 BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
1152 .addReg(ZeroReg, RegState::Undef)
1153 .addReg(ZeroReg, RegState::Undef);
1154 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
1155 BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
1156 .addReg(CopyReg)
1157 .addReg(SizeReg);
1158 BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
1159 .addReg(TestReg)
1160 .addReg(ZeroReg)
1162
1163 // FinalReg now holds final stack pointer value, or zero if
1164 // allocation would overflow. Compare against the current stack
1165 // limit from the thread environment block. Note this limit is the
1166 // lowest touched page on the stack, not the point at which the OS
1167 // will cause an overflow exception, so this is just an optimization
1168 // to avoid unnecessarily touching pages that are below the current
1169 // SP but already committed to the stack by the OS.
1170 BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
1171 .addReg(0)
1172 .addImm(1)
1173 .addReg(0)
1174 .addImm(ThreadEnvironmentStackLimit)
1175 .addReg(X86::GS);
1176 BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
1177 // Jump if the desired stack pointer is at or above the stack limit.
1178 BuildMI(&MBB, DL, TII.get(X86::JCC_1))
1179 .addMBB(ContinueMBB)
1181
1182 // Add code to roundMBB to round the final stack pointer to a page boundary.
1183 if (InProlog)
1184 RoundMBB->addLiveIn(FinalReg);
1185 BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
1186 .addReg(FinalReg)
1187 .addImm(PageMask);
1188 BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
1189
1190 // LimitReg now holds the current stack limit, RoundedReg page-rounded
1191 // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
1192 // and probe until we reach RoundedReg.
1193 if (!InProlog) {
1194 BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
1195 .addReg(LimitReg)
1196 .addMBB(RoundMBB)
1197 .addReg(ProbeReg)
1198 .addMBB(LoopMBB);
1199 }
1200
1201 if (InProlog)
1202 LoopMBB->addLiveIn(JoinReg);
1203 addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
1204 false, -PageSize);
1205
1206 // Probe by storing a byte onto the stack.
1207 BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
1208 .addReg(ProbeReg)
1209 .addImm(1)
1210 .addReg(0)
1211 .addImm(0)
1212 .addReg(0)
1213 .addImm(0);
1214
1215 if (InProlog)
1216 LoopMBB->addLiveIn(RoundedReg);
1217 BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
1218 .addReg(RoundedReg)
1219 .addReg(ProbeReg);
1220 BuildMI(LoopMBB, DL, TII.get(X86::JCC_1))
1221 .addMBB(LoopMBB)
1223
1224 MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
1225
1226 // If in prolog, restore RDX and RCX.
1227 if (InProlog) {
1228 if (RCXShadowSlot) // It means we spilled RCX in the prologue.
1229 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
1230 TII.get(X86::MOV64rm), X86::RCX),
1231 X86::RSP, false, RCXShadowSlot);
1232 if (RDXShadowSlot) // It means we spilled RDX in the prologue.
1233 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
1234 TII.get(X86::MOV64rm), X86::RDX),
1235 X86::RSP, false, RDXShadowSlot);
1236 }
1237
1238 // Now that the probing is done, add code to continueMBB to update
1239 // the stack pointer for real.
1240 BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
1241 .addReg(X86::RSP)
1242 .addReg(SizeReg);
1243
1244 // Add the control flow edges we need.
1245 MBB.addSuccessor(ContinueMBB);
1246 MBB.addSuccessor(RoundMBB);
1247 RoundMBB->addSuccessor(LoopMBB);
1248 LoopMBB->addSuccessor(ContinueMBB);
1249 LoopMBB->addSuccessor(LoopMBB);
1250
1251 if (InProlog) {
1252 LivePhysRegs LiveRegs;
1253 computeAndAddLiveIns(LiveRegs, *ContinueMBB);
1254 }
1255
1256 // Mark all the instructions added to the prolog as frame setup.
1257 if (InProlog) {
1258 for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
1259 BeforeMBBI->setFlag(MachineInstr::FrameSetup);
1260 }
1261 for (MachineInstr &MI : *RoundMBB) {
1263 }
1264 for (MachineInstr &MI : *LoopMBB) {
1266 }
1267 for (MachineInstr &MI :
1268 llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1270 }
1271 }
1272}
1273
1274void X86FrameLowering::emitStackProbeCall(
1276 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1277 std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
1278 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
1279
1280 // FIXME: Add indirect thunk support and remove this.
1281 if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
1282 report_fatal_error("Emitting stack probe calls on 64-bit with the large "
1283 "code model and indirect thunks not yet implemented.");
1284
1285 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1287 "Stack probe calls will clobber live EFLAGS.");
1288
1289 unsigned CallOp;
1290 if (Is64Bit)
1291 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
1292 else
1293 CallOp = X86::CALLpcrel32;
1294
1295 StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
1296
1297 MachineInstrBuilder CI;
1298 MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
1299
1300 // All current stack probes take AX and SP as input, clobber flags, and
1301 // preserve all registers. x86_64 probes leave RSP unmodified.
1303 // For the large code model, we have to call through a register. Use R11,
1304 // as it is scratch in all supported calling conventions.
1305 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
1307 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
1308 } else {
1309 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
1311 }
1312
1313 unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
1314 unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
1320
1321 MachineInstr *ModInst = CI;
1322 if (STI.isTargetWin64() || !STI.isOSWindows()) {
1323 // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
1324 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
1325 // themselves. They also does not clobber %rax so we can reuse it when
1326 // adjusting %rsp.
1327 // All other platforms do not specify a particular ABI for the stack probe
1328 // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
1329 ModInst =
1331 .addReg(SP)
1332 .addReg(AX);
1333 }
1334
1335 // DebugInfo variable locations -- if there's an instruction number for the
1336 // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
1337 // modifies SP.
1338 if (InstrNum) {
1339 if (STI.isTargetWin64() || !STI.isOSWindows()) {
1340 // Label destination operand of the subtract.
1341 MF.makeDebugValueSubstitution(*InstrNum,
1342 {ModInst->getDebugInstrNum(), 0});
1343 } else {
1344 // Label the call. The operand number is the penultimate operand, zero
1345 // based.
1346 unsigned SPDefOperand = ModInst->getNumOperands() - 2;
1348 *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
1349 }
1350 }
1351
1352 if (InProlog) {
1353 // Apply the frame setup flag to all inserted instrs.
1354 for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
1355 ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
1356 }
1357}
1358
1359static unsigned calculateSetFPREG(uint64_t SPAdjust) {
1360 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
1361 // and might require smaller successive adjustments.
1362 const uint64_t Win64MaxSEHOffset = 128;
1363 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
1364 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
1365 return SEHFrameOffset & -16;
1366}
1367
1368// If we're forcing a stack realignment we can't rely on just the frame
1369// info, we need to know the ABI stack alignment as well in case we
1370// have a call out. Otherwise just make sure we have some alignment - we'll
1371// go with the minimum SlotSize.
1373X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
1374 const MachineFrameInfo &MFI = MF.getFrameInfo();
1375 Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
1376 Align StackAlign = getStackAlign();
1377 bool HasRealign = MF.getFunction().hasFnAttribute("stackrealign");
1378 if (HasRealign) {
1379 if (MFI.hasCalls())
1380 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
1381 else if (MaxAlign < SlotSize)
1382 MaxAlign = Align(SlotSize);
1383 }
1384
1386 if (HasRealign)
1387 MaxAlign = (MaxAlign > 16) ? MaxAlign : Align(16);
1388 else
1389 MaxAlign = Align(16);
1390 }
1391 return MaxAlign.value();
1392}
1393
1394void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
1396 const DebugLoc &DL, Register Reg,
1397 uint64_t MaxAlign) const {
1398 uint64_t Val = -MaxAlign;
1399 unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1400
1401 MachineFunction &MF = *MBB.getParent();
1402 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1403 const X86TargetLowering &TLI = *STI.getTargetLowering();
1404 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1405 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1406
1407 // We want to make sure that (in worst case) less than StackProbeSize bytes
1408 // are not probed after the AND. This assumption is used in
1409 // emitStackProbeInlineGeneric.
1410 if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1411 {
1412 NumFrameLoopProbe++;
1413 MachineBasicBlock *entryMBB =
1415 MachineBasicBlock *headMBB =
1417 MachineBasicBlock *bodyMBB =
1419 MachineBasicBlock *footMBB =
1421
1423 MF.insert(MBBIter, entryMBB);
1424 MF.insert(MBBIter, headMBB);
1425 MF.insert(MBBIter, bodyMBB);
1426 MF.insert(MBBIter, footMBB);
1427 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
1428 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
1429 : Is64Bit ? X86::R11D
1430 : X86::EAX;
1431
1432 // Setup entry block
1433 {
1434
1435 entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1436 BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1439 MachineInstr *MI =
1440 BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1441 .addReg(FinalStackProbed)
1442 .addImm(Val)
1444
1445 // The EFLAGS implicit def is dead.
1446 MI->getOperand(3).setIsDead();
1447
1448 BuildMI(entryMBB, DL,
1449 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1450 .addReg(FinalStackProbed)
1453 BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1454 .addMBB(&MBB)
1457 entryMBB->addSuccessor(headMBB);
1458 entryMBB->addSuccessor(&MBB);
1459 }
1460
1461 // Loop entry block
1462
1463 {
1464 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1465 BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1467 .addImm(StackProbeSize)
1469
1470 BuildMI(headMBB, DL,
1471 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1473 .addReg(FinalStackProbed)
1475
1476 // jump to the footer if StackPtr < FinalStackProbed
1477 BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1478 .addMBB(footMBB)
1481
1482 headMBB->addSuccessor(bodyMBB);
1483 headMBB->addSuccessor(footMBB);
1484 }
1485
1486 // setup loop body
1487 {
1488 addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1490 StackPtr, false, 0)
1491 .addImm(0)
1493
1494 const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1495 BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1497 .addImm(StackProbeSize)
1499
1500 // cmp with stack pointer bound
1501 BuildMI(bodyMBB, DL,
1502 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1503 .addReg(FinalStackProbed)
1506
1507 // jump back while FinalStackProbed < StackPtr
1508 BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1509 .addMBB(bodyMBB)
1512 bodyMBB->addSuccessor(bodyMBB);
1513 bodyMBB->addSuccessor(footMBB);
1514 }
1515
1516 // setup loop footer
1517 {
1518 BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1519 .addReg(FinalStackProbed)
1521 addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1523 StackPtr, false, 0)
1524 .addImm(0)
1526 footMBB->addSuccessor(&MBB);
1527 }
1528
1529 fullyRecomputeLiveIns({footMBB, bodyMBB, headMBB, &MBB});
1530 }
1531 } else {
1532 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
1533 .addReg(Reg)
1534 .addImm(Val)
1536
1537 // The EFLAGS implicit def is dead.
1538 MI->getOperand(3).setIsDead();
1539 }
1540}
1541
1543 // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
1544 // clobbered by any interrupt handler.
1545 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1546 "MF used frame lowering for wrong subtarget");
1547 const Function &Fn = MF.getFunction();
1548 const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
1549 return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
1550}
1551
1552bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1553 return !MF.usesWindowsUnwindInfo() && MF.needsFrameMoves();
1554}
1555
1556/// Return true if an opcode is part of the REP group of instructions
1557static bool isOpcodeRep(unsigned Opcode) {
1558 switch (Opcode) {
1559 case X86::REPNE_PREFIX:
1560 case X86::REP_MOVSB_32:
1561 case X86::REP_MOVSB_64:
1562 case X86::REP_MOVSD_32:
1563 case X86::REP_MOVSD_64:
1564 case X86::REP_MOVSQ_32:
1565 case X86::REP_MOVSQ_64:
1566 case X86::REP_MOVSW_32:
1567 case X86::REP_MOVSW_64:
1568 case X86::REP_PREFIX:
1569 case X86::REP_STOSB_32:
1570 case X86::REP_STOSB_64:
1571 case X86::REP_STOSD_32:
1572 case X86::REP_STOSD_64:
1573 case X86::REP_STOSQ_32:
1574 case X86::REP_STOSQ_64:
1575 case X86::REP_STOSW_32:
1576 case X86::REP_STOSW_64:
1577 return true;
1578 default:
1579 break;
1580 }
1581 return false;
1582}
1583
1584/// Returns the number of bytes between the end of the fixed and callee-save
1585/// area and the first local object, which PEI leaves as padding when it aligns
1586/// the local objects relative to the incoming stack pointer.
1588 int64_t FixedEnd = 0;
1589 int64_t LocalsTop = std::numeric_limits<int64_t>::max();
1590 for (int I : seq(MFI.getObjectIndexBegin(), MFI.getObjectIndexEnd())) {
1593 continue;
1594
1595 int64_t ObjOffset = MFI.getObjectOffset(I);
1596 int64_t ObjSize = MFI.getObjectSize(I);
1597 // Offsets are negative, measured from the incoming stack pointer.
1598 if (MFI.isFixedObjectIndex(I))
1599 FixedEnd = std::max(FixedEnd, -ObjOffset);
1600 else
1601 LocalsTop = std::min<int64_t>(LocalsTop, -ObjOffset - ObjSize);
1602 }
1603 if (LocalsTop == std::numeric_limits<int64_t>::max())
1604 return 0;
1605
1606 assert(LocalsTop >= FixedEnd && "Local object overlaps the fixed area");
1607 return LocalsTop - FixedEnd;
1608}
1609
1610/// emitPrologue - Push callee-saved registers onto the stack, which
1611/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
1612/// space for local variables. Also emit labels used by the exception handler to
1613/// generate the exception handling frames.
1614
1615/*
1616 Here's a gist of what gets emitted:
1617
1618 ; Establish frame pointer, if needed
1619 [if needs FP]
1620 push %rbp
1621 .cfi_def_cfa_offset 16
1622 .cfi_offset %rbp, -16
1623 .seh_pushreg %rpb
1624 mov %rsp, %rbp
1625 .cfi_def_cfa_register %rbp
1626
1627 ; Spill general-purpose registers
1628 [for all callee-saved GPRs]
1629 pushq %<reg>
1630 [if not needs FP]
1631 .cfi_def_cfa_offset (offset from RETADDR)
1632 .seh_pushreg %<reg>
1633
1634 ; If the required stack alignment > default stack alignment
1635 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
1636 ; of unknown size in the stack frame.
1637 [if stack needs re-alignment]
1638 and $MASK, %rsp
1639
1640 ; Allocate space for locals
1641 [if target is Windows and allocated space > 4096 bytes]
1642 ; Windows needs special care for allocations larger
1643 ; than one page.
1644 mov $NNN, %rax
1645 call ___chkstk_ms/___chkstk
1646 sub %rax, %rsp
1647 [else]
1648 sub $NNN, %rsp
1649
1650 [if needs FP]
1651 .seh_stackalloc (size of XMM spill slots)
1652 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
1653 [else]
1654 .seh_stackalloc NNN
1655
1656 ; Spill XMMs
1657 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
1658 ; they may get spilled on any platform, if the current function
1659 ; calls @llvm.eh.unwind.init
1660 [if needs FP]
1661 [for all callee-saved XMM registers]
1662 movaps %<xmm reg>, -MMM(%rbp)
1663 [for all callee-saved XMM registers]
1664 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
1665 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
1666 [else]
1667 [for all callee-saved XMM registers]
1668 movaps %<xmm reg>, KKK(%rsp)
1669 [for all callee-saved XMM registers]
1670 .seh_savexmm %<xmm reg>, KKK
1671
1672 .seh_endprologue
1673
1674 [if needs base pointer]
1675 mov %rsp, %rbx
1676 [if needs to restore base pointer]
1677 mov %rsp, -MMM(%rbp)
1678
1679 ; Emit CFI info
1680 [if needs FP]
1681 [for all callee-saved registers]
1682 .cfi_offset %<reg>, (offset from %rbp)
1683 [else]
1684 .cfi_def_cfa_offset (offset from RETADDR)
1685 [for all callee-saved registers]
1686 .cfi_offset %<reg>, (offset from %rsp)
1687
1688 Notes:
1689 - .seh directives are emitted only for Windows 64 ABI
1690 - .cv_fpo directives are emitted on win32 when emitting CodeView
1691 - .cfi directives are emitted for all other ABIs
1692 - for 32-bit code, substitute %e?? registers for %r??
1693*/
1694
1696 MachineBasicBlock &MBB) const {
1697 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1698 "MF used frame lowering for wrong subtarget");
1700 MachineFrameInfo &MFI = MF.getFrameInfo();
1701 const Function &Fn = MF.getFunction();
1703 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
1704 uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate.
1705 bool IsFunclet = MBB.isEHFuncletEntry();
1707 if (Fn.hasPersonalityFn())
1708 Personality = classifyEHPersonality(Fn.getPersonalityFn());
1709 bool FnHasClrFunclet =
1710 MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
1711 bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
1712 bool HasFP = hasFP(MF);
1713 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
1714 bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
1715 // FIXME: Emit FPO data for EH funclets.
1716 bool NeedsWinFPO = !IsFunclet && STI.isTargetWin32() &&
1718 bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1719 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1720 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
1721 Register FramePtr = TRI->getFrameRegister(MF);
1722 const Register MachineFramePtr =
1723 STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
1724 : FramePtr;
1725 Register BasePtr = TRI->getBaseRegister();
1726 bool HasWinCFI = false;
1727
1728 // Helpers to emit Windows x64 unwind SEH pseudos with the correct placement.
1729 // V1/V2: pseudo goes after the real instruction.
1730 // V3: pseudo goes before the real instruction.
1731 // Usage:
1732 // EmitSEHBefore([&]{ BuildMI(...SEH_PushReg...); });
1733 // BuildMI(... real instruction ...);
1734 // EmitSEHAfter([&]{ BuildMI(...SEH_PushReg...); });
1735 auto EmitSEHBefore = [&](auto EmitFn) {
1736 if (NeedsWinCFI && IsWin64UnwindV3) {
1737 HasWinCFI = true;
1738 EmitFn();
1739 }
1740 };
1741 auto EmitSEHAfter = [&](auto EmitFn) {
1742 if (NeedsWinCFI && !IsWin64UnwindV3) {
1743 HasWinCFI = true;
1744 EmitFn();
1745 }
1746 };
1747
1748 // Debug location must be unknown since the first debug location is used
1749 // to determine the end of the prologue.
1750 DebugLoc DL;
1751 Register ArgBaseReg;
1752
1753 // Emit extra prolog for argument stack slot reference.
1754 if (auto *MI = X86FI->getStackPtrSaveMI()) {
1755 // MI is lea instruction that created in X86ArgumentStackSlotPass.
1756 // Creat extra prolog for stack realignment.
1757 ArgBaseReg = MI->getOperand(0).getReg();
1758 // leal 4(%esp), %basereg
1759 // .cfi_def_cfa %basereg, 0
1760 // andl $-128, %esp
1761 // pushl -4(%basereg)
1762 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::LEA64r : X86::LEA32r),
1763 ArgBaseReg)
1765 .addImm(1)
1766 .addUse(X86::NoRegister)
1768 .addUse(X86::NoRegister)
1770 if (NeedsDwarfCFI) {
1771 // .cfi_def_cfa %basereg, 0
1772 unsigned DwarfStackPtr = TRI->getDwarfRegNum(ArgBaseReg, true);
1773 BuildCFI(MBB, MBBI, DL,
1774 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 0),
1776 }
1777 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1778 int64_t Offset = -(int64_t)SlotSize;
1779 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm))
1780 .addReg(ArgBaseReg)
1781 .addImm(1)
1782 .addReg(X86::NoRegister)
1783 .addImm(Offset)
1784 .addReg(X86::NoRegister)
1786 }
1787
1788 // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1789 // tail call.
1790 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1791 if (TailCallArgReserveSize && IsWin64Prologue)
1792 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
1793
1794 const bool EmitStackProbeCall =
1795 STI.getTargetLowering()->hasStackProbeSymbol(MF);
1796 unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
1797
1798 if (HasFP && X86FI->hasSwiftAsyncContext()) {
1801 if (STI.swiftAsyncContextIsDynamicallySet()) {
1802 // The special symbol below is absolute and has a *value* suitable to be
1803 // combined with the frame pointer directly.
1804 BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1805 .addUse(MachineFramePtr)
1806 .addUse(X86::RIP)
1807 .addImm(1)
1808 .addUse(X86::NoRegister)
1809 .addExternalSymbol("swift_async_extendedFramePointerFlags",
1811 .addUse(X86::NoRegister);
1812 break;
1813 }
1814 [[fallthrough]];
1815
1817 assert(
1818 !IsWin64Prologue &&
1819 "win64 prologue does not set the bit 60 in the saved frame pointer");
1820 BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1821 .addUse(MachineFramePtr)
1822 .addImm(60)
1824 break;
1825
1827 break;
1828 }
1829 }
1830
1831 // Re-align the stack on 64-bit if the x86-interrupt calling convention is
1832 // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
1833 // stack alignment.
1835 Fn.arg_size() == 2) {
1836 // Update the stack pointer by pushing a register. This is the instruction
1837 // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1838 // Hard-coding the update to a push avoids emitting a second
1839 // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1840 // probing isn't needed anyways for an 8-byte update.
1841 // Pushing a register leaves us in a similar situation to a regular
1842 // function call where we know that the address at (rsp-8) is writeable.
1843 // That way we avoid any off-by-ones with stack probing for additional
1844 // stack pointer updates later on.
1845 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1846 .addReg(X86::RAX, RegState::Undef)
1848 }
1849
1850 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
1851 // function, and use up to 128 bytes of stack space, don't have a frame
1852 // pointer, calls, or dynamic alloca then we do not need to adjust the
1853 // stack pointer (we fit in the Red Zone). We also check that we don't
1854 // push and pop from the stack.
1855 if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
1856 !MFI.hasVarSizedObjects() && // No dynamic alloca.
1857 !MFI.adjustsStack() && // No calls.
1858 !EmitStackProbeCall && // No stack probes.
1859 !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
1860 !MF.shouldSplitStack()) { // Regular stack
1861 uint64_t MinSize =
1863 if (HasFP)
1864 MinSize += SlotSize;
1865 X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
1866 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
1867 MFI.setStackSize(StackSize);
1868 }
1869
1870 // Insert stack pointer adjustment for later moving of return addr. Only
1871 // applies to tail call optimized functions where the callee argument stack
1872 // size is bigger than the callers.
1873 if (TailCallArgReserveSize != 0) {
1874 BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
1875 /*InEpilogue=*/false)
1876 .setMIFlag(MachineInstr::FrameSetup);
1877 }
1878
1879 // Mapping for machine moves:
1880 //
1881 // DST: VirtualFP AND
1882 // SRC: VirtualFP => DW_CFA_def_cfa_offset
1883 // ELSE => DW_CFA_def_cfa
1884 //
1885 // SRC: VirtualFP AND
1886 // DST: Register => DW_CFA_def_cfa_register
1887 //
1888 // ELSE
1889 // OFFSET < 0 => DW_CFA_offset_extended_sf
1890 // REG < 64 => DW_CFA_offset + Reg
1891 // ELSE => DW_CFA_offset_extended
1892
1893 uint64_t NumBytes = 0;
1894 int stackGrowth = -SlotSize;
1895
1896 // Find the funclet establisher parameter
1897 MCRegister Establisher;
1898 if (IsClrFunclet)
1899 Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1900 else if (IsFunclet)
1901 Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1902
1903 if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1904 // Immediately spill establisher into the home slot.
1905 // The runtime cares about this.
1906 // MOV64mr %rdx, 16(%rsp)
1907 unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1908 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
1909 .addReg(Establisher)
1911 MBB.addLiveIn(Establisher);
1912 }
1913
1914 if (HasFP) {
1915 assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
1916
1917 // Calculate required stack adjustment.
1918 uint64_t FrameSize = StackSize - SlotSize;
1919 NumBytes =
1920 FrameSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
1921
1922 // Callee-saved registers are pushed on stack before the stack is realigned,
1923 // and the realignment itself already provides the local objects' alignment,
1924 // so leave out the padding PEI put in front of them for it.
1925 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue) {
1926 uint64_t Padding = getUnusedLocalAreaPadding(MFI);
1927 assert(Padding <= NumBytes && "Padding exceeds the local area");
1928 NumBytes = alignTo(NumBytes - Padding, MaxAlign);
1929 }
1930
1931 // Save EBP/RBP into the appropriate stack slot.
1932 auto EmitSEHPushFramePtr = [&]() {
1933 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1936 };
1937 EmitSEHBefore(EmitSEHPushFramePtr);
1938 BuildMI(MBB, MBBI, DL,
1940 .addReg(MachineFramePtr, RegState::Kill)
1942 EmitSEHAfter(EmitSEHPushFramePtr);
1943
1944 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1945 // Mark the place where EBP/RBP was saved.
1946 // Define the current CFA rule to use the provided offset.
1947 assert(StackSize);
1948 BuildCFI(MBB, MBBI, DL,
1950 nullptr, -2 * stackGrowth + (int)TailCallArgReserveSize),
1952
1953 // Change the rule for the FramePtr to be an "offset" rule.
1954 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1955 BuildCFI(MBB, MBBI, DL,
1956 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
1957 2 * stackGrowth -
1958 (int)TailCallArgReserveSize),
1960 }
1961
1962 if (!IsFunclet) {
1963 if (X86FI->hasSwiftAsyncContext()) {
1964 assert(!IsWin64Prologue &&
1965 "win64 prologue does not store async context right below rbp");
1966 const auto &Attrs = MF.getFunction().getAttributes();
1967
1968 // Before we update the live frame pointer we have to ensure there's a
1969 // valid (or null) asynchronous context in its slot just before FP in
1970 // the frame record, so store it now.
1971 auto EmitSEHPushR14 = [&]() {
1972 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1973 .addImm(X86::R14)
1975 };
1976 EmitSEHBefore(EmitSEHPushR14);
1977 if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
1978 // We have an initial context in r14, store it just before the frame
1979 // pointer.
1980 MBB.addLiveIn(X86::R14);
1981 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1982 .addReg(X86::R14)
1984 } else {
1985 // No initial context, store null so that there's no pointer that
1986 // could be misused.
1987 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i32))
1988 .addImm(0)
1990 }
1991
1992 // Update CFA offset for the async-context push.
1993 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1994 BuildCFI(
1995 MBB, MBBI, DL,
1996 MCCFIInstruction::createAdjustCfaOffset(nullptr, -stackGrowth),
1998 }
1999
2000 EmitSEHAfter(EmitSEHPushR14);
2001
2002 BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
2003 .addUse(X86::RSP)
2004 .addImm(1)
2005 .addUse(X86::NoRegister)
2006 .addImm(8)
2007 .addUse(X86::NoRegister)
2009
2010 // Switch to an FP-relative CFA before adjusting RSP below.
2011 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
2012 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2013 BuildCFI(MBB, MBBI, DL,
2014 MCCFIInstruction::cfiDefCfa(nullptr, DwarfFramePtr,
2015 -2 * stackGrowth +
2016 (int)TailCallArgReserveSize),
2018 }
2019
2020 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri32), X86::RSP)
2021 .addUse(X86::RSP)
2022 .addImm(8)
2024 }
2025
2026 if (!IsWin64Prologue && !IsFunclet) {
2027 // Update EBP with the new base value.
2028 if (!X86FI->hasSwiftAsyncContext())
2029 BuildMI(MBB, MBBI, DL,
2030 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
2031 FramePtr)
2034
2035 if (NeedsDwarfCFI) {
2036 if (ArgBaseReg.isValid()) {
2037 SmallString<64> CfaExpr;
2038 CfaExpr.push_back(dwarf::DW_CFA_expression);
2039 uint8_t buffer[16];
2040 unsigned DwarfReg = TRI->getDwarfRegNum(MachineFramePtr, true);
2041 CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
2042 CfaExpr.push_back(2);
2043 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
2044 CfaExpr.push_back(0);
2045 // DW_CFA_expression: reg5 DW_OP_breg5 +0
2046 BuildCFI(MBB, MBBI, DL,
2047 MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
2049 } else if (!X86FI->hasSwiftAsyncContext()) {
2050 // Mark effective beginning of when frame pointer becomes valid.
2051 // Define the current CFA to use the EBP/RBP register.
2052 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2053 BuildCFI(
2054 MBB, MBBI, DL,
2055 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
2057 }
2058 }
2059
2060 if (NeedsWinFPO) {
2061 // .cv_fpo_setframe $FramePtr
2062 // NeedsWinFPO is Win32 only, so we're never using Unwind v3, hence it
2063 // is always inserted afterwards.
2064 assert(!IsWin64UnwindV3);
2065 HasWinCFI = true;
2066 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2068 .addImm(0)
2070 }
2071 }
2072 }
2073 } else {
2074 assert(!IsFunclet && "funclets without FPs not yet implemented");
2075 NumBytes =
2076 StackSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
2077 }
2078
2079 // Update the offset adjustment, which is mainly used by codeview to translate
2080 // from ESP to VFRAME relative local variable offsets.
2081 if (!IsFunclet) {
2082 if (HasFP && TRI->hasStackRealignment(MF))
2083 MFI.setOffsetAdjustment(-NumBytes);
2084 else
2085 MFI.setOffsetAdjustment(-StackSize);
2086 }
2087
2088 // For EH funclets, only allocate enough space for outgoing calls. Save the
2089 // NumBytes value that we would've used for the parent frame.
2090 unsigned ParentFrameNumBytes = NumBytes;
2091 if (IsFunclet)
2092 NumBytes = getWinEHFuncletFrameSize(MF);
2093
2094 // Skip the callee-saved push instructions.
2095 bool PushedRegs = false;
2096 int StackOffset = 2 * stackGrowth;
2098 auto IsCSPush = [&](const MachineBasicBlock::iterator &MBBI) {
2099 if (MBBI == MBB.end() || !MBBI->getFlag(MachineInstr::FrameSetup))
2100 return false;
2101 unsigned Opc = MBBI->getOpcode();
2102 return Opc == X86::PUSH32r || Opc == X86::PUSH64r || Opc == X86::PUSHP64r ||
2103 Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2104 };
2105
2106 while (IsCSPush(MBBI)) {
2107 PushedRegs = true;
2108 Register Reg = MBBI->getOperand(0).getReg();
2109 LastCSPush = MBBI;
2110 unsigned Opc = LastCSPush->getOpcode();
2111 bool IsPush2 = Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2112
2113 // V3: emit SEH pseudo before the real instruction.
2114 EmitSEHBefore([&]() {
2115 if (IsPush2) {
2116 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Push2Regs))
2117 .addImm(Reg)
2118 .addImm(LastCSPush->getOperand(1).getReg())
2120 } else {
2121 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2122 .addImm(Reg)
2124 }
2125 });
2126 ++MBBI;
2127
2128 if (!HasFP && NeedsDwarfCFI) {
2129 // Mark callee-saved push instruction.
2130 // Define the current CFA rule to use the provided offset.
2131 assert(StackSize);
2132 // Compared to push, push2 introduces more stack offset (one more
2133 // register).
2134 if (IsPush2)
2135 StackOffset += stackGrowth;
2136 BuildCFI(MBB, MBBI, DL,
2139 StackOffset += stackGrowth;
2140 }
2141
2142 // V1/V2: emit SEH pseudo after the real instruction.
2143 EmitSEHAfter([&]() {
2144 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2145 .addImm(Reg)
2147 if (IsPush2)
2148 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2149 .addImm(LastCSPush->getOperand(1).getReg())
2151 });
2152 }
2153
2154 // Realign stack after we pushed callee-saved registers (so that we'll be
2155 // able to calculate their offsets from the frame pointer).
2156 // Don't do this for Win64, it needs to realign the stack after the prologue.
2157 if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) &&
2158 !ArgBaseReg.isValid()) {
2159 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2160 auto EmitSEHStackAlign = [&]() {
2161 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
2162 .addImm(MaxAlign)
2164 };
2165 EmitSEHBefore(EmitSEHStackAlign);
2166 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
2167 EmitSEHAfter(EmitSEHStackAlign);
2168 }
2169
2170 // If there is an SUB32ri of ESP immediately before this instruction, merge
2171 // the two. This can be the case when tail call elimination is enabled and
2172 // the callee has more arguments than the caller.
2173 NumBytes = mergeSPUpdates(
2174 MBB, MBBI, [NumBytes](int64_t Offset) { return NumBytes - Offset; },
2175 true);
2176
2177 // Adjust stack pointer: ESP -= numbytes.
2178
2179 // Windows and cygwin/mingw require a prologue helper routine when allocating
2180 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
2181 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
2182 // stack and adjust the stack pointer in one go. The 64-bit version of
2183 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
2184 // responsible for adjusting the stack pointer. Touching the stack at 4K
2185 // increments is necessary to ensure that the guard pages used by the OS
2186 // virtual memory manager are allocated in correct sequence.
2187 uint64_t AlignedNumBytes = NumBytes;
2188 if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
2189 AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
2190
2191 auto EmitSEHStackAlloc = [&]() {
2192 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2193 .addImm(NumBytes)
2195 };
2196 if (NumBytes)
2197 EmitSEHBefore(EmitSEHStackAlloc);
2198
2199 if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
2200 assert(!X86FI->getUsesRedZone() &&
2201 "The Red Zone is not accounted for in stack probes");
2202
2203 // Check whether EAX is livein for this block.
2204 bool isEAXAlive = isEAXLiveIn(MBB);
2205
2206 if (isEAXAlive) {
2207 if (Is64Bit) {
2208 // Save RAX
2209 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2210 .addReg(X86::RAX, RegState::Kill)
2212 } else {
2213 // Save EAX
2214 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
2215 .addReg(X86::EAX, RegState::Kill)
2217 }
2218 }
2219
2220 if (Is64Bit) {
2221 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
2222 // Function prologue is responsible for adjusting the stack pointer.
2223 int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
2225 X86::RAX)
2226 .addImm(Alloc)
2228 } else {
2229 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
2230 // We'll also use 4 already allocated bytes for EAX.
2231 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
2232 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
2234 }
2235
2236 // Call __chkstk, __chkstk_ms, or __alloca.
2237 emitStackProbe(MF, MBB, MBBI, DL, true);
2238
2239 if (isEAXAlive) {
2240 // Restore RAX/EAX
2242 if (Is64Bit)
2243 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
2244 StackPtr, false, NumBytes - 8);
2245 else
2246 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
2247 StackPtr, false, NumBytes - 4);
2248 MI->setFlag(MachineInstr::FrameSetup);
2249 MBB.insert(MBBI, MI);
2250 }
2251 } else if (NumBytes) {
2252 emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
2253 }
2254
2255 if (NumBytes)
2256 EmitSEHAfter(EmitSEHStackAlloc);
2257
2258 int SEHFrameOffset = 0;
2259 Register SPOrEstablisher;
2260 if (IsFunclet) {
2261 if (IsClrFunclet) {
2262 // The establisher parameter passed to a CLR funclet is actually a pointer
2263 // to the (mostly empty) frame of its nearest enclosing funclet; we have
2264 // to find the root function establisher frame by loading the PSPSym from
2265 // the intermediate frame.
2266 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2267 MachinePointerInfo NoInfo;
2268 MBB.addLiveIn(Establisher);
2269 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
2270 Establisher, false, PSPSlotOffset)
2273 ;
2274 // Save the root establisher back into the current funclet's (mostly
2275 // empty) frame, in case a sub-funclet or the GC needs it.
2276 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
2277 false, PSPSlotOffset)
2278 .addReg(Establisher)
2280 NoInfo,
2283 }
2284 SPOrEstablisher = Establisher;
2285 } else {
2286 SPOrEstablisher = StackPtr;
2287 }
2288
2289 if (IsWin64Prologue && HasFP) {
2290 // Set RBP to a small fixed offset from RSP. In the funclet case, we base
2291 // this calculation on the incoming establisher, which holds the value of
2292 // RSP from the parent frame at the end of the prologue.
2293 SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
2294
2295 // If this is not a funclet, emit the CFI describing our frame pointer.
2296 if (NeedsWinCFI && !IsFunclet) {
2297 assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
2298 HasWinCFI = true;
2299 if (isAsynchronousEHPersonality(Personality) || MF.hasEHFunclets()) {
2300 if (TRI->hasBasePointer(MF))
2303 else
2304 MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
2305 }
2306 }
2307
2308 auto EmitSEHSetFrame = [&]() {
2309 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2311 .addImm(SEHFrameOffset)
2313 };
2314
2315 if (!IsFunclet)
2316 EmitSEHBefore(EmitSEHSetFrame);
2317
2318 if (SEHFrameOffset)
2319 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
2320 SPOrEstablisher, false, SEHFrameOffset);
2321 else
2322 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
2323 .addReg(SPOrEstablisher);
2324
2325 if (!IsFunclet)
2326 EmitSEHAfter(EmitSEHSetFrame);
2327 } else if (IsFunclet && STI.is32Bit()) {
2328 // Reset EBP / ESI to something good for funclets.
2330 // If we're a catch funclet, we can be returned to via catchret. Save ESP
2331 // into the registration node so that the runtime will restore it for us.
2332 if (!MBB.isCleanupFuncletEntry()) {
2333 assert(Personality == EHPersonality::MSVC_CXX);
2334 Register FrameReg;
2336 int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
2337 // ESP is the first field, so no extra displacement is needed.
2338 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
2339 false, EHRegOffset)
2340 .addReg(X86::ESP);
2341 }
2342 }
2343
2344 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
2345 const MachineInstr &FrameInstr = *MBBI;
2346
2347 if (NeedsWinCFI) {
2348 int FI;
2349 if (Register Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
2350 if (X86::FR64RegClass.contains(Reg)) {
2351 int Offset;
2352 Register IgnoredFrameReg;
2353 if (IsWin64Prologue && IsFunclet)
2354 Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
2355 else
2356 Offset =
2357 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2358 SEHFrameOffset;
2359
2360 assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
2361 auto EmitSEHSaveXMM = [&]() {
2362 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
2363 .addImm(Reg)
2364 .addImm(Offset)
2366 };
2367 EmitSEHBefore(EmitSEHSaveXMM);
2368 ++MBBI;
2369 EmitSEHAfter(EmitSEHSaveXMM);
2370 continue;
2371 }
2372 }
2373 }
2374 ++MBBI;
2375 }
2376
2377 if (NeedsWinCFI && HasWinCFI) {
2378 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
2380 }
2381
2382 if (FnHasClrFunclet && !IsFunclet) {
2383 // Save the so-called Initial-SP (i.e. the value of the stack pointer
2384 // immediately after the prolog) into the PSPSlot so that funclets
2385 // and the GC can recover it.
2386 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2387 auto PSPInfo = MachinePointerInfo::getFixedStack(
2389 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
2390 PSPSlotOffset)
2395 }
2396
2397 // Realign stack after we spilled callee-saved registers (so that we'll be
2398 // able to calculate their offsets from the frame pointer).
2399 // Win64 requires aligning the stack after the prologue.
2400 if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
2401 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2402 BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
2403 }
2404
2405 // We already dealt with stack realignment and funclets above.
2406 if (IsFunclet && STI.is32Bit())
2407 return;
2408
2409 // If we need a base pointer, set it up here. It's whatever the value
2410 // of the stack pointer is at this point. Any variable size objects
2411 // will be allocated after this, so we can still use the base pointer
2412 // to reference locals.
2413 if (TRI->hasBasePointer(MF)) {
2414 // Update the base pointer with the current stack pointer.
2415 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
2416 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
2417 .addReg(SPOrEstablisher)
2419 if (X86FI->getRestoreBasePointer()) {
2420 // Stash value of base pointer. Saving RSP instead of EBP shortens
2421 // dependence chain. Used by SjLj EH.
2422 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2423 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), FramePtr, true,
2425 .addReg(SPOrEstablisher)
2427 }
2428
2429 if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
2430 // Stash the value of the frame pointer relative to the base pointer for
2431 // Win32 EH. This supports Win32 EH, which does the inverse of the above:
2432 // it recovers the frame pointer from the base pointer rather than the
2433 // other way around.
2434 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2435 Register UsedReg;
2436 int Offset =
2437 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2438 .getFixed();
2439 assert(UsedReg == BasePtr);
2440 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
2443 }
2444 }
2445 if (ArgBaseReg.isValid()) {
2446 // Save argument base pointer.
2447 auto *MI = X86FI->getStackPtrSaveMI();
2448 int FI = MI->getOperand(1).getIndex();
2449 unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
2450 // movl %basereg, offset(%ebp)
2451 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), FI)
2452 .addReg(ArgBaseReg)
2454 }
2455
2456 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
2457 // Mark end of stack pointer adjustment.
2458 if (!HasFP && NumBytes) {
2459 // Define the current CFA rule to use the provided offset.
2460 assert(StackSize);
2461 BuildCFI(
2462 MBB, MBBI, DL,
2463 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
2465 }
2466
2467 // Emit DWARF info specifying the offsets of the callee-saved registers.
2469 }
2470
2471 // X86 Interrupt handling function cannot assume anything about the direction
2472 // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
2473 // in each prologue of interrupt handler function.
2474 //
2475 // Create "cld" instruction only in these cases:
2476 // 1. The interrupt handling function uses any of the "rep" instructions.
2477 // 2. Interrupt handling function calls another function.
2478 // 3. If there are any inline asm blocks, as we do not know what they do
2479 //
2480 // TODO: We should also emit cld if we detect the use of std, but as of now,
2481 // the compiler does not even emit that instruction or even define it, so in
2482 // practice, this would only happen with inline asm, which we cover anyway.
2484 bool NeedsCLD = false;
2485
2486 for (const MachineBasicBlock &B : MF) {
2487 for (const MachineInstr &MI : B) {
2488 if (MI.isCall()) {
2489 NeedsCLD = true;
2490 break;
2491 }
2492
2493 if (isOpcodeRep(MI.getOpcode())) {
2494 NeedsCLD = true;
2495 break;
2496 }
2497
2498 if (MI.isInlineAsm()) {
2499 // TODO: Parse asm for rep instructions or call sites?
2500 // For now, let's play it safe and emit a cld instruction
2501 // just in case.
2502 NeedsCLD = true;
2503 break;
2504 }
2505 }
2506 }
2507
2508 if (NeedsCLD) {
2509 BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
2511 }
2512 }
2513
2514 // At this point we know if the function has WinCFI or not.
2515 MF.setHasWinCFI(HasWinCFI);
2516}
2517
2519 const MachineFunction &MF) const {
2520 // We can't use LEA instructions for adjusting the stack pointer if we don't
2521 // have a frame pointer in the Win64 ABI. Only ADD instructions may be used
2522 // to deallocate the stack.
2523 // This means that we can use LEA for SP in two situations:
2524 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
2525 // 2. We *have* a frame pointer which means we are permitted to use LEA.
2526 return !MF.usesWindowsUnwindInfo() || hasFP(MF);
2527}
2528
2530 switch (MI.getOpcode()) {
2531 case X86::CATCHRET:
2532 case X86::CLEANUPRET:
2533 return true;
2534 default:
2535 return false;
2536 }
2537 llvm_unreachable("impossible");
2538}
2539
2540// CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
2541// stack. It holds a pointer to the bottom of the root function frame. The
2542// establisher frame pointer passed to a nested funclet may point to the
2543// (mostly empty) frame of its parent funclet, but it will need to find
2544// the frame of the root function to access locals. To facilitate this,
2545// every funclet copies the pointer to the bottom of the root function
2546// frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
2547// same offset for the PSPSym in the root function frame that's used in the
2548// funclets' frames allows each funclet to dynamically accept any ancestor
2549// frame as its establisher argument (the runtime doesn't guarantee the
2550// immediate parent for some reason lost to history), and also allows the GC,
2551// which uses the PSPSym for some bookkeeping, to find it in any funclet's
2552// frame with only a single offset reported for the entire method.
2553unsigned
2554X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
2555 const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
2557 int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2558 /*IgnoreSPUpdates*/ true)
2559 .getFixed();
2560 assert(Offset >= 0 && SPReg == TRI->getStackRegister());
2561 return static_cast<unsigned>(Offset);
2562}
2563
2564unsigned
2565X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2566 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2567 // This is the size of the pushed CSRs.
2568 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2569 // This is the size of callee saved XMMs.
2570 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2571 unsigned XMMSize =
2572 WinEHXMMSlotInfo.size() * TRI->getSpillSize(X86::VR128RegClass);
2573 // This is the amount of stack a funclet needs to allocate.
2574 unsigned UsedSize;
2575 EHPersonality Personality =
2577 if (Personality == EHPersonality::CoreCLR) {
2578 // CLR funclets need to hold enough space to include the PSPSym, at the
2579 // same offset from the stack pointer (immediately after the prolog) as it
2580 // resides at in the main function.
2581 UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
2582 } else {
2583 // Other funclets just need enough stack for outgoing call arguments.
2584 UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
2585 }
2586 // RBP is not included in the callee saved register block. After pushing RBP,
2587 // everything is 16 byte aligned. Everything we allocate before an outgoing
2588 // call must also be 16 byte aligned.
2589 unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
2590 // Subtract out the size of the callee saved registers. This is how much stack
2591 // each funclet will allocate.
2592 return FrameSizeMinusRBP + XMMSize - CSSize;
2593}
2594
2595static bool isTailCallOpcode(unsigned Opc) {
2596 return Opc == X86::TCRETURNri || Opc == X86::TCRETURN_WIN64ri ||
2597 Opc == X86::TCRETURN_HIPE32ri || Opc == X86::TCRETURNdi ||
2598 Opc == X86::TCRETURNmi || Opc == X86::TCRETURNri64 ||
2599 Opc == X86::TCRETURNri64_ImpCall || Opc == X86::TCRETURNdi64 ||
2600 Opc == X86::TCRETURNmi64 || Opc == X86::TCRETURN_WINmi64;
2601}
2602
2604 MachineBasicBlock &MBB) const {
2605 const MachineFrameInfo &MFI = MF.getFrameInfo();
2607 MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
2608 MachineBasicBlock::iterator MBBI = Terminator;
2609 DebugLoc DL;
2610 if (MBBI != MBB.end())
2611 DL = MBBI->getDebugLoc();
2612 // standard x86_64 uses 64-bit frame/stack pointers, x32 - 32-bit.
2613 const bool Is64BitILP32 = STI.isTarget64BitILP32();
2614 Register FramePtr = TRI->getFrameRegister(MF);
2615 Register MachineFramePtr =
2616 Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
2617
2618 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
2619 bool NeedsWin64CFI =
2620 IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
2621 // For V3 unwind, epilog SEH pseudos are emitted inline before each
2622 // unwind-effecting instruction.
2623 bool IsWin64UnwindV3 =
2624 NeedsWin64CFI && MF.hasWinCFI() && requireWinX64UnwindV3(MF);
2625 bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
2626
2627 // Get the number of bytes to allocate from the FrameInfo.
2628 uint64_t StackSize = MFI.getStackSize();
2629 uint64_t MaxAlign = calculateMaxStackAlign(MF);
2630 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2631 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
2632 bool HasFP = hasFP(MF);
2633 uint64_t NumBytes = 0;
2634
2635 bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
2637 !MF.getTarget().getTargetTriple().isUEFI()) &&
2638 MF.needsFrameMoves();
2639
2640 Register ArgBaseReg;
2641 if (auto *MI = X86FI->getStackPtrSaveMI()) {
2642 unsigned Opc = X86::LEA32r;
2643 Register StackReg = X86::ESP;
2644 ArgBaseReg = MI->getOperand(0).getReg();
2645 if (STI.is64Bit()) {
2646 Opc = X86::LEA64r;
2647 StackReg = X86::RSP;
2648 }
2649 // leal -4(%basereg), %esp
2650 // .cfi_def_cfa %esp, 4
2651 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackReg)
2652 .addUse(ArgBaseReg)
2653 .addImm(1)
2654 .addUse(X86::NoRegister)
2655 .addImm(-(int64_t)SlotSize)
2656 .addUse(X86::NoRegister)
2658 if (NeedsDwarfCFI) {
2659 unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackReg, true);
2660 BuildCFI(MBB, MBBI, DL,
2661 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2663 --MBBI;
2664 }
2665 --MBBI;
2666 }
2667
2668 if (IsFunclet) {
2669 assert(HasFP && "EH funclets without FP not yet implemented");
2670 NumBytes = getWinEHFuncletFrameSize(MF);
2671 } else if (HasFP) {
2672 // Calculate required stack adjustment.
2673 uint64_t FrameSize = StackSize - SlotSize;
2674 NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
2675
2676 // Callee-saved registers were pushed on stack before the stack was
2677 // realigned.
2678 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
2679 NumBytes = alignTo(FrameSize, MaxAlign);
2680 } else {
2681 NumBytes = StackSize - CSSize - TailCallArgReserveSize;
2682 }
2683 uint64_t SEHStackAllocAmt = NumBytes;
2684
2685 unsigned SEHFrameOffset = 0;
2686 if (IsWin64Prologue && HasFP)
2687 SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
2688
2689 // AfterPop is the position to insert .cfi_restore.
2691 if (HasFP) {
2692 if (X86FI->hasSwiftAsyncContext()) {
2693 // Discard the context.
2694 int64_t Offset = mergeSPAdd(MBB, MBBI, 16, true);
2695 emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/ true);
2696 }
2697 // Pop EBP.
2698 if (IsWin64UnwindV3)
2699 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
2702 BuildMI(MBB, MBBI, DL,
2704 MachineFramePtr)
2706
2707 // We need to reset FP to its untagged state on return. Bit 60 is currently
2708 // used to show the presence of an extended frame.
2709 if (X86FI->hasSwiftAsyncContext()) {
2710 BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8), MachineFramePtr)
2711 .addUse(MachineFramePtr)
2712 .addImm(60)
2714 }
2715
2716 if (NeedsDwarfCFI) {
2717 if (!ArgBaseReg.isValid()) {
2718 unsigned DwarfStackPtr =
2719 TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
2720 BuildCFI(MBB, MBBI, DL,
2721 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2723 }
2724 if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
2725 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2726 BuildCFI(MBB, AfterPop, DL,
2727 MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
2729 --MBBI;
2730 --AfterPop;
2731 }
2732 --MBBI;
2733 }
2734 }
2735
2736 MachineBasicBlock::iterator FirstCSPop = MBBI;
2737 // Skip the callee-saved pop instructions.
2738 while (MBBI != MBB.begin()) {
2739 MachineBasicBlock::iterator PI = std::prev(MBBI);
2740 unsigned Opc = PI->getOpcode();
2741
2742 if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
2743 if (!PI->getFlag(MachineInstr::FrameDestroy) ||
2744 (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::BTR64ri8 &&
2745 Opc != X86::ADD64ri32 && Opc != X86::POPP64r && Opc != X86::POP2 &&
2746 Opc != X86::POP2P && Opc != X86::LEA64r && Opc != X86::SEH_PushReg &&
2747 Opc != X86::SEH_Push2Regs && Opc != X86::SEH_StackAlloc &&
2748 Opc != X86::ADD64ri32_NF))
2749 break;
2750 FirstCSPop = PI;
2751 }
2752
2753 --MBBI;
2754 }
2755 if (ArgBaseReg.isValid()) {
2756 // Restore argument base pointer.
2757 auto *MI = X86FI->getStackPtrSaveMI();
2758 int FI = MI->getOperand(1).getIndex();
2759 unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm;
2760 // movl offset(%ebp), %basereg
2761 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVrm), ArgBaseReg), FI)
2763 }
2764 MBBI = FirstCSPop;
2765
2766 if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
2767 emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
2768
2769 if (MBBI != MBB.end())
2770 DL = MBBI->getDebugLoc();
2771 // If there is an ADD32ri or SUB32ri of ESP immediately before this
2772 // instruction, merge the two instructions.
2773 if (NumBytes || MFI.hasVarSizedObjects())
2774 NumBytes = mergeSPAdd(MBB, MBBI, NumBytes, true);
2775
2776 if (IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI()) {
2777 // Find the XMM restores that were tagged with FrameDestroy, now that we
2778 // know the offset we can emit the SEH pseudos for them.
2779 auto EpilogStart = MBBI;
2780 {
2781 auto ScanIt = MBBI;
2782 while (ScanIt != MBB.begin()) {
2783 auto PI = std::prev(ScanIt);
2784 int FI;
2785 if (PI->getFlag(MachineInstr::FrameDestroy) &&
2786 TII.isLoadFromStackSlot(*PI, FI)) {
2787 Register Reg = PI->getOperand(0).getReg();
2788 if (X86::FR64RegClass.contains(Reg)) {
2789 Register IgnoredFrameReg;
2790 int Offset =
2791 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2792 SEHFrameOffset;
2793 BuildMI(MBB, PI, DL, TII.get(X86::SEH_SaveXMM))
2794 .addImm(Reg)
2795 .addImm(Offset)
2797 // std::prev(PI) is the SEH_SaveXMM we just inserted (before PI).
2798 // We start ScanIt from that point so that the next
2799 // std::prev(ScanIt) will examine the instruction before the pseudo,
2800 // i.e. the next potential XMM restore further up the block.
2801 EpilogStart = std::prev(PI);
2802 ScanIt = EpilogStart;
2803 continue;
2804 }
2805 }
2806 break;
2807 }
2808 }
2809
2810 // For V3, SEH_BeginEpilogue must be emitted before any epilog SEH pseudos.
2811 BuildMI(MBB, EpilogStart, DL, TII.get(X86::SEH_BeginEpilogue))
2813 }
2814
2815 // If dynamic alloca is used, then reset esp to point to the last callee-saved
2816 // slot before popping them off! Same applies for the case, when stack was
2817 // realigned. Don't do this if this was a funclet epilogue, since the funclets
2818 // will not do realignment or dynamic stack allocation.
2819 if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
2820 !IsFunclet) {
2821 if (TRI->hasStackRealignment(MF))
2822 MBBI = FirstCSPop;
2823 uint64_t LEAAmount =
2824 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
2825
2826 if (X86FI->hasSwiftAsyncContext())
2827 LEAAmount -= 16;
2828
2829 // There are only two legal forms of epilogue:
2830 // - add SEHAllocationSize, %rsp
2831 // - lea SEHAllocationSize(%FramePtr), %rsp
2832 //
2833 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
2834 // However, we may use this sequence if we have a frame pointer because the
2835 // effects of the prologue can safely be undone.
2836 if (IsWin64UnwindV3) {
2837 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
2839 .addImm(SEHFrameOffset)
2841 if (SEHStackAllocAmt)
2842 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2843 .addImm(SEHStackAllocAmt)
2845 }
2846 if (LEAAmount != 0) {
2849 false, LEAAmount);
2850 --MBBI;
2851 } else {
2852 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
2854 --MBBI;
2855 }
2856 } else if (NumBytes) {
2857 // Adjust stack pointer back: ESP += numbytes.
2858 if (IsWin64UnwindV3)
2859 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
2860 .addImm(NumBytes)
2862 emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2863 if (!HasFP && NeedsDwarfCFI) {
2864 // Define the current CFA rule to use the provided offset.
2865 BuildCFI(MBB, MBBI, DL,
2867 nullptr, CSSize + TailCallArgReserveSize + SlotSize),
2869 }
2870 --MBBI;
2871 }
2872
2873 // For V1/V2, emit SEH_BeginEpilogue after stack restore code.
2874 if (!IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI())
2875 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_BeginEpilogue))
2877
2878 if (!HasFP && NeedsDwarfCFI) {
2879 MBBI = FirstCSPop;
2880 int64_t Offset = -(int64_t)CSSize - SlotSize;
2881 // Mark callee-saved pop instruction.
2882 // Define the current CFA rule to use the provided offset.
2883 while (MBBI != MBB.end()) {
2885 unsigned Opc = PI->getOpcode();
2886 ++MBBI;
2887 if (Opc == X86::POP32r || Opc == X86::POP64r || Opc == X86::POPP64r ||
2888 Opc == X86::POP2 || Opc == X86::POP2P) {
2889 Offset += SlotSize;
2890 // Compared to pop, pop2 introduces more stack offset (one more
2891 // register).
2892 if (Opc == X86::POP2 || Opc == X86::POP2P)
2893 Offset += SlotSize;
2894 BuildCFI(MBB, MBBI, DL,
2897 }
2898 }
2899 }
2900
2901 // Emit DWARF info specifying the restores of the callee-saved registers.
2902 // For epilogue with return inside or being other block without successor,
2903 // no need to generate .cfi_restore for callee-saved registers.
2904 if (NeedsDwarfCFI && !MBB.succ_empty())
2905 emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
2906
2907 if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
2908 // Add the return addr area delta back since we are not tail calling.
2909 int64_t Delta = X86FI->getTCReturnAddrDelta();
2910 assert(Delta <= 0 && "TCDelta should never be positive");
2911 if (Delta) {
2912 // Check for possible merge with preceding ADD instruction.
2913 int64_t Offset = mergeSPAdd(MBB, Terminator, -Delta, true);
2914 emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
2915 }
2916 }
2917
2918 // Emit tilerelease for AMX kernel.
2920 BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
2921
2922 if (NeedsWin64CFI && MF.hasWinCFI())
2923 BuildMI(MBB, Terminator, DL, TII.get(X86::SEH_EndEpilogue))
2925}
2926
2928 int FI,
2929 Register &FrameReg) const {
2930 const MachineFrameInfo &MFI = MF.getFrameInfo();
2931
2932 bool IsFixed = MFI.isFixedObjectIndex(FI);
2933 // We can't calculate offset from frame pointer if the stack is realigned,
2934 // so enforce usage of stack/base pointer. The base pointer is used when we
2935 // have dynamic allocas in addition to dynamic realignment.
2936 if (TRI->hasBasePointer(MF))
2937 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2938 else if (TRI->hasStackRealignment(MF))
2939 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
2940 else
2941 FrameReg = TRI->getFrameRegister(MF);
2942
2943 // Offset will hold the offset from the stack pointer at function entry to the
2944 // object.
2945 // We need to factor in additional offsets applied during the prologue to the
2946 // frame, base, and stack pointer depending on which is used.
2947 int64_t Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
2949 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2950 uint64_t StackSize = MFI.getStackSize();
2951 bool IsWin64Prologue = MF.usesWindowsUnwindInfo();
2952 int64_t FPDelta = 0;
2953
2954 // In an x86 interrupt, remove the offset we added to account for the return
2955 // address from any stack object allocated in the caller's frame. Interrupts
2956 // do not have a standard return address. Fixed objects in the current frame,
2957 // such as SSE register spills, should not get this treatment.
2959 Offset >= 0) {
2961 }
2962
2963 if (IsWin64Prologue) {
2964 assert(!MFI.hasCalls() || (StackSize % 16) == 8);
2965
2966 // Calculate required stack adjustment.
2967 uint64_t FrameSize = StackSize - SlotSize;
2968 // If required, include space for extra hidden slot for stashing base
2969 // pointer.
2970 if (X86FI->getRestoreBasePointer())
2971 FrameSize += SlotSize;
2972 uint64_t NumBytes = FrameSize - CSSize;
2973
2974 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
2975 if (FI && FI == X86FI->getFAIndex())
2976 return StackOffset::getFixed(-SEHFrameOffset);
2977
2978 // FPDelta is the offset from the "traditional" FP location of the old base
2979 // pointer followed by return address and the location required by the
2980 // restricted Win64 prologue.
2981 // Add FPDelta to all offsets below that go through the frame pointer.
2982 FPDelta = FrameSize - SEHFrameOffset;
2983 assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
2984 "FPDelta isn't aligned per the Win64 ABI!");
2985 }
2986
2987 if (FrameReg == TRI->getFramePtr()) {
2988 // Skip saved EBP/RBP
2989 Offset += SlotSize;
2990
2991 // Account for restricted Windows prologue.
2992 Offset += FPDelta;
2993
2994 // Skip the RETADDR move area
2995 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
2996 if (TailCallReturnAddrDelta < 0)
2997 Offset -= TailCallReturnAddrDelta;
2998
3000 }
3001
3002 // FrameReg is either the stack pointer or a base pointer. But the base is
3003 // located at the end of the statically known StackSize so the distinction
3004 // doesn't really matter.
3005 if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
3006 assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
3007 return StackOffset::getFixed(Offset + StackSize);
3008}
3009
3011 Register &FrameReg) const {
3012 const MachineFrameInfo &MFI = MF.getFrameInfo();
3014 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
3015 const auto it = WinEHXMMSlotInfo.find(FI);
3016
3017 if (it == WinEHXMMSlotInfo.end())
3018 return getFrameIndexReference(MF, FI, FrameReg).getFixed();
3019
3020 FrameReg = TRI->getStackRegister();
3021 return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
3022 it->second;
3023}
3024
3027 Register &FrameReg,
3028 int Adjustment) const {
3029 const MachineFrameInfo &MFI = MF.getFrameInfo();
3030 FrameReg = TRI->getStackRegister();
3031 return StackOffset::getFixed(MFI.getObjectOffset(FI) -
3032 getOffsetOfLocalArea() + Adjustment);
3033}
3034
3037 int FI, Register &FrameReg,
3038 bool IgnoreSPUpdates) const {
3039
3040 const MachineFrameInfo &MFI = MF.getFrameInfo();
3041 // Does not include any dynamic realign.
3042 const uint64_t StackSize = MFI.getStackSize();
3043 // LLVM arranges the stack as follows:
3044 // ...
3045 // ARG2
3046 // ARG1
3047 // RETADDR
3048 // PUSH RBP <-- RBP points here
3049 // PUSH CSRs
3050 // ~~~~~~~ <-- possible stack realignment (non-win64)
3051 // ...
3052 // STACK OBJECTS
3053 // ... <-- RSP after prologue points here
3054 // ~~~~~~~ <-- possible stack realignment (win64)
3055 //
3056 // if (hasVarSizedObjects()):
3057 // ... <-- "base pointer" (ESI/RBX) points here
3058 // DYNAMIC ALLOCAS
3059 // ... <-- RSP points here
3060 //
3061 // Case 1: In the simple case of no stack realignment and no dynamic
3062 // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
3063 // with fixed offsets from RSP.
3064 //
3065 // Case 2: In the case of stack realignment with no dynamic allocas, fixed
3066 // stack objects are addressed with RBP and regular stack objects with RSP.
3067 //
3068 // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
3069 // to address stack arguments for outgoing calls and nothing else. The "base
3070 // pointer" points to local variables, and RBP points to fixed objects.
3071 //
3072 // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
3073 // answer we give is relative to the SP after the prologue, and not the
3074 // SP in the middle of the function.
3075
3076 if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
3077 !STI.isTargetWin64())
3078 return getFrameIndexReference(MF, FI, FrameReg);
3079
3080 // If !hasReservedCallFrame the function might have SP adjustement in the
3081 // body. So, even though the offset is statically known, it depends on where
3082 // we are in the function.
3083 if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
3084 return getFrameIndexReference(MF, FI, FrameReg);
3085
3086 // We don't handle tail calls, and shouldn't be seeing them either.
3088 "we don't handle this case!");
3089
3090 // This is how the math works out:
3091 //
3092 // %rsp grows (i.e. gets lower) left to right. Each box below is
3093 // one word (eight bytes). Obj0 is the stack slot we're trying to
3094 // get to.
3095 //
3096 // ----------------------------------
3097 // | BP | Obj0 | Obj1 | ... | ObjN |
3098 // ----------------------------------
3099 // ^ ^ ^ ^
3100 // A B C E
3101 //
3102 // A is the incoming stack pointer.
3103 // (B - A) is the local area offset (-8 for x86-64) [1]
3104 // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
3105 //
3106 // |(E - B)| is the StackSize (absolute value, positive). For a
3107 // stack that grown down, this works out to be (B - E). [3]
3108 //
3109 // E is also the value of %rsp after stack has been set up, and we
3110 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
3111 // (C - E) == (C - A) - (B - A) + (B - E)
3112 // { Using [1], [2] and [3] above }
3113 // == getObjectOffset - LocalAreaOffset + StackSize
3114
3115 return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
3116}
3117
3120 std::vector<CalleeSavedInfo> &CSI) const {
3121 MachineFrameInfo &MFI = MF.getFrameInfo();
3123
3124 unsigned CalleeSavedFrameSize = 0;
3125 unsigned XMMCalleeSavedFrameSize = 0;
3126 auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
3127 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
3128
3129 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
3130
3131 if (TailCallReturnAddrDelta < 0) {
3132 // create RETURNADDR area
3133 // arg
3134 // arg
3135 // RETADDR
3136 // { ...
3137 // RETADDR area
3138 // ...
3139 // }
3140 // [EBP]
3141 MFI.CreateFixedObject(-TailCallReturnAddrDelta,
3142 TailCallReturnAddrDelta - SlotSize, true);
3143 }
3144
3145 // Spill the BasePtr if it's used.
3146 if (this->TRI->hasBasePointer(MF)) {
3147 // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
3148 if (MF.hasEHFunclets()) {
3150 X86FI->setHasSEHFramePtrSave(true);
3151 X86FI->setSEHFramePtrSaveIndex(FI);
3152 }
3153 }
3154
3155 bool IsFPRemovedFromCSI = false;
3156 if (hasFP(MF)) {
3157 // emitPrologue always spills frame register the first thing.
3158 SpillSlotOffset -= SlotSize;
3159 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3160
3161 // The async context lives directly before the frame pointer, and we
3162 // allocate a second slot to preserve stack alignment.
3163 if (X86FI->hasSwiftAsyncContext()) {
3164 SpillSlotOffset -= SlotSize;
3165 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3166 SpillSlotOffset -= SlotSize;
3167 }
3168
3169 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
3170 // the frame register, we can delete it from CSI list and not have to worry
3171 // about avoiding it later.
3172 Register FPReg = TRI->getFrameRegister(MF);
3173 for (unsigned i = 0; i < CSI.size(); ++i) {
3174 if (TRI->regsOverlap(CSI[i].getReg(), FPReg)) {
3175 CSI.erase(CSI.begin() + i);
3176 IsFPRemovedFromCSI = true;
3177 break;
3178 }
3179 }
3180 }
3181
3182 // Strategy:
3183 // 1. Use push2 when
3184 // a) number of CSR > 1 if no need padding
3185 // b) number of CSR > 2 if need padding
3186 // c) stack alignment >= 16 bytes
3187 // 2. When the number of CSR push is odd
3188 // a. Start to use push2 from the 1st push if stack is 16B aligned.
3189 // b. Start to use push2 from the 2nd push if stack is not 16B aligned.
3190 // 3. When the number of CSR push is even, start to use push2 from the 1st
3191 // push and make the stack 16B aligned before the push
3192 unsigned NumRegsForPush2 = 0;
3193 if (STI.hasPush2Pop2() && getStackAlignment() >= 16) {
3194 unsigned NumCSGPR = llvm::count_if(CSI, [](const CalleeSavedInfo &I) {
3195 return X86::GR64RegClass.contains(I.getReg());
3196 });
3197 bool UsePush2Pop2 = !IsFPRemovedFromCSI ? NumCSGPR > 2 : NumCSGPR > 1;
3198 NumRegsForPush2 =
3199 UsePush2Pop2
3200 ? alignDown(IsFPRemovedFromCSI ? NumCSGPR : NumCSGPR - 1, 2)
3201 : 0;
3202 }
3203
3204 // Assign slots for GPRs. It increases frame size.
3205 for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
3206 MCRegister Reg = I.getReg();
3207
3208 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3209 continue;
3210
3211 // A CSR is a candidate for push2/pop2 when it's slot offset is 16B aligned
3212 // or only an odd number of registers in the candidates.
3213 if (X86FI->getNumCandidatesForPush2Pop2() < NumRegsForPush2 &&
3214 (SpillSlotOffset % 16 == 0 ||
3215 X86FI->getNumCandidatesForPush2Pop2() % 2))
3216 X86FI->addCandidateForPush2Pop2(Reg);
3217
3218 SpillSlotOffset -= SlotSize;
3219 CalleeSavedFrameSize += SlotSize;
3220
3221 int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3222 I.setFrameIdx(SlotIndex);
3223 }
3224
3225 // Adjust the offset of spill slot as we know the accurate callee saved frame
3226 // size.
3227 if (X86FI->getRestoreBasePointer()) {
3228 SpillSlotOffset -= SlotSize;
3229 CalleeSavedFrameSize += SlotSize;
3230
3231 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
3232 // TODO: saving the slot index is better?
3233 X86FI->setRestoreBasePointer(CalleeSavedFrameSize);
3234 }
3235 assert(X86FI->getNumCandidatesForPush2Pop2() % 2 == 0 &&
3236 "Expect even candidates for push2/pop2");
3237 if (X86FI->getNumCandidatesForPush2Pop2())
3238 ++NumFunctionUsingPush2Pop2;
3239 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
3240 MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
3241
3242 // Assign slots for XMMs.
3243 for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
3244 MCRegister Reg = I.getReg();
3245 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3246 continue;
3247
3249 unsigned Size = TRI->getSpillSize(*RC);
3250 Align Alignment = TRI->getSpillAlign(*RC);
3251 // ensure alignment
3252 assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
3253 SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
3254
3255 // spill into slot
3256 SpillSlotOffset -= Size;
3257 int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
3258 I.setFrameIdx(SlotIndex);
3259 MFI.ensureMaxAlignment(Alignment);
3260
3261 // Save the start offset and size of XMM in stack frame for funclets.
3262 if (X86::VR128RegClass.contains(Reg)) {
3263 WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
3264 XMMCalleeSavedFrameSize += Size;
3265 }
3266 }
3267
3268 return true;
3269}
3270
3274 DebugLoc DL = MBB.findDebugLoc(MI);
3275
3276 // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
3277 // for us, and there are no XMM CSRs on Win32.
3278 if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
3279 return true;
3280
3281 // Push GPRs. It increases frame size.
3282 const MachineFunction &MF = *MBB.getParent();
3284
3285 // Update LiveIn of the basic block and decide whether we can add a kill flag
3286 // to the use.
3287 auto UpdateLiveInCheckCanKill = [&](Register Reg) {
3288 const MachineRegisterInfo &MRI = MF.getRegInfo();
3289 // Do not set a kill flag on values that are also marked as live-in. This
3290 // happens with the @llvm-returnaddress intrinsic and with arguments
3291 // passed in callee saved registers.
3292 // Omitting the kill flags is conservatively correct even if the live-in
3293 // is not used after all.
3294 if (MRI.isLiveIn(Reg))
3295 return false;
3296 MBB.addLiveIn(Reg);
3297 // Check if any subregister is live-in
3298 for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg)
3299 if (MRI.isLiveIn(*AReg))
3300 return false;
3301 return true;
3302 };
3303 auto UpdateLiveInGetKillRegState = [&](Register Reg) {
3304 return getKillRegState(UpdateLiveInCheckCanKill(Reg));
3305 };
3306
3307 for (auto RI = CSI.rbegin(), RE = CSI.rend(); RI != RE; ++RI) {
3308 MCRegister Reg = RI->getReg();
3309 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3310 continue;
3311
3312 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3313 MCRegister Reg2 = (++RI)->getReg();
3315 .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
3316 .addReg(Reg2, UpdateLiveInGetKillRegState(Reg2))
3318 } else {
3319 BuildMI(MBB, MI, DL, TII.get(getPUSHOpcode(STI)))
3320 .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
3322 }
3323 }
3324
3325 if (X86FI->getRestoreBasePointer()) {
3326 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
3327 Register BaseReg = this->TRI->getBaseRegister();
3328 BuildMI(MBB, MI, DL, TII.get(Opc))
3329 .addReg(BaseReg, getKillRegState(true))
3331 }
3332
3333 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
3334 // It can be done by spilling XMMs to stack frame.
3335 for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
3336 MCRegister Reg = I.getReg();
3337 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3338 continue;
3339
3340 // Add the callee-saved register as live-in. It's killed at the spill.
3341 MBB.addLiveIn(Reg);
3343
3344 TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, Register(),
3346 }
3347
3348 return true;
3349}
3350
3351void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
3353 MachineInstr *CatchRet) const {
3354 // SEH shouldn't use catchret.
3356 MBB.getParent()->getFunction().getPersonalityFn())) &&
3357 "SEH should not use CATCHRET");
3358 const DebugLoc &DL = CatchRet->getDebugLoc();
3359 MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
3360
3361 // Fill EAX/RAX with the address of the target block.
3362 if (STI.is64Bit()) {
3363 // LEA64r CatchRetTarget(%rip), %rax
3364 BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
3365 .addReg(X86::RIP)
3366 .addImm(0)
3367 .addReg(0)
3368 .addMBB(CatchRetTarget)
3369 .addReg(0);
3370 } else {
3371 // MOV32ri $CatchRetTarget, %eax
3372 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
3373 .addMBB(CatchRetTarget);
3374 }
3375
3376 // Record that we've taken the address of CatchRetTarget and no longer just
3377 // reference it in a terminator.
3378 CatchRetTarget->setMachineBlockAddressTaken();
3379}
3380
3384 if (CSI.empty())
3385 return false;
3386
3387 if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
3388 // Don't restore CSRs in 32-bit EH funclets. Matches
3389 // spillCalleeSavedRegisters.
3390 if (STI.is32Bit())
3391 return true;
3392 // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
3393 // funclets. emitEpilogue transforms these to normal jumps.
3394 if (MI->getOpcode() == X86::CATCHRET) {
3395 const Function &F = MBB.getParent()->getFunction();
3396 bool IsSEH = isAsynchronousEHPersonality(
3397 classifyEHPersonality(F.getPersonalityFn()));
3398 if (IsSEH)
3399 return true;
3400 }
3401 }
3402
3403 DebugLoc DL = MBB.findDebugLoc(MI);
3404 MachineFunction &MF = *MBB.getParent();
3406
3407 bool NeedsWin64CFI = MF.needsWinCFI();
3408 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
3409
3410 // Reload XMMs from stack frame.
3411 for (const CalleeSavedInfo &I : CSI) {
3412 MCRegister Reg = I.getReg();
3413 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3414 continue;
3415
3417 TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, Register(), 0,
3419 }
3420
3421 // Clear the stack slot for spill base pointer register.
3422 if (X86FI->getRestoreBasePointer()) {
3423 if (IsWin64UnwindV3)
3424 BuildMI(MBB, MI, DL, TII.get(X86::SEH_PushReg))
3425 .addImm(this->TRI->getBaseRegister())
3427 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
3428 Register BaseReg = this->TRI->getBaseRegister();
3429 BuildMI(MBB, MI, DL, TII.get(Opc), BaseReg)
3431 }
3432
3433 // POP GPRs.
3434 for (auto I = CSI.begin(), E = CSI.end(); I != E; ++I) {
3435 MCRegister Reg = I->getReg();
3436 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3437 continue;
3438
3439 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3440 MCRegister Reg2 = (++I)->getReg();
3441 if (IsWin64UnwindV3) {
3442 BuildMI(MBB, MI, DL, TII.get(X86::SEH_Push2Regs))
3443 .addImm(Reg)
3444 .addImm(Reg2)
3446 }
3447 BuildMI(MBB, MI, DL, TII.get(getPOP2Opcode(STI)), Reg)
3448 .addReg(Reg2, RegState::Define)
3450 } else {
3451 if (IsWin64UnwindV3)
3452 BuildMI(MBB, MI, DL, TII.get(X86::SEH_PushReg))
3453 .addImm(Reg)
3455 BuildMI(MBB, MI, DL, TII.get(getPOPOpcode(STI)), Reg)
3457 }
3458 }
3459
3460 return true;
3461}
3462
3464 BitVector &SavedRegs,
3465 RegScavenger *RS) const {
3467
3468 // Spill the BasePtr if it's used.
3469 if (TRI->hasBasePointer(MF)) {
3470 Register BasePtr = TRI->getBaseRegister();
3471 if (STI.isTarget64BitILP32())
3472 BasePtr = getX86SubSuperRegister(BasePtr, 64);
3473 SavedRegs.set(BasePtr);
3474 }
3475 if (STI.hasUserReservedRegisters()) {
3476 for (int Reg = SavedRegs.find_first(); Reg != -1;
3477 Reg = SavedRegs.find_next(Reg)) {
3478 if (STI.isRegisterReservedByUser(Reg)) {
3479 SavedRegs.reset(Reg);
3480 }
3481 }
3482 }
3483}
3484
3485static bool HasNestArgument(const MachineFunction *MF) {
3486 const Function &F = MF->getFunction();
3487 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3488 I++) {
3489 if (I->hasNestAttr() && !I->use_empty())
3490 return true;
3491 }
3492 return false;
3493}
3494
3495/// GetScratchRegister - Get a temp register for performing work in the
3496/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
3497/// and the properties of the function either one or two registers will be
3498/// needed. Set primary to true for the first register, false for the second.
3499static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64,
3500 const MachineFunction &MF, bool Primary) {
3501 CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
3502
3503 // Erlang stuff.
3504 if (CallingConvention == CallingConv::HiPE) {
3505 if (Is64Bit)
3506 return Primary ? X86::R14 : X86::R13;
3507 else
3508 return Primary ? X86::EBX : X86::EDI;
3509 }
3510
3511 if (Is64Bit) {
3512 if (IsLP64)
3513 return Primary ? X86::R11 : X86::R12;
3514 else
3515 return Primary ? X86::R11D : X86::R12D;
3516 }
3517
3518 bool IsNested = HasNestArgument(&MF);
3519
3520 if (CallingConvention == CallingConv::X86_FastCall ||
3521 CallingConvention == CallingConv::Fast ||
3522 CallingConvention == CallingConv::Tail) {
3523 if (IsNested)
3524 report_fatal_error("Segmented stacks does not support fastcall with "
3525 "nested function.");
3526 return Primary ? X86::EAX : X86::ECX;
3527 }
3528 if (IsNested)
3529 return Primary ? X86::EDX : X86::EAX;
3530 return Primary ? X86::ECX : X86::EAX;
3531}
3532
3533// The stack limit in the TCB is set to this many bytes above the actual stack
3534// limit.
3536
3538 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3539 MachineFrameInfo &MFI = MF.getFrameInfo();
3540 uint64_t StackSize;
3541 unsigned TlsReg, TlsOffset;
3542 DebugLoc DL;
3543
3544 // To support shrink-wrapping we would need to insert the new blocks
3545 // at the right place and update the branches to PrologueMBB.
3546 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3547
3548 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3549 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3550 "Scratch register is live-in");
3551
3552 if (MF.getFunction().isVarArg())
3553 report_fatal_error("Segmented stacks do not support vararg functions.");
3554 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
3555 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
3556 !STI.isTargetDragonFly())
3557 report_fatal_error("Segmented stacks not supported on this platform.");
3558
3559 // Eventually StackSize will be calculated by a link-time pass; which will
3560 // also decide whether checking code needs to be injected into this particular
3561 // prologue.
3562 StackSize = MFI.getStackSize();
3563
3564 if (!MFI.needsSplitStackProlog())
3565 return;
3566
3570 bool IsNested = false;
3571
3572 // We need to know if the function has a nest argument only in 64 bit mode.
3573 if (Is64Bit)
3574 IsNested = HasNestArgument(&MF);
3575
3576 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
3577 // allocMBB needs to be last (terminating) instruction.
3578
3579 for (const auto &LI : PrologueMBB.liveins()) {
3580 allocMBB->addLiveIn(LI);
3581 checkMBB->addLiveIn(LI);
3582 }
3583
3584 if (IsNested)
3585 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
3586
3587 MF.push_front(allocMBB);
3588 MF.push_front(checkMBB);
3589
3590 // When the frame size is less than 256 we just compare the stack
3591 // boundary directly to the value of the stack pointer, per gcc.
3592 bool CompareStackPointer = StackSize < kSplitStackAvailable;
3593
3594 // Read the limit off the current stacklet off the stack_guard location.
3595 if (Is64Bit) {
3596 if (STI.isTargetLinux()) {
3597 TlsReg = X86::FS;
3598 TlsOffset = IsLP64 ? 0x70 : 0x40;
3599 } else if (STI.isTargetDarwin()) {
3600 TlsReg = X86::GS;
3601 TlsOffset = 0x60 + 90 * 8; // See pthread_machdep.h. Steal TLS slot 90.
3602 } else if (STI.isTargetWin64()) {
3603 TlsReg = X86::GS;
3604 TlsOffset = 0x28; // pvArbitrary, reserved for application use
3605 } else if (STI.isTargetFreeBSD()) {
3606 TlsReg = X86::FS;
3607 TlsOffset = 0x18;
3608 } else if (STI.isTargetDragonFly()) {
3609 TlsReg = X86::FS;
3610 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
3611 } else {
3612 report_fatal_error("Segmented stacks not supported on this platform.");
3613 }
3614
3615 if (CompareStackPointer)
3616 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
3617 else
3618 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r),
3619 ScratchReg)
3620 .addReg(X86::RSP)
3621 .addImm(1)
3622 .addReg(0)
3623 .addImm(-StackSize)
3624 .addReg(0);
3625
3626 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm))
3627 .addReg(ScratchReg)
3628 .addReg(0)
3629 .addImm(1)
3630 .addReg(0)
3631 .addImm(TlsOffset)
3632 .addReg(TlsReg);
3633 } else {
3634 if (STI.isTargetLinux()) {
3635 TlsReg = X86::GS;
3636 TlsOffset = 0x30;
3637 } else if (STI.isTargetDarwin()) {
3638 TlsReg = X86::GS;
3639 TlsOffset = 0x48 + 90 * 4;
3640 } else if (STI.isTargetWin32()) {
3641 TlsReg = X86::FS;
3642 TlsOffset = 0x14; // pvArbitrary, reserved for application use
3643 } else if (STI.isTargetDragonFly()) {
3644 TlsReg = X86::FS;
3645 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
3646 } else if (STI.isTargetFreeBSD()) {
3647 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
3648 } else {
3649 report_fatal_error("Segmented stacks not supported on this platform.");
3650 }
3651
3652 if (CompareStackPointer)
3653 ScratchReg = X86::ESP;
3654 else
3655 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg)
3656 .addReg(X86::ESP)
3657 .addImm(1)
3658 .addReg(0)
3659 .addImm(-StackSize)
3660 .addReg(0);
3661
3662 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
3663 STI.isTargetDragonFly()) {
3664 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
3665 .addReg(ScratchReg)
3666 .addReg(0)
3667 .addImm(0)
3668 .addReg(0)
3669 .addImm(TlsOffset)
3670 .addReg(TlsReg);
3671 } else if (STI.isTargetDarwin()) {
3672
3673 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
3674 unsigned ScratchReg2;
3675 bool SaveScratch2;
3676 if (CompareStackPointer) {
3677 // The primary scratch register is available for holding the TLS offset.
3678 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3679 SaveScratch2 = false;
3680 } else {
3681 // Need to use a second register to hold the TLS offset
3682 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
3683
3684 // Unfortunately, with fastcc the second scratch register may hold an
3685 // argument.
3686 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
3687 }
3688
3689 // If Scratch2 is live-in then it needs to be saved.
3690 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
3691 "Scratch register is live-in and not saved");
3692
3693 if (SaveScratch2)
3694 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
3695 .addReg(ScratchReg2, RegState::Kill);
3696
3697 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
3698 .addImm(TlsOffset);
3699 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
3700 .addReg(ScratchReg)
3701 .addReg(ScratchReg2)
3702 .addImm(1)
3703 .addReg(0)
3704 .addImm(0)
3705 .addReg(TlsReg);
3706
3707 if (SaveScratch2)
3708 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
3709 }
3710 }
3711
3712 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
3713 // It jumps to normal execution of the function body.
3714 BuildMI(checkMBB, DL, TII.get(X86::JCC_1))
3715 .addMBB(&PrologueMBB)
3717
3718 // On 32 bit we first push the arguments size and then the frame size. On 64
3719 // bit, we pass the stack frame size in r10 and the argument size in r11.
3720 if (Is64Bit) {
3721 // Functions with nested arguments use R10, so it needs to be saved across
3722 // the call to _morestack
3723
3724 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
3725 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
3726 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
3727 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
3728
3729 if (IsNested)
3730 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
3731
3732 BuildMI(allocMBB, DL, TII.get(X86::getMOVriOpcode(IsLP64, StackSize)),
3733 Reg10)
3734 .addImm(StackSize);
3735 BuildMI(allocMBB, DL,
3737 Reg11)
3738 .addImm(X86FI->getArgumentStackSize());
3739 } else {
3740 BuildMI(allocMBB, DL, TII.get(X86::PUSH32i))
3741 .addImm(X86FI->getArgumentStackSize());
3742 BuildMI(allocMBB, DL, TII.get(X86::PUSH32i)).addImm(StackSize);
3743 }
3744
3745 // __morestack is in libgcc
3747 // Under the large code model, we cannot assume that __morestack lives
3748 // within 2^31 bytes of the call site, so we cannot use pc-relative
3749 // addressing. We cannot perform the call via a temporary register,
3750 // as the rax register may be used to store the static chain, and all
3751 // other suitable registers may be either callee-save or used for
3752 // parameter passing. We cannot use the stack at this point either
3753 // because __morestack manipulates the stack directly.
3754 //
3755 // To avoid these issues, perform an indirect call via a read-only memory
3756 // location containing the address.
3757 //
3758 // This solution is not perfect, as it assumes that the .rodata section
3759 // is laid out within 2^31 bytes of each function body, but this seems
3760 // to be sufficient for JIT.
3761 // FIXME: Add retpoline support and remove the error here..
3762 if (STI.useIndirectThunkCalls())
3763 report_fatal_error("Emitting morestack calls on 64-bit with the large "
3764 "code model and thunks not yet implemented.");
3765 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
3766 .addReg(X86::RIP)
3767 .addImm(0)
3768 .addReg(0)
3769 .addExternalSymbol("__morestack_addr")
3770 .addReg(0);
3771 } else {
3772 if (Is64Bit)
3773 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
3774 .addExternalSymbol("__morestack");
3775 else
3776 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
3777 .addExternalSymbol("__morestack");
3778 }
3779
3780 if (IsNested)
3781 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
3782 else
3783 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
3784
3785 allocMBB->addSuccessor(&PrologueMBB);
3786
3787 checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
3788 checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
3789
3790#ifdef EXPENSIVE_CHECKS
3791 MF.verify();
3792#endif
3793}
3794
3795/// Lookup an ERTS parameter in the !hipe.literals named metadata node.
3796/// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
3797/// to fields it needs, through a named metadata node "hipe.literals" containing
3798/// name-value pairs.
3799static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD,
3800 const StringRef LiteralName) {
3801 for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
3802 MDNode *Node = HiPELiteralsMD->getOperand(i);
3803 if (Node->getNumOperands() != 2)
3804 continue;
3805 MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
3806 ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
3807 if (!NodeName || !NodeVal)
3808 continue;
3809 ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
3810 if (ValConst && NodeName->getString() == LiteralName) {
3811 return ValConst->getZExtValue();
3812 }
3813 }
3814
3815 report_fatal_error("HiPE literal " + LiteralName +
3816 " required but not provided");
3817}
3818
3819// Return true if there are no non-ehpad successors to MBB and there are no
3820// non-meta instructions between MBBI and MBB.end().
3823 return llvm::all_of(
3824 MBB.successors(),
3825 [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
3826 std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
3827 return MI.isMetaInstruction();
3828 });
3829}
3830
3831/// Erlang programs may need a special prologue to handle the stack size they
3832/// might need at runtime. That is because Erlang/OTP does not implement a C
3833/// stack but uses a custom implementation of hybrid stack/heap architecture.
3834/// (for more information see Eric Stenman's Ph.D. thesis:
3835/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
3836///
3837/// CheckStack:
3838/// temp0 = sp - MaxStack
3839/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3840/// OldStart:
3841/// ...
3842/// IncStack:
3843/// call inc_stack # doubles the stack space
3844/// temp0 = sp - MaxStack
3845/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3847 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3848 MachineFrameInfo &MFI = MF.getFrameInfo();
3849 DebugLoc DL;
3850
3851 // To support shrink-wrapping we would need to insert the new blocks
3852 // at the right place and update the branches to PrologueMBB.
3853 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3854
3855 // HiPE-specific values
3856 NamedMDNode *HiPELiteralsMD =
3857 MF.getFunction().getParent()->getNamedMetadata("hipe.literals");
3858 if (!HiPELiteralsMD)
3860 "Can't generate HiPE prologue without runtime parameters");
3861 const unsigned HipeLeafWords = getHiPELiteral(
3862 HiPELiteralsMD, Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
3863 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
3864 const unsigned Guaranteed = HipeLeafWords * SlotSize;
3865 unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs
3866 ? MF.getFunction().arg_size() - CCRegisteredArgs
3867 : 0;
3868 unsigned MaxStack = MFI.getStackSize() + CallerStkArity * SlotSize + SlotSize;
3869
3870 assert(STI.isTargetLinux() &&
3871 "HiPE prologue is only supported on Linux operating systems.");
3872
3873 // Compute the largest caller's frame that is needed to fit the callees'
3874 // frames. This 'MaxStack' is computed from:
3875 //
3876 // a) the fixed frame size, which is the space needed for all spilled temps,
3877 // b) outgoing on-stack parameter areas, and
3878 // c) the minimum stack space this function needs to make available for the
3879 // functions it calls (a tunable ABI property).
3880 if (MFI.hasCalls()) {
3881 unsigned MoreStackForCalls = 0;
3882
3883 for (auto &MBB : MF) {
3884 for (auto &MI : MBB) {
3885 if (!MI.isCall())
3886 continue;
3887
3888 // Get callee operand.
3889 const MachineOperand &MO = MI.getOperand(0);
3890
3891 // Only take account of global function calls (no closures etc.).
3892 if (!MO.isGlobal())
3893 continue;
3894
3895 const Function *F = dyn_cast<Function>(MO.getGlobal());
3896 if (!F)
3897 continue;
3898
3899 // Do not update 'MaxStack' for primitive and built-in functions
3900 // (encoded with names either starting with "erlang."/"bif_" or not
3901 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
3902 // "_", such as the BIF "suspend_0") as they are executed on another
3903 // stack.
3904 if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
3905 F->getName().find_first_of("._") == StringRef::npos)
3906 continue;
3907
3908 unsigned CalleeStkArity = F->arg_size() > CCRegisteredArgs
3909 ? F->arg_size() - CCRegisteredArgs
3910 : 0;
3911 if (HipeLeafWords - 1 > CalleeStkArity)
3912 MoreStackForCalls =
3913 std::max(MoreStackForCalls,
3914 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
3915 }
3916 }
3917 MaxStack += MoreStackForCalls;
3918 }
3919
3920 // If the stack frame needed is larger than the guaranteed then runtime checks
3921 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
3922 if (MaxStack > Guaranteed) {
3923 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
3924 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
3925
3926 for (const auto &LI : PrologueMBB.liveins()) {
3927 stackCheckMBB->addLiveIn(LI);
3928 incStackMBB->addLiveIn(LI);
3929 }
3930
3931 MF.push_front(incStackMBB);
3932 MF.push_front(stackCheckMBB);
3933
3934 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
3935 unsigned LEAop, CMPop, CALLop;
3936 SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
3937 if (Is64Bit) {
3938 SPReg = X86::RSP;
3939 PReg = X86::RBP;
3940 LEAop = X86::LEA64r;
3941 CMPop = X86::CMP64rm;
3942 CALLop = X86::CALL64pcrel32;
3943 } else {
3944 SPReg = X86::ESP;
3945 PReg = X86::EBP;
3946 LEAop = X86::LEA32r;
3947 CMPop = X86::CMP32rm;
3948 CALLop = X86::CALLpcrel32;
3949 }
3950
3951 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
3952 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3953 "HiPE prologue scratch register is live-in");
3954
3955 // Create new MBB for StackCheck:
3956 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
3957 false, -MaxStack);
3958 // SPLimitOffset is in a fixed heap location (pointed by BP).
3959 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
3960 PReg, false, SPLimitOffset);
3961 BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1))
3962 .addMBB(&PrologueMBB)
3964
3965 // Create new MBB for IncStack:
3966 BuildMI(incStackMBB, DL, TII.get(CALLop)).addExternalSymbol("inc_stack_0");
3967 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
3968 false, -MaxStack);
3969 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
3970 PReg, false, SPLimitOffset);
3971 BuildMI(incStackMBB, DL, TII.get(X86::JCC_1))
3972 .addMBB(incStackMBB)
3974
3975 stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
3976 stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
3977 incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
3978 incStackMBB->addSuccessor(incStackMBB, {1, 100});
3979 }
3980#ifdef EXPENSIVE_CHECKS
3981 MF.verify();
3982#endif
3983}
3984
3985bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
3987 const DebugLoc &DL,
3988 int Offset) const {
3989 if (Offset <= 0)
3990 return false;
3991
3992 if (Offset % SlotSize)
3993 return false;
3994
3995 int NumPops = Offset / SlotSize;
3996 // This is only worth it if we have at most 2 pops.
3997 if (NumPops != 1 && NumPops != 2)
3998 return false;
3999
4000 // Handle only the trivial case where the adjustment directly follows
4001 // a call. This is the most common one, anyway.
4002 if (MBBI == MBB.begin())
4003 return false;
4004 MachineBasicBlock::iterator Prev = std::prev(MBBI);
4005 if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
4006 return false;
4007
4008 unsigned Regs[2];
4009 unsigned FoundRegs = 0;
4010
4011 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4012 const MachineOperand &RegMask = Prev->getOperand(1);
4013
4014 auto &RegClass =
4015 Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
4016 // Try to find up to NumPops free registers.
4017 for (auto Candidate : RegClass) {
4018 // Poor man's liveness:
4019 // Since we're immediately after a call, any register that is clobbered
4020 // by the call and not defined by it can be considered dead.
4021 if (!RegMask.clobbersPhysReg(Candidate))
4022 continue;
4023
4024 // Don't clobber reserved registers
4025 if (MRI.isReserved(Candidate))
4026 continue;
4027
4028 bool IsDef = false;
4029 for (const MachineOperand &MO : Prev->implicit_operands()) {
4030 if (MO.isReg() && MO.isDef() &&
4031 TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
4032 IsDef = true;
4033 break;
4034 }
4035 }
4036
4037 if (IsDef)
4038 continue;
4039
4040 Regs[FoundRegs++] = Candidate;
4041 if (FoundRegs == (unsigned)NumPops)
4042 break;
4043 }
4044
4045 if (FoundRegs == 0)
4046 return false;
4047
4048 // If we found only one free register, but need two, reuse the same one twice.
4049 while (FoundRegs < (unsigned)NumPops)
4050 Regs[FoundRegs++] = Regs[0];
4051
4052 for (int i = 0; i < NumPops; ++i)
4053 BuildMI(MBB, MBBI, DL, TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r),
4054 Regs[i]);
4055
4056 return true;
4057}
4058
4062 bool reserveCallFrame = hasReservedCallFrame(MF);
4063 unsigned Opcode = I->getOpcode();
4064 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
4065 DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
4066 uint64_t Amount = TII.getFrameSize(*I);
4067 uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
4068 I = MBB.erase(I);
4069 auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
4070
4071 // Try to avoid emitting dead SP adjustments if the block end is unreachable,
4072 // typically because the function is marked noreturn (abort, throw,
4073 // assert_fail, etc).
4074 if (isDestroy && blockEndIsUnreachable(MBB, I))
4075 return I;
4076
4077 if (!reserveCallFrame) {
4078 // If the stack pointer can be changed after prologue, turn the
4079 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
4080 // adjcallstackdown instruction into 'add ESP, <amt>'
4081
4082 // We need to keep the stack aligned properly. To do this, we round the
4083 // amount of space needed for the outgoing arguments up to the next
4084 // alignment boundary.
4085 Amount = alignTo(Amount, getStackAlign());
4086
4087 const Function &F = MF.getFunction();
4088 bool WindowsCFI = MF.usesWindowsUnwindInfo();
4089 bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
4090
4091 // If we have any exception handlers in this function, and we adjust
4092 // the SP before calls, we may need to indicate this to the unwinder
4093 // using GNU_ARGS_SIZE. Note that this may be necessary even when
4094 // Amount == 0, because the preceding function may have set a non-0
4095 // GNU_ARGS_SIZE.
4096 // TODO: We don't need to reset this between subsequent functions,
4097 // if it didn't change.
4098 bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
4099
4100 if (HasDwarfEHHandlers && !isDestroy &&
4102 BuildCFI(MBB, InsertPos, DL,
4103 MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
4104
4105 if (Amount == 0)
4106 return I;
4107
4108 // Factor out the amount that gets handled inside the sequence
4109 // (Pushes of argument for frame setup, callee pops for frame destroy)
4110 Amount -= InternalAmt;
4111
4112 // TODO: This is needed only if we require precise CFA.
4113 // If this is a callee-pop calling convention, emit a CFA adjust for
4114 // the amount the callee popped.
4115 if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
4116 BuildCFI(MBB, InsertPos, DL,
4117 MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
4118
4119 // Add Amount to SP to destroy a frame, or subtract to setup.
4120 int64_t StackAdjustment = isDestroy ? Amount : -Amount;
4121 int64_t CfaAdjustment = StackAdjustment;
4122
4123 if (StackAdjustment) {
4124 // Merge with any previous or following adjustment instruction. Note: the
4125 // instructions merged with here do not have CFI, so their stack
4126 // adjustments do not feed into CfaAdjustment
4127
4128 auto CalcCfaAdjust = [&CfaAdjustment](MachineBasicBlock::iterator PI,
4129 int64_t Offset) {
4130 CfaAdjustment += Offset;
4131 };
4132 auto CalcNewOffset = [&StackAdjustment](int64_t Offset) {
4133 return StackAdjustment + Offset;
4134 };
4135 StackAdjustment =
4136 mergeSPUpdates(MBB, InsertPos, CalcCfaAdjust, CalcNewOffset, true);
4137 StackAdjustment =
4138 mergeSPUpdates(MBB, InsertPos, CalcCfaAdjust, CalcNewOffset, false);
4139
4140 if (StackAdjustment) {
4141 if (!(F.hasMinSize() &&
4142 adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
4143 BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
4144 /*InEpilogue=*/false);
4145 }
4146 }
4147
4148 if (DwarfCFI && !hasFP(MF) && CfaAdjustment) {
4149 // If we don't have FP, but need to generate unwind information,
4150 // we need to set the correct CFA offset after the stack adjustment.
4151 // How much we adjust the CFA offset depends on whether we're emitting
4152 // CFI only for EH purposes or for debugging. EH only requires the CFA
4153 // offset to be correct at each call site, while for debugging we want
4154 // it to be more precise.
4155
4156 // TODO: When not using precise CFA, we also need to adjust for the
4157 // InternalAmt here.
4158 BuildCFI(
4159 MBB, InsertPos, DL,
4160 MCCFIInstruction::createAdjustCfaOffset(nullptr, -CfaAdjustment));
4161 }
4162
4163 return I;
4164 }
4165
4166 if (InternalAmt) {
4169 while (CI != B && !std::prev(CI)->isCall())
4170 --CI;
4171 BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
4172 }
4173
4174 return I;
4175}
4176
4178 assert(MBB.getParent() && "Block is not attached to a function!");
4179 const MachineFunction &MF = *MBB.getParent();
4180 if (!MBB.isLiveIn(X86::EFLAGS))
4181 return true;
4182
4183 // If stack probes have to loop inline or call, that will clobber EFLAGS.
4184 // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
4186 const X86TargetLowering &TLI = *STI.getTargetLowering();
4187 if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
4188 return false;
4189
4191 return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
4192}
4193
4195 assert(MBB.getParent() && "Block is not attached to a function!");
4196
4197 // Win64 has strict requirements in terms of epilogue and we are
4198 // not taking a chance at messing with them.
4199 // I.e., unless this block is already an exit block, we can't use
4200 // it as an epilogue.
4201 if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
4202 return false;
4203
4204 // Swift async context epilogue has a BTR instruction that clobbers parts of
4205 // EFLAGS.
4206 const MachineFunction &MF = *MBB.getParent();
4209
4210 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
4211 return true;
4212
4213 // If we cannot use LEA to adjust SP, we may need to use ADD, which
4214 // clobbers the EFLAGS. Check that we do not need to preserve it,
4215 // otherwise, conservatively assume this is not
4216 // safe to insert the epilogue here.
4218}
4219
4221 // If we may need to emit frameless compact unwind information, give
4222 // up as this is currently broken: PR25614.
4223 bool CompactUnwind =
4225 return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
4226 !CompactUnwind) &&
4227 // The lowering of segmented stack and HiPE only support entry
4228 // blocks as prologue blocks: PR26107. This limitation may be
4229 // lifted if we fix:
4230 // - adjustForSegmentedStacks
4231 // - adjustForHiPEPrologue
4233 !MF.shouldSplitStack();
4234}
4235
4238 const DebugLoc &DL, bool RestoreSP) const {
4239 assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
4240 assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
4241 assert(STI.is32Bit() && !Uses64BitFramePtr &&
4242 "restoring EBP/ESI on non-32-bit target");
4243
4244 MachineFunction &MF = *MBB.getParent();
4245 Register FramePtr = TRI->getFrameRegister(MF);
4246 Register BasePtr = TRI->getBaseRegister();
4247 WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
4249 MachineFrameInfo &MFI = MF.getFrameInfo();
4250
4251 // FIXME: Don't set FrameSetup flag in catchret case.
4252
4253 int FI = FuncInfo.EHRegNodeFrameIndex;
4254 int EHRegSize = MFI.getObjectSize(FI);
4255
4256 if (RestoreSP) {
4257 // MOV32rm -EHRegSize(%ebp), %esp
4258 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
4259 X86::EBP, true, -EHRegSize)
4261 }
4262
4263 Register UsedReg;
4264 int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
4265 int EndOffset = -EHRegOffset - EHRegSize;
4266 FuncInfo.EHRegNodeEndOffset = EndOffset;
4267
4268 if (UsedReg == FramePtr) {
4269 // ADD $offset, %ebp
4270 unsigned ADDri = getADDriOpcode(false);
4271 BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
4273 .addImm(EndOffset)
4275 ->getOperand(3)
4276 .setIsDead();
4277 assert(EndOffset >= 0 &&
4278 "end of registration object above normal EBP position!");
4279 } else if (UsedReg == BasePtr) {
4280 // LEA offset(%ebp), %esi
4281 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
4282 FramePtr, false, EndOffset)
4284 // MOV32rm SavedEBPOffset(%esi), %ebp
4285 assert(X86FI->getHasSEHFramePtrSave());
4286 int Offset =
4287 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
4288 .getFixed();
4289 assert(UsedReg == BasePtr);
4290 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
4291 UsedReg, true, Offset)
4293 } else {
4294 llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
4295 }
4296 return MBBI;
4297}
4298
4300 return TRI->getSlotSize();
4301}
4302
4307
4311 Register FrameRegister = RI->getFrameRegister(MF);
4312 if (getInitialCFARegister(MF) == FrameRegister &&
4314 DwarfFrameBase FrameBase;
4315 FrameBase.Kind = DwarfFrameBase::CFA;
4316 FrameBase.Location.Offset =
4318 return FrameBase;
4319 }
4320
4321 return DwarfFrameBase{DwarfFrameBase::Register, {FrameRegister}};
4322}
4323
4324namespace {
4325// Struct used by orderFrameObjects to help sort the stack objects.
4326struct X86FrameSortingObject {
4327 bool IsValid = false; // true if we care about this Object.
4328 unsigned ObjectIndex = 0; // Index of Object into MFI list.
4329 unsigned ObjectSize = 0; // Size of Object in bytes.
4330 Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
4331 unsigned ObjectNumUses = 0; // Object static number of uses.
4332};
4333
4334// The comparison function we use for std::sort to order our local
4335// stack symbols. The current algorithm is to use an estimated
4336// "density". This takes into consideration the size and number of
4337// uses each object has in order to roughly minimize code size.
4338// So, for example, an object of size 16B that is referenced 5 times
4339// will get higher priority than 4 4B objects referenced 1 time each.
4340// It's not perfect and we may be able to squeeze a few more bytes out of
4341// it (for example : 0(esp) requires fewer bytes, symbols allocated at the
4342// fringe end can have special consideration, given their size is less
4343// important, etc.), but the algorithmic complexity grows too much to be
4344// worth the extra gains we get. This gets us pretty close.
4345// The final order leaves us with objects with highest priority going
4346// at the end of our list.
4347struct X86FrameSortingComparator {
4348 inline bool operator()(const X86FrameSortingObject &A,
4349 const X86FrameSortingObject &B) const {
4350 uint64_t DensityAScaled, DensityBScaled;
4351
4352 // For consistency in our comparison, all invalid objects are placed
4353 // at the end. This also allows us to stop walking when we hit the
4354 // first invalid item after it's all sorted.
4355 if (!A.IsValid)
4356 return false;
4357 if (!B.IsValid)
4358 return true;
4359
4360 // The density is calculated by doing :
4361 // (double)DensityA = A.ObjectNumUses / A.ObjectSize
4362 // (double)DensityB = B.ObjectNumUses / B.ObjectSize
4363 // Since this approach may cause inconsistencies in
4364 // the floating point <, >, == comparisons, depending on the floating
4365 // point model with which the compiler was built, we're going
4366 // to scale both sides by multiplying with
4367 // A.ObjectSize * B.ObjectSize. This ends up factoring away
4368 // the division and, with it, the need for any floating point
4369 // arithmetic.
4370 DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
4371 static_cast<uint64_t>(B.ObjectSize);
4372 DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
4373 static_cast<uint64_t>(A.ObjectSize);
4374
4375 // If the two densities are equal, prioritize highest alignment
4376 // objects. This allows for similar alignment objects
4377 // to be packed together (given the same density).
4378 // There's room for improvement here, also, since we can pack
4379 // similar alignment (different density) objects next to each
4380 // other to save padding. This will also require further
4381 // complexity/iterations, and the overall gain isn't worth it,
4382 // in general. Something to keep in mind, though.
4383 if (DensityAScaled == DensityBScaled)
4384 return A.ObjectAlignment < B.ObjectAlignment;
4385
4386 return DensityAScaled < DensityBScaled;
4387 }
4388};
4389} // namespace
4390
4391// Order the symbols in the local stack.
4392// We want to place the local stack objects in some sort of sensible order.
4393// The heuristic we use is to try and pack them according to static number
4394// of uses and size of object in order to minimize code size.
4396 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
4397 const MachineFrameInfo &MFI = MF.getFrameInfo();
4398
4399 // Don't waste time if there's nothing to do.
4400 if (ObjectsToAllocate.empty())
4401 return;
4402
4403 // Create an array of all MFI objects. We won't need all of these
4404 // objects, but we're going to create a full array of them to make
4405 // it easier to index into when we're counting "uses" down below.
4406 // We want to be able to easily/cheaply access an object by simply
4407 // indexing into it, instead of having to search for it every time.
4408 std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
4409
4410 // Walk the objects we care about and mark them as such in our working
4411 // struct.
4412 for (auto &Obj : ObjectsToAllocate) {
4413 SortingObjects[Obj].IsValid = true;
4414 SortingObjects[Obj].ObjectIndex = Obj;
4415 SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
4416 // Set the size.
4417 int ObjectSize = MFI.getObjectSize(Obj);
4418 if (ObjectSize == 0)
4419 // Variable size. Just use 4.
4420 SortingObjects[Obj].ObjectSize = 4;
4421 else
4422 SortingObjects[Obj].ObjectSize = ObjectSize;
4423 }
4424
4425 // Count the number of uses for each object.
4426 for (auto &MBB : MF) {
4427 for (auto &MI : MBB) {
4428 if (MI.isDebugInstr())
4429 continue;
4430 for (const MachineOperand &MO : MI.operands()) {
4431 // Check to see if it's a local stack symbol.
4432 if (!MO.isFI())
4433 continue;
4434 int Index = MO.getIndex();
4435 // Check to see if it falls within our range, and is tagged
4436 // to require ordering.
4437 if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
4438 SortingObjects[Index].IsValid)
4439 SortingObjects[Index].ObjectNumUses++;
4440 }
4441 }
4442 }
4443
4444 // Sort the objects using X86FrameSortingAlgorithm (see its comment for
4445 // info).
4446 llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
4447
4448 // Now modify the original list to represent the final order that
4449 // we want. The order will depend on whether we're going to access them
4450 // from the stack pointer or the frame pointer. For SP, the list should
4451 // end up with the END containing objects that we want with smaller offsets.
4452 // For FP, it should be flipped.
4453 int i = 0;
4454 for (auto &Obj : SortingObjects) {
4455 // All invalid items are sorted at the end, so it's safe to stop.
4456 if (!Obj.IsValid)
4457 break;
4458 ObjectsToAllocate[i++] = Obj.ObjectIndex;
4459 }
4460
4461 // Flip it if we're accessing off of the FP.
4462 if (!TRI->hasStackRealignment(MF) && hasFP(MF))
4463 std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
4464}
4465
4466unsigned
4468 // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
4469 unsigned Offset = 16;
4470 // RBP is immediately pushed.
4471 Offset += SlotSize;
4472 // All callee-saved registers are then pushed.
4473 Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
4474 // Every funclet allocates enough stack space for the largest outgoing call.
4475 Offset += getWinEHFuncletFrameSize(MF);
4476 return Offset;
4477}
4478
4480 MachineFunction &MF, RegScavenger *RS) const {
4481 // Mark the function as not having WinCFI. We will set it back to true in
4482 // emitPrologue if it gets called and emits CFI.
4483 MF.setHasWinCFI(false);
4484
4485 MachineFrameInfo &MFI = MF.getFrameInfo();
4486 // If the frame is big enough that we might need to scavenge a register to
4487 // handle huge offsets, reserve a stack slot for that now.
4488 if (!isInt<32>(MFI.estimateStackSize(MF))) {
4489 int FI = MFI.CreateStackObject(SlotSize, Align(SlotSize), false);
4490 RS->addScavengingFrameIndex(FI);
4491 }
4492
4493 // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
4494 // aligned. The format doesn't support misaligned stack adjustments.
4495 if (MF.usesWindowsUnwindInfo())
4497
4498 // If this function isn't doing Win64-style C++ EH, we don't need to do
4499 // anything.
4500 if (STI.is64Bit() && MF.hasEHFunclets() &&
4503 adjustFrameForMsvcCxxEh(MF);
4504 }
4505}
4506
4507void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
4508 // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
4509 // relative to RSP after the prologue. Find the offset of the last fixed
4510 // object, so that we can allocate a slot immediately following it. If there
4511 // were no fixed objects, use offset -SlotSize, which is immediately after the
4512 // return address. Fixed objects have negative frame indices.
4513 MachineFrameInfo &MFI = MF.getFrameInfo();
4514 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
4515 int64_t MinFixedObjOffset = -SlotSize;
4516 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
4517 MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
4518
4519 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
4520 for (WinEHHandlerType &H : TBME.HandlerArray) {
4521 int FrameIndex = H.CatchObj.FrameIndex;
4522 if ((FrameIndex != INT_MAX) && MFI.getObjectOffset(FrameIndex) == 0) {
4523 // Ensure alignment.
4524 unsigned Align = MFI.getObjectAlign(FrameIndex).value();
4525 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
4526 MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
4527 MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
4528 }
4529 }
4530 }
4531
4532 // Ensure alignment.
4533 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
4534 int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
4535 int UnwindHelpFI =
4536 MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
4537 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
4538
4539 // Store -2 into UnwindHelp on function entry. We have to scan forwards past
4540 // other frame setup instructions.
4541 MachineBasicBlock &MBB = MF.front();
4542 auto MBBI = MBB.begin();
4543 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
4544 ++MBBI;
4545
4547 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
4548 UnwindHelpFI)
4549 .addImm(-2);
4550}
4551
4553 MachineFunction &MF, RegScavenger *RS) const {
4554 auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4555
4556 if (STI.is32Bit() && MF.hasEHFunclets())
4558 // We have emitted prolog and epilog. Don't need stack pointer saving
4559 // instruction any more.
4560 if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) {
4561 MI->eraseFromParent();
4562 X86FI->setStackPtrSaveMI(nullptr);
4563 }
4564}
4565
4567 MachineFunction &MF) const {
4568 // 32-bit functions have to restore stack pointers when control is transferred
4569 // back to the parent function. These blocks are identified as eh pads that
4570 // are not funclet entries.
4571 bool IsSEH = isAsynchronousEHPersonality(
4573 for (MachineBasicBlock &MBB : MF) {
4574 bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
4575 if (NeedsRestore)
4577 /*RestoreSP=*/IsSEH);
4578 }
4579}
4580
4581// Compute the alignment gap between current SP after spilling FP/BP and the
4582// next properly aligned stack offset.
4584 const TargetRegisterClass *RC,
4585 unsigned NumSpilledRegs) {
4587 unsigned AllocSize = TRI->getSpillSize(*RC) * NumSpilledRegs;
4588 Align StackAlign = MF.getSubtarget().getFrameLowering()->getStackAlign();
4589 unsigned AlignedSize = alignTo(AllocSize, StackAlign);
4590 return AlignedSize - AllocSize;
4591}
4592
4593void X86FrameLowering::spillFPBPUsingSP(MachineFunction &MF,
4595 Register FP, Register BP,
4596 int SPAdjust) const {
4597 assert(FP.isValid() || BP.isValid());
4598
4599 MachineBasicBlock *MBB = BeforeMI->getParent();
4600 DebugLoc DL = BeforeMI->getDebugLoc();
4601
4602 // Spill FP.
4603 if (FP.isValid()) {
4604 BuildMI(*MBB, BeforeMI, DL,
4605 TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>())))
4606 .addReg(FP);
4607 }
4608
4609 // Spill BP.
4610 if (BP.isValid()) {
4611 BuildMI(*MBB, BeforeMI, DL,
4612 TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>())))
4613 .addReg(BP);
4614 }
4615
4616 // Make sure SP is aligned.
4617 if (SPAdjust)
4618 emitSPUpdate(*MBB, BeforeMI, DL, -SPAdjust, false);
4619
4620 // Emit unwinding information.
4621 if (FP.isValid() && needsDwarfCFI(MF)) {
4622 // Emit .cfi_remember_state to remember old frame.
4623 unsigned CFIIndex =
4625 BuildMI(*MBB, BeforeMI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
4626 .addCFIIndex(CFIIndex);
4627
4628 // Setup new CFA value with DW_CFA_def_cfa_expression:
4629 // DW_OP_breg7+offset, DW_OP_deref, DW_OP_consts 16, DW_OP_plus
4630 SmallString<64> CfaExpr;
4631 uint8_t buffer[16];
4632 int Offset = SPAdjust;
4633 if (BP.isValid())
4634 Offset += TRI->getSpillSize(*TRI->getMinimalPhysRegClass(BP));
4635 // If BeforeMI is a frame setup instruction, we need to adjust the position
4636 // and offset of the new cfi instruction.
4637 if (TII.isFrameSetup(*BeforeMI)) {
4638 Offset += alignTo(TII.getFrameSize(*BeforeMI), getStackAlign());
4639 BeforeMI = std::next(BeforeMI);
4640 }
4641 Register StackPtr = TRI->getStackRegister();
4642 if (STI.isTarget64BitILP32())
4644 unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackPtr, true);
4645 CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfStackPtr));
4646 CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
4647 CfaExpr.push_back(dwarf::DW_OP_deref);
4648 CfaExpr.push_back(dwarf::DW_OP_consts);
4649 CfaExpr.append(buffer, buffer + encodeSLEB128(SlotSize * 2, buffer));
4650 CfaExpr.push_back((uint8_t)dwarf::DW_OP_plus);
4651
4652 SmallString<64> DefCfaExpr;
4653 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
4654 DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer));
4655 DefCfaExpr.append(CfaExpr.str());
4656 BuildCFI(*MBB, BeforeMI, DL,
4657 MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()),
4659 }
4660}
4661
4662void X86FrameLowering::restoreFPBPUsingSP(MachineFunction &MF,
4664 Register FP, Register BP,
4665 int SPAdjust) const {
4666 assert(FP.isValid() || BP.isValid());
4667
4668 // Adjust SP so it points to spilled FP or BP.
4669 MachineBasicBlock *MBB = AfterMI->getParent();
4670 MachineBasicBlock::iterator Pos = std::next(AfterMI);
4671 DebugLoc DL = AfterMI->getDebugLoc();
4672 if (SPAdjust)
4673 emitSPUpdate(*MBB, Pos, DL, SPAdjust, false);
4674
4675 // Restore BP.
4676 if (BP.isValid()) {
4677 BuildMI(*MBB, Pos, DL,
4678 TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())), BP);
4679 }
4680
4681 // Restore FP.
4682 if (FP.isValid()) {
4683 BuildMI(*MBB, Pos, DL,
4684 TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())), FP);
4685
4686 // Emit unwinding information.
4687 if (needsDwarfCFI(MF)) {
4688 // Restore original frame with .cfi_restore_state.
4689 unsigned CFIIndex =
4691 BuildMI(*MBB, Pos, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
4692 .addCFIIndex(CFIIndex);
4693 }
4694 }
4695}
4696
4697void X86FrameLowering::saveAndRestoreFPBPUsingSP(
4699 MachineBasicBlock::iterator AfterMI, bool SpillFP, bool SpillBP) const {
4700 assert(SpillFP || SpillBP);
4701
4702 Register FP, BP;
4703 const TargetRegisterClass *RC;
4704 unsigned NumRegs = 0;
4705
4706 if (SpillFP) {
4707 FP = TRI->getFrameRegister(MF);
4708 if (STI.isTarget64BitILP32())
4710 RC = TRI->getMinimalPhysRegClass(FP);
4711 ++NumRegs;
4712 }
4713 if (SpillBP) {
4714 BP = TRI->getBaseRegister();
4715 if (STI.isTarget64BitILP32())
4716 BP = Register(getX86SubSuperRegister(BP, 64));
4717 RC = TRI->getMinimalPhysRegClass(BP);
4718 ++NumRegs;
4719 }
4720 int SPAdjust = computeFPBPAlignmentGap(MF, RC, NumRegs);
4721
4722 spillFPBPUsingSP(MF, BeforeMI, FP, BP, SPAdjust);
4723 restoreFPBPUsingSP(MF, AfterMI, FP, BP, SPAdjust);
4724}
4725
4726bool X86FrameLowering::skipSpillFPBP(
4728 if (MI->getOpcode() == X86::LCMPXCHG16B_SAVE_RBX) {
4729 // The pseudo instruction LCMPXCHG16B_SAVE_RBX is generated in the form
4730 // SaveRbx = COPY RBX
4731 // SaveRbx = LCMPXCHG16B_SAVE_RBX ..., SaveRbx, implicit-def rbx
4732 // And later LCMPXCHG16B_SAVE_RBX is expanded to restore RBX from SaveRbx.
4733 // We should skip this instruction sequence.
4734 int FI;
4735 Register Reg;
4736 while (!(MI->getOpcode() == TargetOpcode::COPY &&
4737 MI->getOperand(1).getReg() == X86::RBX) &&
4738 !((Reg = TII.isStoreToStackSlot(*MI, FI)) && Reg == X86::RBX))
4739 ++MI;
4740 return true;
4741 }
4742 return false;
4743}
4744
4746 const TargetRegisterInfo *TRI, bool &AccessFP,
4747 bool &AccessBP) {
4748 AccessFP = AccessBP = false;
4749 if (FP) {
4750 if (MI.findRegisterUseOperandIdx(FP, TRI, false) != -1 ||
4751 MI.findRegisterDefOperandIdx(FP, TRI, false, true) != -1)
4752 AccessFP = true;
4753 }
4754 if (BP) {
4755 if (MI.findRegisterUseOperandIdx(BP, TRI, false) != -1 ||
4756 MI.findRegisterDefOperandIdx(BP, TRI, false, true) != -1)
4757 AccessBP = true;
4758 }
4759 return AccessFP || AccessBP;
4760}
4761
4762// Invoke instruction has been lowered to normal function call. We try to figure
4763// out if MI comes from Invoke.
4764// Do we have any better method?
4765static bool isInvoke(const MachineInstr &MI, bool InsideEHLabels) {
4766 if (!MI.isCall())
4767 return false;
4768 if (InsideEHLabels)
4769 return true;
4770
4771 const MachineBasicBlock *MBB = MI.getParent();
4772 if (!MBB->hasEHPadSuccessor())
4773 return false;
4774
4775 // Check if there is another call instruction from MI to the end of MBB.
4777 for (++MBBI; MBBI != ME; ++MBBI)
4778 if (MBBI->isCall())
4779 return false;
4780 return true;
4781}
4782
4783/// Given the live range of FP or BP (DefMI, KillMI), check if there is any
4784/// interfered stack access in the range, usually generated by register spill.
4785void X86FrameLowering::checkInterferedAccess(
4787 MachineBasicBlock::reverse_iterator KillMI, bool SpillFP,
4788 bool SpillBP) const {
4789 if (DefMI == KillMI)
4790 return;
4791 if (TRI->hasBasePointer(MF)) {
4792 if (!SpillBP)
4793 return;
4794 } else {
4795 if (!SpillFP)
4796 return;
4797 }
4798
4799 auto MI = KillMI;
4800 while (MI != DefMI) {
4801 if (any_of(MI->operands(),
4802 [](const MachineOperand &MO) { return MO.isFI(); }))
4803 MF.getContext().reportError(SMLoc(),
4804 "Interference usage of base pointer/frame "
4805 "pointer.");
4806 MI++;
4807 }
4808}
4809
4810/// If a function uses base pointer and the base pointer is clobbered by inline
4811/// asm, RA doesn't detect this case, and after the inline asm, the base pointer
4812/// contains garbage value.
4813/// For example if a 32b x86 function uses base pointer esi, and esi is
4814/// clobbered by following inline asm
4815/// asm("rep movsb" : "+D"(ptr), "+S"(x), "+c"(c)::"memory");
4816/// We need to save esi before the asm and restore it after the asm.
4817///
4818/// The problem can also occur to frame pointer if there is a function call, and
4819/// the callee uses a different calling convention and clobbers the fp.
4820///
4821/// Because normal frame objects (spill slots) are accessed through fp/bp
4822/// register, so we can't spill fp/bp to normal spill slots.
4823///
4824/// FIXME: There are 2 possible enhancements:
4825/// 1. In many cases there are different physical registers not clobbered by
4826/// inline asm, we can use one of them as base pointer. Or use a virtual
4827/// register as base pointer and let RA allocate a physical register to it.
4828/// 2. If there is no other instructions access stack with fp/bp from the
4829/// inline asm to the epilog, and no cfi requirement for a correct fp, we can
4830/// skip the save and restore operations.
4832 Register FP, BP;
4834 if (TFI.hasFP(MF))
4835 FP = TRI->getFrameRegister(MF);
4836 if (TRI->hasBasePointer(MF))
4837 BP = TRI->getBaseRegister();
4838
4839 // Currently only inline asm and function call can clobbers fp/bp. So we can
4840 // do some quick test and return early.
4841 if (!MF.hasInlineAsm()) {
4843 if (!X86FI->getFPClobberedByCall())
4844 FP = 0;
4845 if (!X86FI->getBPClobberedByCall())
4846 BP = 0;
4847 }
4848 if (!FP && !BP)
4849 return;
4850
4851 for (MachineBasicBlock &MBB : MF) {
4852 bool InsideEHLabels = false;
4853 auto MI = MBB.rbegin(), ME = MBB.rend();
4854 auto TermMI = MBB.getFirstTerminator();
4855 if (TermMI == MBB.begin())
4856 continue;
4857 MI = *(std::prev(TermMI));
4858
4859 while (MI != ME) {
4860 // Skip frame setup/destroy instructions.
4861 // Skip Invoke (call inside try block) instructions.
4862 // Skip instructions handled by target.
4863 if (MI->getFlag(MachineInstr::MIFlag::FrameSetup) ||
4865 isInvoke(*MI, InsideEHLabels) || skipSpillFPBP(MF, MI)) {
4866 ++MI;
4867 continue;
4868 }
4869
4870 if (MI->getOpcode() == TargetOpcode::EH_LABEL) {
4871 InsideEHLabels = !InsideEHLabels;
4872 ++MI;
4873 continue;
4874 }
4875
4876 bool AccessFP, AccessBP;
4877 // Check if fp or bp is used in MI.
4878 if (!isFPBPAccess(*MI, FP, BP, TRI, AccessFP, AccessBP)) {
4879 ++MI;
4880 continue;
4881 }
4882
4883 // Look for the range [DefMI, KillMI] in which fp or bp is defined and
4884 // used.
4885 bool FPLive = false, BPLive = false;
4886 bool SpillFP = false, SpillBP = false;
4887 auto DefMI = MI, KillMI = MI;
4888 do {
4889 SpillFP |= AccessFP;
4890 SpillBP |= AccessBP;
4891
4892 // Maintain FPLive and BPLive.
4893 if (FPLive && MI->findRegisterDefOperandIdx(FP, TRI, false, true) != -1)
4894 FPLive = false;
4895 if (FP && MI->findRegisterUseOperandIdx(FP, TRI, false) != -1)
4896 FPLive = true;
4897 if (BPLive && MI->findRegisterDefOperandIdx(BP, TRI, false, true) != -1)
4898 BPLive = false;
4899 if (BP && MI->findRegisterUseOperandIdx(BP, TRI, false) != -1)
4900 BPLive = true;
4901
4902 DefMI = MI++;
4903 } while ((MI != ME) &&
4904 (FPLive || BPLive ||
4905 isFPBPAccess(*MI, FP, BP, TRI, AccessFP, AccessBP)));
4906
4907 // Don't need to save/restore if FP is accessed through llvm.frameaddress.
4908 if (FPLive && !SpillBP)
4909 continue;
4910
4911 // If the bp is clobbered by a call, we should save and restore outside of
4912 // the frame setup instructions.
4913 if (KillMI->isCall() && DefMI != ME) {
4914 auto FrameSetup = std::next(DefMI);
4915 // Look for frame setup instruction toward the start of the BB.
4916 // If we reach another call instruction, it means no frame setup
4917 // instruction for the current call instruction.
4918 while (FrameSetup != ME && !TII.isFrameSetup(*FrameSetup) &&
4919 !FrameSetup->isCall())
4920 ++FrameSetup;
4921 // If a frame setup instruction is found, we need to find out the
4922 // corresponding frame destroy instruction.
4923 if (FrameSetup != ME && TII.isFrameSetup(*FrameSetup) &&
4924 (TII.getFrameSize(*FrameSetup) ||
4925 TII.getFrameAdjustment(*FrameSetup))) {
4926 while (!TII.isFrameInstr(*KillMI))
4927 --KillMI;
4928 DefMI = FrameSetup;
4929 MI = DefMI;
4930 ++MI;
4931 }
4932 }
4933
4934 checkInterferedAccess(MF, DefMI, KillMI, SpillFP, SpillBP);
4935
4936 // Call target function to spill and restore FP and BP registers.
4937 saveAndRestoreFPBPUsingSP(MF, &(*DefMI), &(*KillMI), SpillFP, SpillBP);
4938 }
4939 }
4940}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
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.
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
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
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
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:171
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:409
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:317
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:324
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
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:718
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:890
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:886
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:734
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:635
static MCCFIInstruction createGnuArgsSize(MCSymbol *L, int64_t Size, SMLoc Loc={})
A special wrapper for .cfi_escape that indicates GNU_ARGS_SIZE.
Definition MCDwarf.h:765
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:725
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:628
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:670
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:745
OpType getOperation() const
Definition MCDwarf.h:833
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
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:756
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:651
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:750
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...
virtual int64_t getDwarfRegNum(MCRegister Reg, bool isEH) const
Map a target register to an equivalent dwarf register number.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Metadata node.
Definition Metadata.h:1081
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
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 & 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:301
WinX64EHUnwindMode getWinX64EHUnwindMode() const
Get how unwind information should be generated for x64 Windows.
Definition Module.cpp:1012
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition Module.cpp:617
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:1797
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:112
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
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)
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
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...
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:775
bool isOSWindows() const
Tests whether the OS is Windows.
Definition Triple.h:778
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:471
Value * getValue() const
Definition Metadata.h:510
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
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
@ 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).
@ 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:541
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
static const MachineInstrBuilder & addRegOffset(const MachineInstrBuilder &MIB, Register Reg, bool isKill, int Offset)
addRegOffset - This function is used to add a memory reference of the form [Reg + Offset],...
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.
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