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