xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains the X86 implementation of TargetFrameLowering class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "X86FrameLowering.h"
1481ad6265SDimitry Andric #include "MCTargetDesc/X86MCTargetDesc.h"
150b57cec5SDimitry Andric #include "X86InstrBuilder.h"
160b57cec5SDimitry Andric #include "X86InstrInfo.h"
170b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h"
180b57cec5SDimitry Andric #include "X86Subtarget.h"
190b57cec5SDimitry Andric #include "X86TargetMachine.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
215ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
2381ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
310b57cec5SDimitry Andric #include "llvm/IR/Function.h"
320b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
33e8d8bef9SDimitry Andric #include "llvm/MC/MCObjectFileInfo.h"
340b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
350b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
360b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
370b57cec5SDimitry Andric #include <cstdlib>
380b57cec5SDimitry Andric 
395ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-fl"
405ffd83dbSDimitry Andric 
415ffd83dbSDimitry Andric STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
425ffd83dbSDimitry Andric STATISTIC(NumFrameExtraProbe,
435ffd83dbSDimitry Andric           "Number of extra stack probes generated in prologue");
445ffd83dbSDimitry Andric 
450b57cec5SDimitry Andric using namespace llvm;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
488bcb0991SDimitry Andric                                    MaybeAlign StackAlignOverride)
498bcb0991SDimitry Andric     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
500b57cec5SDimitry Andric                           STI.is64Bit() ? -8 : -4),
510b57cec5SDimitry Andric       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
520b57cec5SDimitry Andric   // Cache a bunch of frame-related predicates for this subtarget.
530b57cec5SDimitry Andric   SlotSize = TRI->getSlotSize();
540b57cec5SDimitry Andric   Is64Bit = STI.is64Bit();
550b57cec5SDimitry Andric   IsLP64 = STI.isTarget64BitLP64();
560b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
570b57cec5SDimitry Andric   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
580b57cec5SDimitry Andric   StackPtr = TRI->getStackRegister();
590b57cec5SDimitry Andric }
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
620b57cec5SDimitry Andric   return !MF.getFrameInfo().hasVarSizedObjects() &&
635ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
645ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
680b57cec5SDimitry Andric /// call frame pseudos can be simplified.  Having a FP, as in the default
690b57cec5SDimitry Andric /// implementation, is not sufficient here since we can't always use it.
700b57cec5SDimitry Andric /// Use a more nuanced condition.
710b57cec5SDimitry Andric bool
720b57cec5SDimitry Andric X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
730b57cec5SDimitry Andric   return hasReservedCallFrame(MF) ||
745ffd83dbSDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
75fe6060f1SDimitry Andric          (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
760b57cec5SDimitry Andric          TRI->hasBasePointer(MF);
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric // needsFrameIndexResolution - Do we need to perform FI resolution for
800b57cec5SDimitry Andric // this function. Normally, this is required only when the function
810b57cec5SDimitry Andric // has any stack objects. However, FI resolution actually has another job,
820b57cec5SDimitry Andric // not apparent from the title - it resolves callframesetup/destroy
830b57cec5SDimitry Andric // that were not simplified earlier.
840b57cec5SDimitry Andric // So, this is required for x86 functions that have push sequences even
850b57cec5SDimitry Andric // when there are no stack objects.
860b57cec5SDimitry Andric bool
870b57cec5SDimitry Andric X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
880b57cec5SDimitry Andric   return MF.getFrameInfo().hasStackObjects() ||
890b57cec5SDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
930b57cec5SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
940b57cec5SDimitry Andric /// or if frame pointer elimination is disabled.
950b57cec5SDimitry Andric bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
960b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
970b57cec5SDimitry Andric   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
98fe6060f1SDimitry Andric           TRI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
990b57cec5SDimitry Andric           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
1000b57cec5SDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
1015ffd83dbSDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
1020b57cec5SDimitry Andric           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
1030b57cec5SDimitry Andric           MFI.hasStackMap() || MFI.hasPatchPoint() ||
104d56accc7SDimitry Andric           (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment()));
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
107480093f4SDimitry Andric static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
1080b57cec5SDimitry Andric   if (IsLP64) {
1090b57cec5SDimitry Andric     if (isInt<8>(Imm))
1100b57cec5SDimitry Andric       return X86::SUB64ri8;
1110b57cec5SDimitry Andric     return X86::SUB64ri32;
1120b57cec5SDimitry Andric   } else {
1130b57cec5SDimitry Andric     if (isInt<8>(Imm))
1140b57cec5SDimitry Andric       return X86::SUB32ri8;
1150b57cec5SDimitry Andric     return X86::SUB32ri;
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
119480093f4SDimitry Andric static unsigned getADDriOpcode(bool IsLP64, int64_t Imm) {
1200b57cec5SDimitry Andric   if (IsLP64) {
1210b57cec5SDimitry Andric     if (isInt<8>(Imm))
1220b57cec5SDimitry Andric       return X86::ADD64ri8;
1230b57cec5SDimitry Andric     return X86::ADD64ri32;
1240b57cec5SDimitry Andric   } else {
1250b57cec5SDimitry Andric     if (isInt<8>(Imm))
1260b57cec5SDimitry Andric       return X86::ADD32ri8;
1270b57cec5SDimitry Andric     return X86::ADD32ri;
1280b57cec5SDimitry Andric   }
1290b57cec5SDimitry Andric }
1300b57cec5SDimitry Andric 
131480093f4SDimitry Andric static unsigned getSUBrrOpcode(bool IsLP64) {
132480093f4SDimitry Andric   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric 
135480093f4SDimitry Andric static unsigned getADDrrOpcode(bool IsLP64) {
136480093f4SDimitry Andric   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
1400b57cec5SDimitry Andric   if (IsLP64) {
1410b57cec5SDimitry Andric     if (isInt<8>(Imm))
1420b57cec5SDimitry Andric       return X86::AND64ri8;
1430b57cec5SDimitry Andric     return X86::AND64ri32;
1440b57cec5SDimitry Andric   }
1450b57cec5SDimitry Andric   if (isInt<8>(Imm))
1460b57cec5SDimitry Andric     return X86::AND32ri8;
1470b57cec5SDimitry Andric   return X86::AND32ri;
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric 
150480093f4SDimitry Andric static unsigned getLEArOpcode(bool IsLP64) {
1510b57cec5SDimitry Andric   return IsLP64 ? X86::LEA64r : X86::LEA32r;
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
15404eeddc0SDimitry Andric static unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm) {
15504eeddc0SDimitry Andric   if (Use64BitReg) {
15604eeddc0SDimitry Andric     if (isUInt<32>(Imm))
15704eeddc0SDimitry Andric       return X86::MOV32ri64;
15804eeddc0SDimitry Andric     if (isInt<32>(Imm))
15904eeddc0SDimitry Andric       return X86::MOV64ri32;
16004eeddc0SDimitry Andric     return X86::MOV64ri;
16104eeddc0SDimitry Andric   }
16204eeddc0SDimitry Andric   return X86::MOV32ri;
16304eeddc0SDimitry Andric }
16404eeddc0SDimitry Andric 
1650b57cec5SDimitry Andric static bool isEAXLiveIn(MachineBasicBlock &MBB) {
1660b57cec5SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
1670b57cec5SDimitry Andric     unsigned Reg = RegMask.PhysReg;
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
1700b57cec5SDimitry Andric         Reg == X86::AH || Reg == X86::AL)
1710b57cec5SDimitry Andric       return true;
1720b57cec5SDimitry Andric   }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   return false;
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric /// Check if the flags need to be preserved before the terminators.
1780b57cec5SDimitry Andric /// This would be the case, if the eflags is live-in of the region
1790b57cec5SDimitry Andric /// composed by the terminators or live-out of that region, without
1800b57cec5SDimitry Andric /// being defined by a terminator.
1810b57cec5SDimitry Andric static bool
1820b57cec5SDimitry Andric flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
1830b57cec5SDimitry Andric   for (const MachineInstr &MI : MBB.terminators()) {
1840b57cec5SDimitry Andric     bool BreakNext = false;
1850b57cec5SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1860b57cec5SDimitry Andric       if (!MO.isReg())
1870b57cec5SDimitry Andric         continue;
1888bcb0991SDimitry Andric       Register Reg = MO.getReg();
1890b57cec5SDimitry Andric       if (Reg != X86::EFLAGS)
1900b57cec5SDimitry Andric         continue;
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric       // This terminator needs an eflags that is not defined
1930b57cec5SDimitry Andric       // by a previous another terminator:
1940b57cec5SDimitry Andric       // EFLAGS is live-in of the region composed by the terminators.
1950b57cec5SDimitry Andric       if (!MO.isDef())
1960b57cec5SDimitry Andric         return true;
1970b57cec5SDimitry Andric       // This terminator defines the eflags, i.e., we don't need to preserve it.
1980b57cec5SDimitry Andric       // However, we still need to check this specific terminator does not
1990b57cec5SDimitry Andric       // read a live-in value.
2000b57cec5SDimitry Andric       BreakNext = true;
2010b57cec5SDimitry Andric     }
2020b57cec5SDimitry Andric     // We found a definition of the eflags, no need to preserve them.
2030b57cec5SDimitry Andric     if (BreakNext)
2040b57cec5SDimitry Andric       return false;
2050b57cec5SDimitry Andric   }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // None of the terminators use or define the eflags.
2080b57cec5SDimitry Andric   // Check if they are live-out, that would imply we need to preserve them.
2090b57cec5SDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors())
2100b57cec5SDimitry Andric     if (Succ->isLiveIn(X86::EFLAGS))
2110b57cec5SDimitry Andric       return true;
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   return false;
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric /// emitSPUpdate - Emit a series of instructions to increment / decrement the
2170b57cec5SDimitry Andric /// stack pointer by a constant value.
2180b57cec5SDimitry Andric void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
2190b57cec5SDimitry Andric                                     MachineBasicBlock::iterator &MBBI,
2200b57cec5SDimitry Andric                                     const DebugLoc &DL,
2210b57cec5SDimitry Andric                                     int64_t NumBytes, bool InEpilogue) const {
2220b57cec5SDimitry Andric   bool isSub = NumBytes < 0;
2230b57cec5SDimitry Andric   uint64_t Offset = isSub ? -NumBytes : NumBytes;
2240b57cec5SDimitry Andric   MachineInstr::MIFlag Flag =
2250b57cec5SDimitry Andric       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   uint64_t Chunk = (1LL << 31) - 1;
2280b57cec5SDimitry Andric 
2295ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
2305ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
2315ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
2325ffd83dbSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
2335ffd83dbSDimitry Andric 
2345ffd83dbSDimitry Andric   // It's ok to not take into account large chunks when probing, as the
2355ffd83dbSDimitry Andric   // allocation is split in smaller chunks anyway.
2365ffd83dbSDimitry Andric   if (EmitInlineStackProbe && !InEpilogue) {
2375ffd83dbSDimitry Andric 
2385ffd83dbSDimitry Andric     // This pseudo-instruction is going to be expanded, potentially using a
2395ffd83dbSDimitry Andric     // loop, by inlineStackProbe().
2405ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset);
2415ffd83dbSDimitry Andric     return;
2425ffd83dbSDimitry Andric   } else if (Offset > Chunk) {
2430b57cec5SDimitry Andric     // Rather than emit a long series of instructions for large offsets,
2440b57cec5SDimitry Andric     // load the offset into a register and do one sub/add
2450b57cec5SDimitry Andric     unsigned Reg = 0;
2460b57cec5SDimitry Andric     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric     if (isSub && !isEAXLiveIn(MBB))
2490b57cec5SDimitry Andric       Reg = Rax;
2500b57cec5SDimitry Andric     else
251e8d8bef9SDimitry Andric       Reg = TRI->findDeadCallerSavedReg(MBB, MBBI);
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric     unsigned AddSubRROpc =
2540b57cec5SDimitry Andric         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
2550b57cec5SDimitry Andric     if (Reg) {
25604eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Reg)
2570b57cec5SDimitry Andric           .addImm(Offset)
2580b57cec5SDimitry Andric           .setMIFlag(Flag);
2590b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
2600b57cec5SDimitry Andric                              .addReg(StackPtr)
2610b57cec5SDimitry Andric                              .addReg(Reg);
2620b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2630b57cec5SDimitry Andric       return;
2640b57cec5SDimitry Andric     } else if (Offset > 8 * Chunk) {
2650b57cec5SDimitry Andric       // If we would need more than 8 add or sub instructions (a >16GB stack
2660b57cec5SDimitry Andric       // frame), it's worth spilling RAX to materialize this immediate.
2670b57cec5SDimitry Andric       //   pushq %rax
2680b57cec5SDimitry Andric       //   movabsq +-$Offset+-SlotSize, %rax
2690b57cec5SDimitry Andric       //   addq %rsp, %rax
2700b57cec5SDimitry Andric       //   xchg %rax, (%rsp)
2710b57cec5SDimitry Andric       //   movq (%rsp), %rsp
2720b57cec5SDimitry Andric       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
2730b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2740b57cec5SDimitry Andric           .addReg(Rax, RegState::Kill)
2750b57cec5SDimitry Andric           .setMIFlag(Flag);
2760b57cec5SDimitry Andric       // Subtract is not commutative, so negate the offset and always use add.
2770b57cec5SDimitry Andric       // Subtract 8 less and add 8 more to account for the PUSH we just did.
2780b57cec5SDimitry Andric       if (isSub)
2790b57cec5SDimitry Andric         Offset = -(Offset - SlotSize);
2800b57cec5SDimitry Andric       else
2810b57cec5SDimitry Andric         Offset = Offset + SlotSize;
28204eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Rax)
2830b57cec5SDimitry Andric           .addImm(Offset)
2840b57cec5SDimitry Andric           .setMIFlag(Flag);
2850b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
2860b57cec5SDimitry Andric                              .addReg(Rax)
2870b57cec5SDimitry Andric                              .addReg(StackPtr);
2880b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2890b57cec5SDimitry Andric       // Exchange the new SP in RAX with the top of the stack.
2900b57cec5SDimitry Andric       addRegOffset(
2910b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
2920b57cec5SDimitry Andric           StackPtr, false, 0);
2930b57cec5SDimitry Andric       // Load new SP from the top of the stack into RSP.
2940b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
2950b57cec5SDimitry Andric                    StackPtr, false, 0);
2960b57cec5SDimitry Andric       return;
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   while (Offset) {
3010b57cec5SDimitry Andric     uint64_t ThisVal = std::min(Offset, Chunk);
3020b57cec5SDimitry Andric     if (ThisVal == SlotSize) {
3030b57cec5SDimitry Andric       // Use push / pop for slot sized adjustments as a size optimization. We
3040b57cec5SDimitry Andric       // need to find a dead register when using pop.
3050b57cec5SDimitry Andric       unsigned Reg = isSub
3060b57cec5SDimitry Andric         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
307e8d8bef9SDimitry Andric         : TRI->findDeadCallerSavedReg(MBB, MBBI);
3080b57cec5SDimitry Andric       if (Reg) {
3090b57cec5SDimitry Andric         unsigned Opc = isSub
3100b57cec5SDimitry Andric           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
3110b57cec5SDimitry Andric           : (Is64Bit ? X86::POP64r  : X86::POP32r);
3120b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(Opc))
3130b57cec5SDimitry Andric             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
3140b57cec5SDimitry Andric             .setMIFlag(Flag);
3150b57cec5SDimitry Andric         Offset -= ThisVal;
3160b57cec5SDimitry Andric         continue;
3170b57cec5SDimitry Andric       }
3180b57cec5SDimitry Andric     }
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
3210b57cec5SDimitry Andric         .setMIFlag(Flag);
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     Offset -= ThisVal;
3240b57cec5SDimitry Andric   }
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
3280b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3290b57cec5SDimitry Andric     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
3300b57cec5SDimitry Andric   assert(Offset != 0 && "zero offset stack adjustment requested");
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
3330b57cec5SDimitry Andric   // is tricky.
3340b57cec5SDimitry Andric   bool UseLEA;
3350b57cec5SDimitry Andric   if (!InEpilogue) {
3360b57cec5SDimitry Andric     // Check if inserting the prologue at the beginning
3370b57cec5SDimitry Andric     // of MBB would require to use LEA operations.
3380b57cec5SDimitry Andric     // We need to use LEA operations if EFLAGS is live in, because
3390b57cec5SDimitry Andric     // it means an instruction will read it before it gets defined.
3400b57cec5SDimitry Andric     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
3410b57cec5SDimitry Andric   } else {
3420b57cec5SDimitry Andric     // If we can use LEA for SP but we shouldn't, check that none
3430b57cec5SDimitry Andric     // of the terminators uses the eflags. Otherwise we will insert
3440b57cec5SDimitry Andric     // a ADD that will redefine the eflags and break the condition.
3450b57cec5SDimitry Andric     // Alternatively, we could move the ADD, but this may not be possible
3460b57cec5SDimitry Andric     // and is an optimization anyway.
3470b57cec5SDimitry Andric     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
3480b57cec5SDimitry Andric     if (UseLEA && !STI.useLeaForSP())
3490b57cec5SDimitry Andric       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
3500b57cec5SDimitry Andric     // If that assert breaks, that means we do not do the right thing
3510b57cec5SDimitry Andric     // in canUseAsEpilogue.
3520b57cec5SDimitry Andric     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
3530b57cec5SDimitry Andric            "We shouldn't have allowed this insertion point");
3540b57cec5SDimitry Andric   }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   MachineInstrBuilder MI;
3570b57cec5SDimitry Andric   if (UseLEA) {
3580b57cec5SDimitry Andric     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
3590b57cec5SDimitry Andric                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
3600b57cec5SDimitry Andric                               StackPtr),
3610b57cec5SDimitry Andric                       StackPtr, false, Offset);
3620b57cec5SDimitry Andric   } else {
3630b57cec5SDimitry Andric     bool IsSub = Offset < 0;
3640b57cec5SDimitry Andric     uint64_t AbsOffset = IsSub ? -Offset : Offset;
3655ffd83dbSDimitry Andric     const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
3660b57cec5SDimitry Andric                                : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
3670b57cec5SDimitry Andric     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
3680b57cec5SDimitry Andric              .addReg(StackPtr)
3690b57cec5SDimitry Andric              .addImm(AbsOffset);
3700b57cec5SDimitry Andric     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric   return MI;
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
3760b57cec5SDimitry Andric                                      MachineBasicBlock::iterator &MBBI,
3770b57cec5SDimitry Andric                                      bool doMergeWithPrevious) const {
3780b57cec5SDimitry Andric   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
3790b57cec5SDimitry Andric       (!doMergeWithPrevious && MBBI == MBB.end()))
3800b57cec5SDimitry Andric     return 0;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   PI = skipDebugInstructionsBackward(PI, MBB.begin());
3850b57cec5SDimitry Andric   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
3860b57cec5SDimitry Andric   // instruction, and that there are no DBG_VALUE or other instructions between
3870b57cec5SDimitry Andric   // ADD/SUB/LEA and its corresponding CFI instruction.
3880b57cec5SDimitry Andric   /* TODO: Add support for the case where there are multiple CFI instructions
3890b57cec5SDimitry Andric     below the ADD/SUB/LEA, e.g.:
3900b57cec5SDimitry Andric     ...
3910b57cec5SDimitry Andric     add
3920b57cec5SDimitry Andric     cfi_def_cfa_offset
3930b57cec5SDimitry Andric     cfi_offset
3940b57cec5SDimitry Andric     ...
3950b57cec5SDimitry Andric   */
3960b57cec5SDimitry Andric   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
3970b57cec5SDimitry Andric     PI = std::prev(PI);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   unsigned Opc = PI->getOpcode();
4000b57cec5SDimitry Andric   int Offset = 0;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
4030b57cec5SDimitry Andric        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
4040b57cec5SDimitry Andric       PI->getOperand(0).getReg() == StackPtr){
4050b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4060b57cec5SDimitry Andric     Offset = PI->getOperand(2).getImm();
4070b57cec5SDimitry Andric   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
4080b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr &&
4090b57cec5SDimitry Andric              PI->getOperand(1).getReg() == StackPtr &&
4100b57cec5SDimitry Andric              PI->getOperand(2).getImm() == 1 &&
4110b57cec5SDimitry Andric              PI->getOperand(3).getReg() == X86::NoRegister &&
4120b57cec5SDimitry Andric              PI->getOperand(5).getReg() == X86::NoRegister) {
4130b57cec5SDimitry Andric     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
4140b57cec5SDimitry Andric     Offset = PI->getOperand(4).getImm();
4150b57cec5SDimitry Andric   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
4160b57cec5SDimitry Andric               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
4170b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr) {
4180b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4190b57cec5SDimitry Andric     Offset = -PI->getOperand(2).getImm();
4200b57cec5SDimitry Andric   } else
4210b57cec5SDimitry Andric     return 0;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   PI = MBB.erase(PI);
424fe6060f1SDimitry Andric   if (PI != MBB.end() && PI->isCFIInstruction()) {
425fe6060f1SDimitry Andric     auto CIs = MBB.getParent()->getFrameInstructions();
426fe6060f1SDimitry Andric     MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()];
427fe6060f1SDimitry Andric     if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset ||
428fe6060f1SDimitry Andric         CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
429fe6060f1SDimitry Andric       PI = MBB.erase(PI);
430fe6060f1SDimitry Andric   }
4310b57cec5SDimitry Andric   if (!doMergeWithPrevious)
4320b57cec5SDimitry Andric     MBBI = skipDebugInstructionsForward(PI, MBB.end());
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   return Offset;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
4380b57cec5SDimitry Andric                                 MachineBasicBlock::iterator MBBI,
4390b57cec5SDimitry Andric                                 const DebugLoc &DL,
44081ad6265SDimitry Andric                                 const MCCFIInstruction &CFIInst,
44181ad6265SDimitry Andric                                 MachineInstr::MIFlag Flag) const {
4420b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4430b57cec5SDimitry Andric   unsigned CFIIndex = MF.addFrameInst(CFIInst);
4440b57cec5SDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
44581ad6265SDimitry Andric       .addCFIIndex(CFIIndex)
44681ad6265SDimitry Andric       .setMIFlag(Flag);
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
4495ffd83dbSDimitry Andric /// Emits Dwarf Info specifying offsets of callee saved registers and
4505ffd83dbSDimitry Andric /// frame pointer. This is called only when basic block sections are enabled.
45104eeddc0SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA(
4525ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
4535ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
4545ffd83dbSDimitry Andric   if (!hasFP(MF)) {
4555ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4565ffd83dbSDimitry Andric     return;
4575ffd83dbSDimitry Andric   }
4585ffd83dbSDimitry Andric   const MachineModuleInfo &MMI = MF.getMMI();
4595ffd83dbSDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
460e8d8bef9SDimitry Andric   const Register FramePtr = TRI->getFrameRegister(MF);
461e8d8bef9SDimitry Andric   const Register MachineFramePtr =
462e8d8bef9SDimitry Andric       STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
4635ffd83dbSDimitry Andric                                : FramePtr;
4645ffd83dbSDimitry Andric   unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true);
4655ffd83dbSDimitry Andric   // Offset = space for return address + size of the frame pointer itself.
4665ffd83dbSDimitry Andric   unsigned Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
4675ffd83dbSDimitry Andric   BuildCFI(MBB, MBBI, DebugLoc{},
4685ffd83dbSDimitry Andric            MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset));
4695ffd83dbSDimitry Andric   emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4705ffd83dbSDimitry Andric }
4715ffd83dbSDimitry Andric 
4720b57cec5SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMoves(
4730b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
4745ffd83dbSDimitry Andric     const DebugLoc &DL, bool IsPrologue) const {
4750b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4760b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
4770b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
4780b57cec5SDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // Add callee saved registers to move list.
4810b57cec5SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   // Calculate offsets.
4844824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
4854824e7fdSDimitry Andric     int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
48604eeddc0SDimitry Andric     Register Reg = I.getReg();
4870b57cec5SDimitry Andric     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
4885ffd83dbSDimitry Andric 
4895ffd83dbSDimitry Andric     if (IsPrologue) {
4900b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
4910b57cec5SDimitry Andric                MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
4925ffd83dbSDimitry Andric     } else {
4935ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
4945ffd83dbSDimitry Andric                MCCFIInstruction::createRestore(nullptr, DwarfReg));
4955ffd83dbSDimitry Andric     }
4960b57cec5SDimitry Andric   }
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric 
49981ad6265SDimitry Andric void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
50081ad6265SDimitry Andric                                             MachineBasicBlock &MBB) const {
50181ad6265SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
50281ad6265SDimitry Andric 
50381ad6265SDimitry Andric   // Insertion point.
50481ad6265SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
50581ad6265SDimitry Andric 
50681ad6265SDimitry Andric   // Fake a debug loc.
50781ad6265SDimitry Andric   DebugLoc DL;
50881ad6265SDimitry Andric   if (MBBI != MBB.end())
50981ad6265SDimitry Andric     DL = MBBI->getDebugLoc();
51081ad6265SDimitry Andric 
51181ad6265SDimitry Andric   // Zero out FP stack if referenced. Do this outside of the loop below so that
51281ad6265SDimitry Andric   // it's done only once.
51381ad6265SDimitry Andric   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
51481ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits()) {
51581ad6265SDimitry Andric     if (!X86::RFP80RegClass.contains(Reg))
51681ad6265SDimitry Andric       continue;
51781ad6265SDimitry Andric 
51881ad6265SDimitry Andric     unsigned NumFPRegs = ST.is64Bit() ? 8 : 7;
51981ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
52081ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0));
52181ad6265SDimitry Andric 
52281ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
52381ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0);
52481ad6265SDimitry Andric     break;
52581ad6265SDimitry Andric   }
52681ad6265SDimitry Andric 
52781ad6265SDimitry Andric   // For GPRs, we only care to clear out the 32-bit register.
52881ad6265SDimitry Andric   BitVector GPRsToZero(TRI->getNumRegs());
52981ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits())
53081ad6265SDimitry Andric     if (TRI->isGeneralPurposeRegister(MF, Reg)) {
53181ad6265SDimitry Andric       GPRsToZero.set(getX86SubSuperRegisterOrZero(Reg, 32));
53281ad6265SDimitry Andric       RegsToZero.reset(Reg);
53381ad6265SDimitry Andric     }
53481ad6265SDimitry Andric 
53581ad6265SDimitry Andric   for (MCRegister Reg : GPRsToZero.set_bits())
53681ad6265SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::XOR32rr), Reg)
53781ad6265SDimitry Andric         .addReg(Reg, RegState::Undef)
53881ad6265SDimitry Andric         .addReg(Reg, RegState::Undef);
53981ad6265SDimitry Andric 
54081ad6265SDimitry Andric   // Zero out registers.
54181ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits()) {
54281ad6265SDimitry Andric     if (ST.hasMMX() && X86::VR64RegClass.contains(Reg))
54381ad6265SDimitry Andric       // FIXME: Ignore MMX registers?
54481ad6265SDimitry Andric       continue;
54581ad6265SDimitry Andric 
54681ad6265SDimitry Andric     unsigned XorOp;
54781ad6265SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
54881ad6265SDimitry Andric       // XMM#
54981ad6265SDimitry Andric       if (!ST.hasSSE1())
55081ad6265SDimitry Andric         continue;
55181ad6265SDimitry Andric       XorOp = X86::PXORrr;
55281ad6265SDimitry Andric     } else if (X86::VR256RegClass.contains(Reg)) {
55381ad6265SDimitry Andric       // YMM#
55481ad6265SDimitry Andric       if (!ST.hasAVX())
55581ad6265SDimitry Andric         continue;
55681ad6265SDimitry Andric       XorOp = X86::VPXORrr;
55781ad6265SDimitry Andric     } else if (X86::VR512RegClass.contains(Reg)) {
55881ad6265SDimitry Andric       // ZMM#
55981ad6265SDimitry Andric       if (!ST.hasAVX512())
56081ad6265SDimitry Andric         continue;
56181ad6265SDimitry Andric       XorOp = X86::VPXORYrr;
56281ad6265SDimitry Andric     } else if (X86::VK1RegClass.contains(Reg) ||
56381ad6265SDimitry Andric                X86::VK2RegClass.contains(Reg) ||
56481ad6265SDimitry Andric                X86::VK4RegClass.contains(Reg) ||
56581ad6265SDimitry Andric                X86::VK8RegClass.contains(Reg) ||
56681ad6265SDimitry Andric                X86::VK16RegClass.contains(Reg)) {
56781ad6265SDimitry Andric       if (!ST.hasVLX())
56881ad6265SDimitry Andric         continue;
56981ad6265SDimitry Andric       XorOp = ST.hasBWI() ? X86::KXORQrr : X86::KXORWrr;
57081ad6265SDimitry Andric     } else {
57181ad6265SDimitry Andric       continue;
57281ad6265SDimitry Andric     }
57381ad6265SDimitry Andric 
57481ad6265SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(XorOp), Reg)
57581ad6265SDimitry Andric       .addReg(Reg, RegState::Undef)
57681ad6265SDimitry Andric       .addReg(Reg, RegState::Undef);
57781ad6265SDimitry Andric   }
57881ad6265SDimitry Andric }
57981ad6265SDimitry Andric 
5804824e7fdSDimitry Andric void X86FrameLowering::emitStackProbe(
5814824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
5824824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
583*bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
5840b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
5850b57cec5SDimitry Andric   if (STI.isTargetWindowsCoreCLR()) {
5860b57cec5SDimitry Andric     if (InProlog) {
5875ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING))
5885ffd83dbSDimitry Andric           .addImm(0 /* no explicit stack size */);
5890b57cec5SDimitry Andric     } else {
5900b57cec5SDimitry Andric       emitStackProbeInline(MF, MBB, MBBI, DL, false);
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric   } else {
5934824e7fdSDimitry Andric     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
5940b57cec5SDimitry Andric   }
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric 
5974824e7fdSDimitry Andric bool X86FrameLowering::stackProbeFunctionModifiesSP() const {
5984824e7fdSDimitry Andric   return STI.isOSWindows() && !STI.isTargetWin64();
5994824e7fdSDimitry Andric }
6004824e7fdSDimitry Andric 
6010b57cec5SDimitry Andric void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
6020b57cec5SDimitry Andric                                         MachineBasicBlock &PrologMBB) const {
6035ffd83dbSDimitry Andric   auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
6045ffd83dbSDimitry Andric     return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
6055ffd83dbSDimitry Andric   });
6065ffd83dbSDimitry Andric   if (Where != PrologMBB.end()) {
6075ffd83dbSDimitry Andric     DebugLoc DL = PrologMBB.findDebugLoc(Where);
6085ffd83dbSDimitry Andric     emitStackProbeInline(MF, PrologMBB, Where, DL, true);
6095ffd83dbSDimitry Andric     Where->eraseFromParent();
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
6140b57cec5SDimitry Andric                                             MachineBasicBlock &MBB,
6150b57cec5SDimitry Andric                                             MachineBasicBlock::iterator MBBI,
6160b57cec5SDimitry Andric                                             const DebugLoc &DL,
6170b57cec5SDimitry Andric                                             bool InProlog) const {
6180b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6195ffd83dbSDimitry Andric   if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
6205ffd83dbSDimitry Andric     emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
6215ffd83dbSDimitry Andric   else
6225ffd83dbSDimitry Andric     emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
6235ffd83dbSDimitry Andric }
6245ffd83dbSDimitry Andric 
6255ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGeneric(
6265ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
6275ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
6285ffd83dbSDimitry Andric   MachineInstr &AllocWithProbe = *MBBI;
6295ffd83dbSDimitry Andric   uint64_t Offset = AllocWithProbe.getOperand(0).getImm();
6305ffd83dbSDimitry Andric 
6315ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6325ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6335ffd83dbSDimitry Andric   assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
6345ffd83dbSDimitry Andric          "different expansion expected for CoreCLR 64 bit");
6355ffd83dbSDimitry Andric 
6365ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6375ffd83dbSDimitry Andric   uint64_t ProbeChunk = StackProbeSize * 8;
6385ffd83dbSDimitry Andric 
639eaeb601bSDimitry Andric   uint64_t MaxAlign =
640fe6060f1SDimitry Andric       TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
641eaeb601bSDimitry Andric 
6425ffd83dbSDimitry Andric   // Synthesize a loop or unroll it, depending on the number of iterations.
643eaeb601bSDimitry Andric   // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
644eaeb601bSDimitry Andric   // between the unaligned rsp and current rsp.
6455ffd83dbSDimitry Andric   if (Offset > ProbeChunk) {
646eaeb601bSDimitry Andric     emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
647eaeb601bSDimitry Andric                                     MaxAlign % StackProbeSize);
6485ffd83dbSDimitry Andric   } else {
649eaeb601bSDimitry Andric     emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
650eaeb601bSDimitry Andric                                      MaxAlign % StackProbeSize);
6515ffd83dbSDimitry Andric   }
6525ffd83dbSDimitry Andric }
6535ffd83dbSDimitry Andric 
6545ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericBlock(
6555ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
656eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
657eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
6585ffd83dbSDimitry Andric 
659fe6060f1SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
660fe6060f1SDimitry Andric   const bool HasFP = hasFP(MF);
6615ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6625ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6635ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
6645ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6655ffd83dbSDimitry Andric 
666eaeb601bSDimitry Andric   uint64_t CurrentOffset = 0;
667eaeb601bSDimitry Andric 
668eaeb601bSDimitry Andric   assert(AlignOffset < StackProbeSize);
669eaeb601bSDimitry Andric 
670eaeb601bSDimitry Andric   // If the offset is so small it fits within a page, there's nothing to do.
671eaeb601bSDimitry Andric   if (StackProbeSize < Offset + AlignOffset) {
672eaeb601bSDimitry Andric 
673*bdd1243dSDimitry Andric     uint64_t StackAdjustment = StackProbeSize - AlignOffset;
674*bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
675eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
676fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
677*bdd1243dSDimitry Andric       BuildCFI(
678*bdd1243dSDimitry Andric           MBB, MBBI, DL,
679*bdd1243dSDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
680fe6060f1SDimitry Andric     }
681eaeb601bSDimitry Andric 
682eaeb601bSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
683eaeb601bSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
684eaeb601bSDimitry Andric                  StackPtr, false, 0)
685eaeb601bSDimitry Andric         .addImm(0)
686eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
687eaeb601bSDimitry Andric     NumFrameExtraProbe++;
688eaeb601bSDimitry Andric     CurrentOffset = StackProbeSize - AlignOffset;
689eaeb601bSDimitry Andric   }
690eaeb601bSDimitry Andric 
691eaeb601bSDimitry Andric   // For the next N - 1 pages, just probe. I tried to take advantage of
6925ffd83dbSDimitry Andric   // natural probes but it implies much more logic and there was very few
6935ffd83dbSDimitry Andric   // interesting natural probes to interleave.
6945ffd83dbSDimitry Andric   while (CurrentOffset + StackProbeSize < Offset) {
695*bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
6965ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
6975ffd83dbSDimitry Andric 
698fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
699fe6060f1SDimitry Andric       BuildCFI(
700fe6060f1SDimitry Andric           MBB, MBBI, DL,
701fe6060f1SDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
702fe6060f1SDimitry Andric     }
7035ffd83dbSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
7045ffd83dbSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
7055ffd83dbSDimitry Andric                  StackPtr, false, 0)
7065ffd83dbSDimitry Andric         .addImm(0)
7075ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
7085ffd83dbSDimitry Andric     NumFrameExtraProbe++;
7095ffd83dbSDimitry Andric     CurrentOffset += StackProbeSize;
7105ffd83dbSDimitry Andric   }
7115ffd83dbSDimitry Andric 
712eaeb601bSDimitry Andric   // No need to probe the tail, it is smaller than a Page.
7135ffd83dbSDimitry Andric   uint64_t ChunkSize = Offset - CurrentOffset;
714*bdd1243dSDimitry Andric   if (ChunkSize == SlotSize) {
715*bdd1243dSDimitry Andric     // Use push for slot sized adjustments as a size optimization,
716*bdd1243dSDimitry Andric     // like emitSPUpdate does when not probing.
717*bdd1243dSDimitry Andric     unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
718*bdd1243dSDimitry Andric     unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
719*bdd1243dSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc))
720*bdd1243dSDimitry Andric         .addReg(Reg, RegState::Undef)
7215ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
722*bdd1243dSDimitry Andric   } else {
723*bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
724*bdd1243dSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
725*bdd1243dSDimitry Andric   }
726fe6060f1SDimitry Andric   // No need to adjust Dwarf CFA offset here, the last position of the stack has
727fe6060f1SDimitry Andric   // been defined
7285ffd83dbSDimitry Andric }
7295ffd83dbSDimitry Andric 
7305ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericLoop(
7315ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
732eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
733eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
7345ffd83dbSDimitry Andric   assert(Offset && "null offset");
7355ffd83dbSDimitry Andric 
736*bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
737*bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
738*bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
739*bdd1243dSDimitry Andric 
74004eeddc0SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
74104eeddc0SDimitry Andric   const bool HasFP = hasFP(MF);
7425ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
7435ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
7445ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
7455ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
7465ffd83dbSDimitry Andric 
747eaeb601bSDimitry Andric   if (AlignOffset) {
748eaeb601bSDimitry Andric     if (AlignOffset < StackProbeSize) {
749eaeb601bSDimitry Andric       // Perform a first smaller allocation followed by a probe.
750*bdd1243dSDimitry Andric       BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
751eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
752eaeb601bSDimitry Andric 
753eaeb601bSDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
754eaeb601bSDimitry Andric                        .setMIFlag(MachineInstr::FrameSetup),
755eaeb601bSDimitry Andric                    StackPtr, false, 0)
756eaeb601bSDimitry Andric           .addImm(0)
757eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
758eaeb601bSDimitry Andric       NumFrameExtraProbe++;
759eaeb601bSDimitry Andric       Offset -= AlignOffset;
760eaeb601bSDimitry Andric     }
761eaeb601bSDimitry Andric   }
762eaeb601bSDimitry Andric 
7635ffd83dbSDimitry Andric   // Synthesize a loop
7645ffd83dbSDimitry Andric   NumFrameLoopProbe++;
7655ffd83dbSDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
7665ffd83dbSDimitry Andric 
7675ffd83dbSDimitry Andric   MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7685ffd83dbSDimitry Andric   MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7695ffd83dbSDimitry Andric 
7705ffd83dbSDimitry Andric   MachineFunction::iterator MBBIter = ++MBB.getIterator();
7715ffd83dbSDimitry Andric   MF.insert(MBBIter, testMBB);
7725ffd83dbSDimitry Andric   MF.insert(MBBIter, tailMBB);
7735ffd83dbSDimitry Andric 
7748c6f6c0cSDimitry Andric   Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
7758c6f6c0cSDimitry Andric                               : Is64Bit         ? X86::R11D
7768c6f6c0cSDimitry Andric                                                 : X86::EAX;
77704eeddc0SDimitry Andric 
7785ffd83dbSDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
7795ffd83dbSDimitry Andric       .addReg(StackPtr)
7805ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
7815ffd83dbSDimitry Andric 
7825ffd83dbSDimitry Andric   // save loop bound
7835ffd83dbSDimitry Andric   {
78404eeddc0SDimitry Andric     const unsigned BoundOffset = alignDown(Offset, StackProbeSize);
78504eeddc0SDimitry Andric     const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr, BoundOffset);
786eaeb601bSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
7875ffd83dbSDimitry Andric         .addReg(FinalStackProbed)
78804eeddc0SDimitry Andric         .addImm(BoundOffset)
7895ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
79004eeddc0SDimitry Andric 
79104eeddc0SDimitry Andric     // while in the loop, use loop-invariant reg for CFI,
79204eeddc0SDimitry Andric     // instead of the stack pointer, which changes during the loop
79304eeddc0SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
79404eeddc0SDimitry Andric       // x32 uses the same DWARF register numbers as x86-64,
79504eeddc0SDimitry Andric       // so there isn't a register number for r11d, we must use r11 instead
79604eeddc0SDimitry Andric       const Register DwarfFinalStackProbed =
79704eeddc0SDimitry Andric           STI.isTarget64BitILP32()
79804eeddc0SDimitry Andric               ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
79904eeddc0SDimitry Andric               : FinalStackProbed;
80004eeddc0SDimitry Andric 
80104eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
80204eeddc0SDimitry Andric                MCCFIInstruction::createDefCfaRegister(
80304eeddc0SDimitry Andric                    nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
80404eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
80504eeddc0SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
80604eeddc0SDimitry Andric     }
8075ffd83dbSDimitry Andric   }
8085ffd83dbSDimitry Andric 
8095ffd83dbSDimitry Andric   // allocate a page
810*bdd1243dSDimitry Andric   BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
811*bdd1243dSDimitry Andric                        /*InEpilogue=*/false)
8125ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8135ffd83dbSDimitry Andric 
8145ffd83dbSDimitry Andric   // touch the page
8155ffd83dbSDimitry Andric   addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
8165ffd83dbSDimitry Andric                    .setMIFlag(MachineInstr::FrameSetup),
8175ffd83dbSDimitry Andric                StackPtr, false, 0)
8185ffd83dbSDimitry Andric       .addImm(0)
8195ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8205ffd83dbSDimitry Andric 
8215ffd83dbSDimitry Andric   // cmp with stack pointer bound
8225ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
8235ffd83dbSDimitry Andric       .addReg(StackPtr)
8245ffd83dbSDimitry Andric       .addReg(FinalStackProbed)
8255ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8265ffd83dbSDimitry Andric 
8275ffd83dbSDimitry Andric   // jump
8285ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(X86::JCC_1))
8295ffd83dbSDimitry Andric       .addMBB(testMBB)
8305ffd83dbSDimitry Andric       .addImm(X86::COND_NE)
8315ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8325ffd83dbSDimitry Andric   testMBB->addSuccessor(testMBB);
8335ffd83dbSDimitry Andric   testMBB->addSuccessor(tailMBB);
8345ffd83dbSDimitry Andric 
8355ffd83dbSDimitry Andric   // BB management
8365ffd83dbSDimitry Andric   tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
8375ffd83dbSDimitry Andric   tailMBB->transferSuccessorsAndUpdatePHIs(&MBB);
8385ffd83dbSDimitry Andric   MBB.addSuccessor(testMBB);
8395ffd83dbSDimitry Andric 
8405ffd83dbSDimitry Andric   // handle tail
841*bdd1243dSDimitry Andric   const uint64_t TailOffset = Offset % StackProbeSize;
84204eeddc0SDimitry Andric   MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
8435ffd83dbSDimitry Andric   if (TailOffset) {
844*bdd1243dSDimitry Andric     BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
845*bdd1243dSDimitry Andric                          /*InEpilogue=*/false)
8465ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
8475ffd83dbSDimitry Andric   }
8485ffd83dbSDimitry Andric 
84904eeddc0SDimitry Andric   // after the loop, switch back to stack pointer for CFI
85004eeddc0SDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
85104eeddc0SDimitry Andric     // x32 uses the same DWARF register numbers as x86-64,
85204eeddc0SDimitry Andric     // so there isn't a register number for esp, we must use rsp instead
85304eeddc0SDimitry Andric     const Register DwarfStackPtr =
85404eeddc0SDimitry Andric         STI.isTarget64BitILP32()
85504eeddc0SDimitry Andric             ? Register(getX86SubSuperRegister(StackPtr, 64))
85604eeddc0SDimitry Andric             : Register(StackPtr);
85704eeddc0SDimitry Andric 
85804eeddc0SDimitry Andric     BuildCFI(*tailMBB, TailMBBIter, DL,
85904eeddc0SDimitry Andric              MCCFIInstruction::createDefCfaRegister(
86004eeddc0SDimitry Andric                  nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
86104eeddc0SDimitry Andric   }
86204eeddc0SDimitry Andric 
8635ffd83dbSDimitry Andric   // Update Live In information
8645ffd83dbSDimitry Andric   recomputeLiveIns(*testMBB);
8655ffd83dbSDimitry Andric   recomputeLiveIns(*tailMBB);
8665ffd83dbSDimitry Andric }
8675ffd83dbSDimitry Andric 
8685ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
8695ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
8705ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
8715ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
8720b57cec5SDimitry Andric   assert(STI.is64Bit() && "different expansion needed for 32 bit");
8730b57cec5SDimitry Andric   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
8740b57cec5SDimitry Andric   const TargetInstrInfo &TII = *STI.getInstrInfo();
8750b57cec5SDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
8760b57cec5SDimitry Andric 
877*bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
878*bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
879*bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
880*bdd1243dSDimitry Andric 
8810b57cec5SDimitry Andric   // RAX contains the number of bytes of desired stack adjustment.
8820b57cec5SDimitry Andric   // The handling here assumes this value has already been updated so as to
8830b57cec5SDimitry Andric   // maintain stack alignment.
8840b57cec5SDimitry Andric   //
8850b57cec5SDimitry Andric   // We need to exit with RSP modified by this amount and execute suitable
8860b57cec5SDimitry Andric   // page touches to notify the OS that we're growing the stack responsibly.
8870b57cec5SDimitry Andric   // All stack probing must be done without modifying RSP.
8880b57cec5SDimitry Andric   //
8890b57cec5SDimitry Andric   // MBB:
8900b57cec5SDimitry Andric   //    SizeReg = RAX;
8910b57cec5SDimitry Andric   //    ZeroReg = 0
8920b57cec5SDimitry Andric   //    CopyReg = RSP
8930b57cec5SDimitry Andric   //    Flags, TestReg = CopyReg - SizeReg
8940b57cec5SDimitry Andric   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
8950b57cec5SDimitry Andric   //    LimitReg = gs magic thread env access
8960b57cec5SDimitry Andric   //    if FinalReg >= LimitReg goto ContinueMBB
8970b57cec5SDimitry Andric   // RoundBB:
8980b57cec5SDimitry Andric   //    RoundReg = page address of FinalReg
8990b57cec5SDimitry Andric   // LoopMBB:
9000b57cec5SDimitry Andric   //    LoopReg = PHI(LimitReg,ProbeReg)
9010b57cec5SDimitry Andric   //    ProbeReg = LoopReg - PageSize
9020b57cec5SDimitry Andric   //    [ProbeReg] = 0
9030b57cec5SDimitry Andric   //    if (ProbeReg > RoundReg) goto LoopMBB
9040b57cec5SDimitry Andric   // ContinueMBB:
9050b57cec5SDimitry Andric   //    RSP = RSP - RAX
9060b57cec5SDimitry Andric   //    [rest of original MBB]
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   // Set up the new basic blocks
9090b57cec5SDimitry Andric   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9100b57cec5SDimitry Andric   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9110b57cec5SDimitry Andric   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
9140b57cec5SDimitry Andric   MF.insert(MBBIter, RoundMBB);
9150b57cec5SDimitry Andric   MF.insert(MBBIter, LoopMBB);
9160b57cec5SDimitry Andric   MF.insert(MBBIter, ContinueMBB);
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   // Split MBB and move the tail portion down to ContinueMBB.
9190b57cec5SDimitry Andric   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
9200b57cec5SDimitry Andric   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
9210b57cec5SDimitry Andric   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // Some useful constants
9240b57cec5SDimitry Andric   const int64_t ThreadEnvironmentStackLimit = 0x10;
9250b57cec5SDimitry Andric   const int64_t PageSize = 0x1000;
9260b57cec5SDimitry Andric   const int64_t PageMask = ~(PageSize - 1);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   // Registers we need. For the normal case we use virtual
9290b57cec5SDimitry Andric   // registers. For the prolog expansion we use RAX, RCX and RDX.
9300b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
9310b57cec5SDimitry Andric   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
9320b57cec5SDimitry Andric   const Register SizeReg = InProlog ? X86::RAX
9330b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9340b57cec5SDimitry Andric                  ZeroReg = InProlog ? X86::RCX
9350b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9360b57cec5SDimitry Andric                  CopyReg = InProlog ? X86::RDX
9370b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9380b57cec5SDimitry Andric                  TestReg = InProlog ? X86::RDX
9390b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9400b57cec5SDimitry Andric                  FinalReg = InProlog ? X86::RDX
9410b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
9420b57cec5SDimitry Andric                  RoundedReg = InProlog ? X86::RDX
9430b57cec5SDimitry Andric                                        : MRI.createVirtualRegister(RegClass),
9440b57cec5SDimitry Andric                  LimitReg = InProlog ? X86::RCX
9450b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
9460b57cec5SDimitry Andric                  JoinReg = InProlog ? X86::RCX
9470b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9480b57cec5SDimitry Andric                  ProbeReg = InProlog ? X86::RCX
9490b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass);
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   // SP-relative offsets where we can save RCX and RDX.
9520b57cec5SDimitry Andric   int64_t RCXShadowSlot = 0;
9530b57cec5SDimitry Andric   int64_t RDXShadowSlot = 0;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   // If inlining in the prolog, save RCX and RDX.
9560b57cec5SDimitry Andric   if (InProlog) {
9570b57cec5SDimitry Andric     // Compute the offsets. We need to account for things already
9580b57cec5SDimitry Andric     // pushed onto the stack at this point: return address, frame
9590b57cec5SDimitry Andric     // pointer (if used), and callee saves.
9600b57cec5SDimitry Andric     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9610b57cec5SDimitry Andric     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
9620b57cec5SDimitry Andric     const bool HasFP = hasFP(MF);
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric     // Check if we need to spill RCX and/or RDX.
9650b57cec5SDimitry Andric     // Here we assume that no earlier prologue instruction changes RCX and/or
9660b57cec5SDimitry Andric     // RDX, so checking the block live-ins is enough.
9670b57cec5SDimitry Andric     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
9680b57cec5SDimitry Andric     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
9690b57cec5SDimitry Andric     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
9700b57cec5SDimitry Andric     // Assign the initial slot to both registers, then change RDX's slot if both
9710b57cec5SDimitry Andric     // need to be spilled.
9720b57cec5SDimitry Andric     if (IsRCXLiveIn)
9730b57cec5SDimitry Andric       RCXShadowSlot = InitSlot;
9740b57cec5SDimitry Andric     if (IsRDXLiveIn)
9750b57cec5SDimitry Andric       RDXShadowSlot = InitSlot;
9760b57cec5SDimitry Andric     if (IsRDXLiveIn && IsRCXLiveIn)
9770b57cec5SDimitry Andric       RDXShadowSlot += 8;
9780b57cec5SDimitry Andric     // Emit the saves if needed.
9790b57cec5SDimitry Andric     if (IsRCXLiveIn)
9800b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
9810b57cec5SDimitry Andric                    RCXShadowSlot)
9820b57cec5SDimitry Andric           .addReg(X86::RCX);
9830b57cec5SDimitry Andric     if (IsRDXLiveIn)
9840b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
9850b57cec5SDimitry Andric                    RDXShadowSlot)
9860b57cec5SDimitry Andric           .addReg(X86::RDX);
9870b57cec5SDimitry Andric   } else {
9880b57cec5SDimitry Andric     // Not in the prolog. Copy RAX to a virtual reg.
9890b57cec5SDimitry Andric     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   // Add code to MBB to check for overflow and set the new target stack pointer
9930b57cec5SDimitry Andric   // to zero if so.
9940b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
9950b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef)
9960b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef);
9970b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
9980b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
9990b57cec5SDimitry Andric       .addReg(CopyReg)
10000b57cec5SDimitry Andric       .addReg(SizeReg);
10010b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
10020b57cec5SDimitry Andric       .addReg(TestReg)
10030b57cec5SDimitry Andric       .addReg(ZeroReg)
10040b57cec5SDimitry Andric       .addImm(X86::COND_B);
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   // FinalReg now holds final stack pointer value, or zero if
10070b57cec5SDimitry Andric   // allocation would overflow. Compare against the current stack
10080b57cec5SDimitry Andric   // limit from the thread environment block. Note this limit is the
10090b57cec5SDimitry Andric   // lowest touched page on the stack, not the point at which the OS
10100b57cec5SDimitry Andric   // will cause an overflow exception, so this is just an optimization
10110b57cec5SDimitry Andric   // to avoid unnecessarily touching pages that are below the current
10120b57cec5SDimitry Andric   // SP but already committed to the stack by the OS.
10130b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
10140b57cec5SDimitry Andric       .addReg(0)
10150b57cec5SDimitry Andric       .addImm(1)
10160b57cec5SDimitry Andric       .addReg(0)
10170b57cec5SDimitry Andric       .addImm(ThreadEnvironmentStackLimit)
10180b57cec5SDimitry Andric       .addReg(X86::GS);
10190b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
10200b57cec5SDimitry Andric   // Jump if the desired stack pointer is at or above the stack limit.
10210b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   // Add code to roundMBB to round the final stack pointer to a page boundary.
10240b57cec5SDimitry Andric   RoundMBB->addLiveIn(FinalReg);
10250b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
10260b57cec5SDimitry Andric       .addReg(FinalReg)
10270b57cec5SDimitry Andric       .addImm(PageMask);
10280b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   // LimitReg now holds the current stack limit, RoundedReg page-rounded
10310b57cec5SDimitry Andric   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
10320b57cec5SDimitry Andric   // and probe until we reach RoundedReg.
10330b57cec5SDimitry Andric   if (!InProlog) {
10340b57cec5SDimitry Andric     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
10350b57cec5SDimitry Andric         .addReg(LimitReg)
10360b57cec5SDimitry Andric         .addMBB(RoundMBB)
10370b57cec5SDimitry Andric         .addReg(ProbeReg)
10380b57cec5SDimitry Andric         .addMBB(LoopMBB);
10390b57cec5SDimitry Andric   }
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   LoopMBB->addLiveIn(JoinReg);
10420b57cec5SDimitry Andric   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
10430b57cec5SDimitry Andric                false, -PageSize);
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric   // Probe by storing a byte onto the stack.
10460b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
10470b57cec5SDimitry Andric       .addReg(ProbeReg)
10480b57cec5SDimitry Andric       .addImm(1)
10490b57cec5SDimitry Andric       .addReg(0)
10500b57cec5SDimitry Andric       .addImm(0)
10510b57cec5SDimitry Andric       .addReg(0)
10520b57cec5SDimitry Andric       .addImm(0);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   LoopMBB->addLiveIn(RoundedReg);
10550b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
10560b57cec5SDimitry Andric       .addReg(RoundedReg)
10570b57cec5SDimitry Andric       .addReg(ProbeReg);
10580b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   // If in prolog, restore RDX and RCX.
10630b57cec5SDimitry Andric   if (InProlog) {
10640b57cec5SDimitry Andric     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
10650b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
10660b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RCX),
10670b57cec5SDimitry Andric                    X86::RSP, false, RCXShadowSlot);
10680b57cec5SDimitry Andric     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
10690b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
10700b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RDX),
10710b57cec5SDimitry Andric                    X86::RSP, false, RDXShadowSlot);
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   // Now that the probing is done, add code to continueMBB to update
10750b57cec5SDimitry Andric   // the stack pointer for real.
10760b57cec5SDimitry Andric   ContinueMBB->addLiveIn(SizeReg);
10770b57cec5SDimitry Andric   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
10780b57cec5SDimitry Andric       .addReg(X86::RSP)
10790b57cec5SDimitry Andric       .addReg(SizeReg);
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // Add the control flow edges we need.
10820b57cec5SDimitry Andric   MBB.addSuccessor(ContinueMBB);
10830b57cec5SDimitry Andric   MBB.addSuccessor(RoundMBB);
10840b57cec5SDimitry Andric   RoundMBB->addSuccessor(LoopMBB);
10850b57cec5SDimitry Andric   LoopMBB->addSuccessor(ContinueMBB);
10860b57cec5SDimitry Andric   LoopMBB->addSuccessor(LoopMBB);
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric   // Mark all the instructions added to the prolog as frame setup.
10890b57cec5SDimitry Andric   if (InProlog) {
10900b57cec5SDimitry Andric     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
10910b57cec5SDimitry Andric       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
10920b57cec5SDimitry Andric     }
10930b57cec5SDimitry Andric     for (MachineInstr &MI : *RoundMBB) {
10940b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
10950b57cec5SDimitry Andric     }
10960b57cec5SDimitry Andric     for (MachineInstr &MI : *LoopMBB) {
10970b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
10980b57cec5SDimitry Andric     }
1099*bdd1243dSDimitry Andric     for (MachineInstr &MI :
1100*bdd1243dSDimitry Andric          llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1101*bdd1243dSDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11020b57cec5SDimitry Andric     }
11030b57cec5SDimitry Andric   }
11040b57cec5SDimitry Andric }
11050b57cec5SDimitry Andric 
11064824e7fdSDimitry Andric void X86FrameLowering::emitStackProbeCall(
11074824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
11084824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1109*bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
11100b57cec5SDimitry Andric   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
11110b57cec5SDimitry Andric 
11120946e70aSDimitry Andric   // FIXME: Add indirect thunk support and remove this.
11130946e70aSDimitry Andric   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
11140b57cec5SDimitry Andric     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
11150946e70aSDimitry Andric                        "code model and indirect thunks not yet implemented.");
11160b57cec5SDimitry Andric 
1117*bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1118*bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
1119*bdd1243dSDimitry Andric          "Stack probe calls will clobber live EFLAGS.");
1120*bdd1243dSDimitry Andric 
11210b57cec5SDimitry Andric   unsigned CallOp;
11220b57cec5SDimitry Andric   if (Is64Bit)
11230b57cec5SDimitry Andric     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
11240b57cec5SDimitry Andric   else
11250b57cec5SDimitry Andric     CallOp = X86::CALLpcrel32;
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   MachineInstrBuilder CI;
11300b57cec5SDimitry Andric   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   // All current stack probes take AX and SP as input, clobber flags, and
11330b57cec5SDimitry Andric   // preserve all registers. x86_64 probes leave RSP unmodified.
11340b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
11350b57cec5SDimitry Andric     // For the large code model, we have to call through a register. Use R11,
11360b57cec5SDimitry Andric     // as it is scratch in all supported calling conventions.
11370b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
11380b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11390b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
11400b57cec5SDimitry Andric   } else {
11410b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
11420b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11430b57cec5SDimitry Andric   }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
11460b57cec5SDimitry Andric   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
11470b57cec5SDimitry Andric   CI.addReg(AX, RegState::Implicit)
11480b57cec5SDimitry Andric       .addReg(SP, RegState::Implicit)
11490b57cec5SDimitry Andric       .addReg(AX, RegState::Define | RegState::Implicit)
11500b57cec5SDimitry Andric       .addReg(SP, RegState::Define | RegState::Implicit)
11510b57cec5SDimitry Andric       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11520b57cec5SDimitry Andric 
11534824e7fdSDimitry Andric   MachineInstr *ModInst = CI;
11540b57cec5SDimitry Andric   if (STI.isTargetWin64() || !STI.isOSWindows()) {
11550b57cec5SDimitry Andric     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
11560b57cec5SDimitry Andric     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
11570b57cec5SDimitry Andric     // themselves. They also does not clobber %rax so we can reuse it when
11580b57cec5SDimitry Andric     // adjusting %rsp.
11590b57cec5SDimitry Andric     // All other platforms do not specify a particular ABI for the stack probe
11600b57cec5SDimitry Andric     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
11614824e7fdSDimitry Andric     ModInst =
11620b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
11630b57cec5SDimitry Andric             .addReg(SP)
11640b57cec5SDimitry Andric             .addReg(AX);
11650b57cec5SDimitry Andric   }
11660b57cec5SDimitry Andric 
11674824e7fdSDimitry Andric   // DebugInfo variable locations -- if there's an instruction number for the
11684824e7fdSDimitry Andric   // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
11694824e7fdSDimitry Andric   // modifies SP.
11704824e7fdSDimitry Andric   if (InstrNum) {
11714824e7fdSDimitry Andric     if (STI.isTargetWin64() || !STI.isOSWindows()) {
11724824e7fdSDimitry Andric       // Label destination operand of the subtract.
11734824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(*InstrNum,
11744824e7fdSDimitry Andric                                     {ModInst->getDebugInstrNum(), 0});
11754824e7fdSDimitry Andric     } else {
11764824e7fdSDimitry Andric       // Label the call. The operand number is the penultimate operand, zero
11774824e7fdSDimitry Andric       // based.
11784824e7fdSDimitry Andric       unsigned SPDefOperand = ModInst->getNumOperands() - 2;
11794824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(
11804824e7fdSDimitry Andric           *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
11814824e7fdSDimitry Andric     }
11824824e7fdSDimitry Andric   }
11834824e7fdSDimitry Andric 
11840b57cec5SDimitry Andric   if (InProlog) {
11850b57cec5SDimitry Andric     // Apply the frame setup flag to all inserted instrs.
11860b57cec5SDimitry Andric     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
11870b57cec5SDimitry Andric       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric static unsigned calculateSetFPREG(uint64_t SPAdjust) {
11920b57cec5SDimitry Andric   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
11930b57cec5SDimitry Andric   // and might require smaller successive adjustments.
11940b57cec5SDimitry Andric   const uint64_t Win64MaxSEHOffset = 128;
11950b57cec5SDimitry Andric   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
11960b57cec5SDimitry Andric   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
11970b57cec5SDimitry Andric   return SEHFrameOffset & -16;
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric // If we're forcing a stack realignment we can't rely on just the frame
12010b57cec5SDimitry Andric // info, we need to know the ABI stack alignment as well in case we
12020b57cec5SDimitry Andric // have a call out.  Otherwise just make sure we have some alignment - we'll
12030b57cec5SDimitry Andric // go with the minimum SlotSize.
12040b57cec5SDimitry Andric uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
12050b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
12065ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
12075ffd83dbSDimitry Andric   Align StackAlign = getStackAlign();
12080b57cec5SDimitry Andric   if (MF.getFunction().hasFnAttribute("stackrealign")) {
12090b57cec5SDimitry Andric     if (MFI.hasCalls())
12100b57cec5SDimitry Andric       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
12110b57cec5SDimitry Andric     else if (MaxAlign < SlotSize)
12125ffd83dbSDimitry Andric       MaxAlign = Align(SlotSize);
12130b57cec5SDimitry Andric   }
12145ffd83dbSDimitry Andric   return MaxAlign.value();
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
12180b57cec5SDimitry Andric                                           MachineBasicBlock::iterator MBBI,
12190b57cec5SDimitry Andric                                           const DebugLoc &DL, unsigned Reg,
12200b57cec5SDimitry Andric                                           uint64_t MaxAlign) const {
12210b57cec5SDimitry Andric   uint64_t Val = -MaxAlign;
12220b57cec5SDimitry Andric   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1223eaeb601bSDimitry Andric 
1224eaeb601bSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1225eaeb601bSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1226eaeb601bSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
1227eaeb601bSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1228eaeb601bSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1229eaeb601bSDimitry Andric 
1230eaeb601bSDimitry Andric   // We want to make sure that (in worst case) less than StackProbeSize bytes
1231eaeb601bSDimitry Andric   // are not probed after the AND. This assumption is used in
1232eaeb601bSDimitry Andric   // emitStackProbeInlineGeneric.
1233eaeb601bSDimitry Andric   if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1234eaeb601bSDimitry Andric     {
1235eaeb601bSDimitry Andric       NumFrameLoopProbe++;
1236eaeb601bSDimitry Andric       MachineBasicBlock *entryMBB =
1237eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1238eaeb601bSDimitry Andric       MachineBasicBlock *headMBB =
1239eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1240eaeb601bSDimitry Andric       MachineBasicBlock *bodyMBB =
1241eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1242eaeb601bSDimitry Andric       MachineBasicBlock *footMBB =
1243eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1244eaeb601bSDimitry Andric 
1245eaeb601bSDimitry Andric       MachineFunction::iterator MBBIter = MBB.getIterator();
1246eaeb601bSDimitry Andric       MF.insert(MBBIter, entryMBB);
1247eaeb601bSDimitry Andric       MF.insert(MBBIter, headMBB);
1248eaeb601bSDimitry Andric       MF.insert(MBBIter, bodyMBB);
1249eaeb601bSDimitry Andric       MF.insert(MBBIter, footMBB);
1250eaeb601bSDimitry Andric       const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
12518c6f6c0cSDimitry Andric       Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
12528c6f6c0cSDimitry Andric                                   : Is64Bit         ? X86::R11D
12538c6f6c0cSDimitry Andric                                                     : X86::EAX;
1254eaeb601bSDimitry Andric 
1255eaeb601bSDimitry Andric       // Setup entry block
1256eaeb601bSDimitry Andric       {
1257eaeb601bSDimitry Andric 
1258eaeb601bSDimitry Andric         entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1259eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1260eaeb601bSDimitry Andric             .addReg(StackPtr)
1261eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1262eaeb601bSDimitry Andric         MachineInstr *MI =
1263eaeb601bSDimitry Andric             BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1264eaeb601bSDimitry Andric                 .addReg(FinalStackProbed)
1265eaeb601bSDimitry Andric                 .addImm(Val)
1266eaeb601bSDimitry Andric                 .setMIFlag(MachineInstr::FrameSetup);
1267eaeb601bSDimitry Andric 
1268eaeb601bSDimitry Andric         // The EFLAGS implicit def is dead.
1269eaeb601bSDimitry Andric         MI->getOperand(3).setIsDead();
1270eaeb601bSDimitry Andric 
1271eaeb601bSDimitry Andric         BuildMI(entryMBB, DL,
1272eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1273eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1274eaeb601bSDimitry Andric             .addReg(StackPtr)
1275eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1276eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1277eaeb601bSDimitry Andric             .addMBB(&MBB)
1278eaeb601bSDimitry Andric             .addImm(X86::COND_E)
1279eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1280eaeb601bSDimitry Andric         entryMBB->addSuccessor(headMBB);
1281eaeb601bSDimitry Andric         entryMBB->addSuccessor(&MBB);
1282eaeb601bSDimitry Andric       }
1283eaeb601bSDimitry Andric 
1284eaeb601bSDimitry Andric       // Loop entry block
1285eaeb601bSDimitry Andric 
1286eaeb601bSDimitry Andric       {
1287eaeb601bSDimitry Andric         const unsigned SUBOpc =
1288eaeb601bSDimitry Andric             getSUBriOpcode(Uses64BitFramePtr, StackProbeSize);
1289eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1290eaeb601bSDimitry Andric             .addReg(StackPtr)
1291eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1292eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1293eaeb601bSDimitry Andric 
1294eaeb601bSDimitry Andric         BuildMI(headMBB, DL,
1295eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1296eaeb601bSDimitry Andric             .addReg(StackPtr)
1297*bdd1243dSDimitry Andric             .addReg(FinalStackProbed)
1298eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1299eaeb601bSDimitry Andric 
1300*bdd1243dSDimitry Andric         // jump to the footer if StackPtr < FinalStackProbed
1301eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1302eaeb601bSDimitry Andric             .addMBB(footMBB)
1303eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1304eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1305eaeb601bSDimitry Andric 
1306eaeb601bSDimitry Andric         headMBB->addSuccessor(bodyMBB);
1307eaeb601bSDimitry Andric         headMBB->addSuccessor(footMBB);
1308eaeb601bSDimitry Andric       }
1309eaeb601bSDimitry Andric 
1310eaeb601bSDimitry Andric       // setup loop body
1311eaeb601bSDimitry Andric       {
1312eaeb601bSDimitry Andric         addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1313eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1314eaeb601bSDimitry Andric                      StackPtr, false, 0)
1315eaeb601bSDimitry Andric             .addImm(0)
1316eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1317eaeb601bSDimitry Andric 
1318eaeb601bSDimitry Andric         const unsigned SUBOpc =
1319eaeb601bSDimitry Andric             getSUBriOpcode(Uses64BitFramePtr, StackProbeSize);
1320eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1321eaeb601bSDimitry Andric             .addReg(StackPtr)
1322eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1323eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1324eaeb601bSDimitry Andric 
1325eaeb601bSDimitry Andric         // cmp with stack pointer bound
1326eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL,
1327eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1328eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1329eaeb601bSDimitry Andric             .addReg(StackPtr)
1330eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1331eaeb601bSDimitry Andric 
1332*bdd1243dSDimitry Andric         // jump back while FinalStackProbed < StackPtr
1333eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1334eaeb601bSDimitry Andric             .addMBB(bodyMBB)
1335eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1336eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1337eaeb601bSDimitry Andric         bodyMBB->addSuccessor(bodyMBB);
1338eaeb601bSDimitry Andric         bodyMBB->addSuccessor(footMBB);
1339eaeb601bSDimitry Andric       }
1340eaeb601bSDimitry Andric 
1341eaeb601bSDimitry Andric       // setup loop footer
1342eaeb601bSDimitry Andric       {
1343eaeb601bSDimitry Andric         BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1344eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1345eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1346eaeb601bSDimitry Andric         addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1347eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1348eaeb601bSDimitry Andric                      StackPtr, false, 0)
1349eaeb601bSDimitry Andric             .addImm(0)
1350eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1351eaeb601bSDimitry Andric         footMBB->addSuccessor(&MBB);
1352eaeb601bSDimitry Andric       }
1353eaeb601bSDimitry Andric 
1354eaeb601bSDimitry Andric       recomputeLiveIns(*headMBB);
1355eaeb601bSDimitry Andric       recomputeLiveIns(*bodyMBB);
1356eaeb601bSDimitry Andric       recomputeLiveIns(*footMBB);
1357eaeb601bSDimitry Andric       recomputeLiveIns(MBB);
1358eaeb601bSDimitry Andric     }
1359eaeb601bSDimitry Andric   } else {
13600b57cec5SDimitry Andric     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
13610b57cec5SDimitry Andric                            .addReg(Reg)
13620b57cec5SDimitry Andric                            .addImm(Val)
13630b57cec5SDimitry Andric                            .setMIFlag(MachineInstr::FrameSetup);
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric     // The EFLAGS implicit def is dead.
13660b57cec5SDimitry Andric     MI->getOperand(3).setIsDead();
13670b57cec5SDimitry Andric   }
1368eaeb601bSDimitry Andric }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
13710b57cec5SDimitry Andric   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
13720b57cec5SDimitry Andric   // clobbered by any interrupt handler.
13730b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
13740b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
13750b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
13760b57cec5SDimitry Andric   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
13770b57cec5SDimitry Andric   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
13780b57cec5SDimitry Andric }
13790b57cec5SDimitry Andric 
1380d56accc7SDimitry Andric /// Return true if we need to use the restricted Windows x64 prologue and
1381d56accc7SDimitry Andric /// epilogue code patterns that can be described with WinCFI (.seh_*
1382d56accc7SDimitry Andric /// directives).
1383fe6060f1SDimitry Andric bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const {
1384fe6060f1SDimitry Andric   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1385fe6060f1SDimitry Andric }
1386fe6060f1SDimitry Andric 
1387fe6060f1SDimitry Andric bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1388fe6060f1SDimitry Andric   return !isWin64Prologue(MF) && MF.needsFrameMoves();
1389fe6060f1SDimitry Andric }
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric /// emitPrologue - Push callee-saved registers onto the stack, which
13920b57cec5SDimitry Andric /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
13930b57cec5SDimitry Andric /// space for local variables. Also emit labels used by the exception handler to
13940b57cec5SDimitry Andric /// generate the exception handling frames.
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric /*
13970b57cec5SDimitry Andric   Here's a gist of what gets emitted:
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric   ; Establish frame pointer, if needed
14000b57cec5SDimitry Andric   [if needs FP]
14010b57cec5SDimitry Andric       push  %rbp
14020b57cec5SDimitry Andric       .cfi_def_cfa_offset 16
14030b57cec5SDimitry Andric       .cfi_offset %rbp, -16
14040b57cec5SDimitry Andric       .seh_pushreg %rpb
14050b57cec5SDimitry Andric       mov  %rsp, %rbp
14060b57cec5SDimitry Andric       .cfi_def_cfa_register %rbp
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric   ; Spill general-purpose registers
14090b57cec5SDimitry Andric   [for all callee-saved GPRs]
14100b57cec5SDimitry Andric       pushq %<reg>
14110b57cec5SDimitry Andric       [if not needs FP]
14120b57cec5SDimitry Andric          .cfi_def_cfa_offset (offset from RETADDR)
14130b57cec5SDimitry Andric       .seh_pushreg %<reg>
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   ; If the required stack alignment > default stack alignment
14160b57cec5SDimitry Andric   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
14170b57cec5SDimitry Andric   ; of unknown size in the stack frame.
14180b57cec5SDimitry Andric   [if stack needs re-alignment]
14190b57cec5SDimitry Andric       and  $MASK, %rsp
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   ; Allocate space for locals
14220b57cec5SDimitry Andric   [if target is Windows and allocated space > 4096 bytes]
14230b57cec5SDimitry Andric       ; Windows needs special care for allocations larger
14240b57cec5SDimitry Andric       ; than one page.
14250b57cec5SDimitry Andric       mov $NNN, %rax
14260b57cec5SDimitry Andric       call ___chkstk_ms/___chkstk
14270b57cec5SDimitry Andric       sub  %rax, %rsp
14280b57cec5SDimitry Andric   [else]
14290b57cec5SDimitry Andric       sub  $NNN, %rsp
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   [if needs FP]
14320b57cec5SDimitry Andric       .seh_stackalloc (size of XMM spill slots)
14330b57cec5SDimitry Andric       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
14340b57cec5SDimitry Andric   [else]
14350b57cec5SDimitry Andric       .seh_stackalloc NNN
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   ; Spill XMMs
14380b57cec5SDimitry Andric   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
14390b57cec5SDimitry Andric   ; they may get spilled on any platform, if the current function
14400b57cec5SDimitry Andric   ; calls @llvm.eh.unwind.init
14410b57cec5SDimitry Andric   [if needs FP]
14420b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14430b57cec5SDimitry Andric           movaps  %<xmm reg>, -MMM(%rbp)
14440b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14450b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
14460b57cec5SDimitry Andric               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
14470b57cec5SDimitry Andric   [else]
14480b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14490b57cec5SDimitry Andric           movaps  %<xmm reg>, KKK(%rsp)
14500b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14510b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, KKK
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   .seh_endprologue
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   [if needs base pointer]
14560b57cec5SDimitry Andric       mov  %rsp, %rbx
14570b57cec5SDimitry Andric       [if needs to restore base pointer]
14580b57cec5SDimitry Andric           mov %rsp, -MMM(%rbp)
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   ; Emit CFI info
14610b57cec5SDimitry Andric   [if needs FP]
14620b57cec5SDimitry Andric       [for all callee-saved registers]
14630b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rbp)
14640b57cec5SDimitry Andric   [else]
14650b57cec5SDimitry Andric        .cfi_def_cfa_offset (offset from RETADDR)
14660b57cec5SDimitry Andric       [for all callee-saved registers]
14670b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rsp)
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   Notes:
14700b57cec5SDimitry Andric   - .seh directives are emitted only for Windows 64 ABI
14710b57cec5SDimitry Andric   - .cv_fpo directives are emitted on win32 when emitting CodeView
14720b57cec5SDimitry Andric   - .cfi directives are emitted for all other ABIs
14730b57cec5SDimitry Andric   - for 32-bit code, substitute %e?? registers for %r??
14740b57cec5SDimitry Andric */
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric void X86FrameLowering::emitPrologue(MachineFunction &MF,
14770b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
14780b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
14790b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
14800b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
14810b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
14820b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
14830b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
14840b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
14850b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
14860b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
14870b57cec5SDimitry Andric   bool IsFunclet = MBB.isEHFuncletEntry();
14880b57cec5SDimitry Andric   EHPersonality Personality = EHPersonality::Unknown;
14890b57cec5SDimitry Andric   if (Fn.hasPersonalityFn())
14900b57cec5SDimitry Andric     Personality = classifyEHPersonality(Fn.getPersonalityFn());
14910b57cec5SDimitry Andric   bool FnHasClrFunclet =
14920b57cec5SDimitry Andric       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
14930b57cec5SDimitry Andric   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
14940b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
1495fe6060f1SDimitry Andric   bool IsWin64Prologue = isWin64Prologue(MF);
14960b57cec5SDimitry Andric   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
14970b57cec5SDimitry Andric   // FIXME: Emit FPO data for EH funclets.
14980b57cec5SDimitry Andric   bool NeedsWinFPO =
14990b57cec5SDimitry Andric       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
15000b57cec5SDimitry Andric   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1501fe6060f1SDimitry Andric   bool NeedsDwarfCFI = needsDwarfCFI(MF);
15028bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
15038bcb0991SDimitry Andric   const Register MachineFramePtr =
15040b57cec5SDimitry Andric       STI.isTarget64BitILP32()
15058bcb0991SDimitry Andric           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
15068bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
15070b57cec5SDimitry Andric   bool HasWinCFI = false;
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // Debug location must be unknown since the first debug location is used
15100b57cec5SDimitry Andric   // to determine the end of the prologue.
15110b57cec5SDimitry Andric   DebugLoc DL;
15120b57cec5SDimitry Andric 
1513349cc55cSDimitry Andric   // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1514349cc55cSDimitry Andric   // tail call.
1515349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1516349cc55cSDimitry Andric   if (TailCallArgReserveSize  && IsWin64Prologue)
15170b57cec5SDimitry Andric     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
15180b57cec5SDimitry Andric 
15195ffd83dbSDimitry Andric   const bool EmitStackProbeCall =
15205ffd83dbSDimitry Andric       STI.getTargetLowering()->hasStackProbeSymbol(MF);
15218bcb0991SDimitry Andric   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
15220b57cec5SDimitry Andric 
1523fe6060f1SDimitry Andric   if (HasFP && X86FI->hasSwiftAsyncContext()) {
1524349cc55cSDimitry Andric     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1525349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::DeploymentBased:
1526349cc55cSDimitry Andric       if (STI.swiftAsyncContextIsDynamicallySet()) {
1527349cc55cSDimitry Andric         // The special symbol below is absolute and has a *value* suitable to be
1528349cc55cSDimitry Andric         // combined with the frame pointer directly.
1529349cc55cSDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1530349cc55cSDimitry Andric             .addUse(MachineFramePtr)
1531349cc55cSDimitry Andric             .addUse(X86::RIP)
1532349cc55cSDimitry Andric             .addImm(1)
1533349cc55cSDimitry Andric             .addUse(X86::NoRegister)
1534349cc55cSDimitry Andric             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1535349cc55cSDimitry Andric                                X86II::MO_GOTPCREL)
1536349cc55cSDimitry Andric             .addUse(X86::NoRegister);
1537349cc55cSDimitry Andric         break;
1538349cc55cSDimitry Andric       }
1539*bdd1243dSDimitry Andric       [[fallthrough]];
1540349cc55cSDimitry Andric 
1541349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Always:
1542349cc55cSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1543fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
1544fe6060f1SDimitry Andric           .addImm(60)
1545fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
1546349cc55cSDimitry Andric       break;
1547349cc55cSDimitry Andric 
1548349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Never:
1549349cc55cSDimitry Andric       break;
1550349cc55cSDimitry Andric     }
1551fe6060f1SDimitry Andric   }
1552fe6060f1SDimitry Andric 
15530b57cec5SDimitry Andric   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
15540b57cec5SDimitry Andric   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
15550b57cec5SDimitry Andric   // stack alignment.
15560b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
15570b57cec5SDimitry Andric       Fn.arg_size() == 2) {
15580b57cec5SDimitry Andric     StackSize += 8;
15590b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
15600b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -8, /*InEpilogue=*/false);
15610b57cec5SDimitry Andric   }
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
15640b57cec5SDimitry Andric   // function, and use up to 128 bytes of stack space, don't have a frame
15650b57cec5SDimitry Andric   // pointer, calls, or dynamic alloca then we do not need to adjust the
15660b57cec5SDimitry Andric   // stack pointer (we fit in the Red Zone). We also check that we don't
15670b57cec5SDimitry Andric   // push and pop from the stack.
1568fe6060f1SDimitry Andric   if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
15690b57cec5SDimitry Andric       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
15700b57cec5SDimitry Andric       !MFI.adjustsStack() &&                   // No calls.
15715ffd83dbSDimitry Andric       !EmitStackProbeCall &&                   // No stack probes.
15720b57cec5SDimitry Andric       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
15730b57cec5SDimitry Andric       !MF.shouldSplitStack()) {                // Regular stack
1574349cc55cSDimitry Andric     uint64_t MinSize =
1575349cc55cSDimitry Andric         X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta();
15760b57cec5SDimitry Andric     if (HasFP) MinSize += SlotSize;
15770b57cec5SDimitry Andric     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
15780b57cec5SDimitry Andric     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
15790b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
15800b57cec5SDimitry Andric   }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric   // Insert stack pointer adjustment for later moving of return addr.  Only
15830b57cec5SDimitry Andric   // applies to tail call optimized functions where the callee argument stack
15840b57cec5SDimitry Andric   // size is bigger than the callers.
1585349cc55cSDimitry Andric   if (TailCallArgReserveSize != 0) {
1586349cc55cSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
15870b57cec5SDimitry Andric                          /*InEpilogue=*/false)
15880b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
15890b57cec5SDimitry Andric   }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   // Mapping for machine moves:
15920b57cec5SDimitry Andric   //
15930b57cec5SDimitry Andric   //   DST: VirtualFP AND
15940b57cec5SDimitry Andric   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
15950b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_def_cfa
15960b57cec5SDimitry Andric   //
15970b57cec5SDimitry Andric   //   SRC: VirtualFP AND
15980b57cec5SDimitry Andric   //        DST: Register               => DW_CFA_def_cfa_register
15990b57cec5SDimitry Andric   //
16000b57cec5SDimitry Andric   //   ELSE
16010b57cec5SDimitry Andric   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
16020b57cec5SDimitry Andric   //        REG < 64                    => DW_CFA_offset + Reg
16030b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_offset_extended
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   uint64_t NumBytes = 0;
16060b57cec5SDimitry Andric   int stackGrowth = -SlotSize;
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   // Find the funclet establisher parameter
16098bcb0991SDimitry Andric   Register Establisher = X86::NoRegister;
16100b57cec5SDimitry Andric   if (IsClrFunclet)
16110b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
16120b57cec5SDimitry Andric   else if (IsFunclet)
16130b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
16160b57cec5SDimitry Andric     // Immediately spill establisher into the home slot.
16170b57cec5SDimitry Andric     // The runtime cares about this.
16180b57cec5SDimitry Andric     // MOV64mr %rdx, 16(%rsp)
16190b57cec5SDimitry Andric     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
16200b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
16210b57cec5SDimitry Andric         .addReg(Establisher)
16220b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
16230b57cec5SDimitry Andric     MBB.addLiveIn(Establisher);
16240b57cec5SDimitry Andric   }
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   if (HasFP) {
16270b57cec5SDimitry Andric     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric     // Calculate required stack adjustment.
16300b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
16310b57cec5SDimitry Andric     // If required, include space for extra hidden slot for stashing base pointer.
16320b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
16330b57cec5SDimitry Andric       FrameSize += SlotSize;
16340b57cec5SDimitry Andric 
1635349cc55cSDimitry Andric     NumBytes = FrameSize -
1636349cc55cSDimitry Andric                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric     // Callee-saved registers are pushed on stack before the stack is realigned.
1639fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
16400b57cec5SDimitry Andric       NumBytes = alignTo(NumBytes, MaxAlign);
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric     // Save EBP/RBP into the appropriate stack slot.
16430b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
16440b57cec5SDimitry Andric       .addReg(MachineFramePtr, RegState::Kill)
16450b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
16480b57cec5SDimitry Andric       // Mark the place where EBP/RBP was saved.
16490b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
16500b57cec5SDimitry Andric       assert(StackSize);
16510b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
165281ad6265SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(nullptr, -2 * stackGrowth),
165381ad6265SDimitry Andric                MachineInstr::FrameSetup);
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric       // Change the rule for the FramePtr to be an "offset" rule.
16560b57cec5SDimitry Andric       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
165781ad6265SDimitry Andric       BuildCFI(MBB, MBBI, DL,
165881ad6265SDimitry Andric                MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
165981ad6265SDimitry Andric                                               2 * stackGrowth),
166081ad6265SDimitry Andric                MachineInstr::FrameSetup);
16610b57cec5SDimitry Andric     }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric     if (NeedsWinCFI) {
16640b57cec5SDimitry Andric       HasWinCFI = true;
16650b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
16660b57cec5SDimitry Andric           .addImm(FramePtr)
16670b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
16680b57cec5SDimitry Andric     }
16690b57cec5SDimitry Andric 
1670fe6060f1SDimitry Andric     if (!IsFunclet) {
1671fe6060f1SDimitry Andric       if (X86FI->hasSwiftAsyncContext()) {
1672fe6060f1SDimitry Andric         const auto &Attrs = MF.getFunction().getAttributes();
1673fe6060f1SDimitry Andric 
1674fe6060f1SDimitry Andric         // Before we update the live frame pointer we have to ensure there's a
1675fe6060f1SDimitry Andric         // valid (or null) asynchronous context in its slot just before FP in
1676fe6060f1SDimitry Andric         // the frame record, so store it now.
1677fe6060f1SDimitry Andric         if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
1678fe6060f1SDimitry Andric           // We have an initial context in r14, store it just before the frame
1679fe6060f1SDimitry Andric           // pointer.
1680fe6060f1SDimitry Andric           MBB.addLiveIn(X86::R14);
1681fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1682fe6060f1SDimitry Andric               .addReg(X86::R14)
1683fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1684fe6060f1SDimitry Andric         } else {
1685fe6060f1SDimitry Andric           // No initial context, store null so that there's no pointer that
1686fe6060f1SDimitry Andric           // could be misused.
1687fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i8))
1688fe6060f1SDimitry Andric               .addImm(0)
1689fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1690fe6060f1SDimitry Andric         }
1691fe6060f1SDimitry Andric 
1692fe6060f1SDimitry Andric         if (NeedsWinCFI) {
1693fe6060f1SDimitry Andric           HasWinCFI = true;
1694fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1695fe6060f1SDimitry Andric               .addImm(X86::R14)
1696fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1697fe6060f1SDimitry Andric         }
1698fe6060f1SDimitry Andric 
1699fe6060f1SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
1700fe6060f1SDimitry Andric             .addUse(X86::RSP)
1701fe6060f1SDimitry Andric             .addImm(1)
1702fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1703fe6060f1SDimitry Andric             .addImm(8)
1704fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1705fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1706fe6060f1SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri8), X86::RSP)
1707fe6060f1SDimitry Andric             .addUse(X86::RSP)
1708fe6060f1SDimitry Andric             .addImm(8)
1709fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1710fe6060f1SDimitry Andric       }
1711fe6060f1SDimitry Andric 
17120b57cec5SDimitry Andric       if (!IsWin64Prologue && !IsFunclet) {
17130b57cec5SDimitry Andric         // Update EBP with the new base value.
1714fe6060f1SDimitry Andric         if (!X86FI->hasSwiftAsyncContext())
17150b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL,
17160b57cec5SDimitry Andric                   TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
17170b57cec5SDimitry Andric                   FramePtr)
17180b57cec5SDimitry Andric               .addReg(StackPtr)
17190b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric         if (NeedsDwarfCFI) {
17220b57cec5SDimitry Andric           // Mark effective beginning of when frame pointer becomes valid.
17230b57cec5SDimitry Andric           // Define the current CFA to use the EBP/RBP register.
17240b57cec5SDimitry Andric           unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1725fe6060f1SDimitry Andric           BuildCFI(
1726fe6060f1SDimitry Andric               MBB, MBBI, DL,
172781ad6265SDimitry Andric               MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
172881ad6265SDimitry Andric               MachineInstr::FrameSetup);
17290b57cec5SDimitry Andric         }
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric         if (NeedsWinFPO) {
17320b57cec5SDimitry Andric           // .cv_fpo_setframe $FramePtr
17330b57cec5SDimitry Andric           HasWinCFI = true;
17340b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
17350b57cec5SDimitry Andric               .addImm(FramePtr)
17360b57cec5SDimitry Andric               .addImm(0)
17370b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
17380b57cec5SDimitry Andric         }
17390b57cec5SDimitry Andric       }
1740fe6060f1SDimitry Andric     }
17410b57cec5SDimitry Andric   } else {
17420b57cec5SDimitry Andric     assert(!IsFunclet && "funclets without FPs not yet implemented");
1743349cc55cSDimitry Andric     NumBytes = StackSize -
1744349cc55cSDimitry Andric                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
17450b57cec5SDimitry Andric   }
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   // Update the offset adjustment, which is mainly used by codeview to translate
17480b57cec5SDimitry Andric   // from ESP to VFRAME relative local variable offsets.
17490b57cec5SDimitry Andric   if (!IsFunclet) {
1750fe6060f1SDimitry Andric     if (HasFP && TRI->hasStackRealignment(MF))
17510b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-NumBytes);
17520b57cec5SDimitry Andric     else
17530b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-StackSize);
17540b57cec5SDimitry Andric   }
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   // For EH funclets, only allocate enough space for outgoing calls. Save the
17570b57cec5SDimitry Andric   // NumBytes value that we would've used for the parent frame.
17580b57cec5SDimitry Andric   unsigned ParentFrameNumBytes = NumBytes;
17590b57cec5SDimitry Andric   if (IsFunclet)
17600b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   // Skip the callee-saved push instructions.
17630b57cec5SDimitry Andric   bool PushedRegs = false;
17640b57cec5SDimitry Andric   int StackOffset = 2 * stackGrowth;
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric   while (MBBI != MBB.end() &&
17670b57cec5SDimitry Andric          MBBI->getFlag(MachineInstr::FrameSetup) &&
17680b57cec5SDimitry Andric          (MBBI->getOpcode() == X86::PUSH32r ||
17690b57cec5SDimitry Andric           MBBI->getOpcode() == X86::PUSH64r)) {
17700b57cec5SDimitry Andric     PushedRegs = true;
17718bcb0991SDimitry Andric     Register Reg = MBBI->getOperand(0).getReg();
17720b57cec5SDimitry Andric     ++MBBI;
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
17750b57cec5SDimitry Andric       // Mark callee-saved push instruction.
17760b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
17770b57cec5SDimitry Andric       assert(StackSize);
17780b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
177981ad6265SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(nullptr, -StackOffset),
178081ad6265SDimitry Andric                MachineInstr::FrameSetup);
17810b57cec5SDimitry Andric       StackOffset += stackGrowth;
17820b57cec5SDimitry Andric     }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric     if (NeedsWinCFI) {
17850b57cec5SDimitry Andric       HasWinCFI = true;
17860b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
17870b57cec5SDimitry Andric           .addImm(Reg)
17880b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
17890b57cec5SDimitry Andric     }
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Realign stack after we pushed callee-saved registers (so that we'll be
17930b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
17940b57cec5SDimitry Andric   // Don't do this for Win64, it needs to realign the stack after the prologue.
1795fe6060f1SDimitry Andric   if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF)) {
17960b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
17970b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric     if (NeedsWinCFI) {
18000b57cec5SDimitry Andric       HasWinCFI = true;
18010b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
18020b57cec5SDimitry Andric           .addImm(MaxAlign)
18030b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18040b57cec5SDimitry Andric     }
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   // If there is an SUB32ri of ESP immediately before this instruction, merge
18080b57cec5SDimitry Andric   // the two. This can be the case when tail call elimination is enabled and
18090b57cec5SDimitry Andric   // the callee has more arguments then the caller.
18100b57cec5SDimitry Andric   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   // Adjust stack pointer: ESP -= numbytes.
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Windows and cygwin/mingw require a prologue helper routine when allocating
18150b57cec5SDimitry Andric   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
18160b57cec5SDimitry Andric   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
18170b57cec5SDimitry Andric   // stack and adjust the stack pointer in one go.  The 64-bit version of
18180b57cec5SDimitry Andric   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
18190b57cec5SDimitry Andric   // responsible for adjusting the stack pointer.  Touching the stack at 4K
18200b57cec5SDimitry Andric   // increments is necessary to ensure that the guard pages used by the OS
18210b57cec5SDimitry Andric   // virtual memory manager are allocated in correct sequence.
18220b57cec5SDimitry Andric   uint64_t AlignedNumBytes = NumBytes;
1823fe6060f1SDimitry Andric   if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
18240b57cec5SDimitry Andric     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
18255ffd83dbSDimitry Andric   if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
18260b57cec5SDimitry Andric     assert(!X86FI->getUsesRedZone() &&
18270b57cec5SDimitry Andric            "The Red Zone is not accounted for in stack probes");
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric     // Check whether EAX is livein for this block.
18300b57cec5SDimitry Andric     bool isEAXAlive = isEAXLiveIn(MBB);
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric     if (isEAXAlive) {
18330b57cec5SDimitry Andric       if (Is64Bit) {
18340b57cec5SDimitry Andric         // Save RAX
18350b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
18360b57cec5SDimitry Andric           .addReg(X86::RAX, RegState::Kill)
18370b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18380b57cec5SDimitry Andric       } else {
18390b57cec5SDimitry Andric         // Save EAX
18400b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
18410b57cec5SDimitry Andric           .addReg(X86::EAX, RegState::Kill)
18420b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18430b57cec5SDimitry Andric       }
18440b57cec5SDimitry Andric     }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric     if (Is64Bit) {
18470b57cec5SDimitry Andric       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
18480b57cec5SDimitry Andric       // Function prologue is responsible for adjusting the stack pointer.
1849480093f4SDimitry Andric       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
185004eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Alloc)), X86::RAX)
18510b57cec5SDimitry Andric           .addImm(Alloc)
18520b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18530b57cec5SDimitry Andric     } else {
18540b57cec5SDimitry Andric       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
18550b57cec5SDimitry Andric       // We'll also use 4 already allocated bytes for EAX.
18560b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
18570b57cec5SDimitry Andric           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
18580b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18590b57cec5SDimitry Andric     }
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric     // Call __chkstk, __chkstk_ms, or __alloca.
18620b57cec5SDimitry Andric     emitStackProbe(MF, MBB, MBBI, DL, true);
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric     if (isEAXAlive) {
18650b57cec5SDimitry Andric       // Restore RAX/EAX
18660b57cec5SDimitry Andric       MachineInstr *MI;
18670b57cec5SDimitry Andric       if (Is64Bit)
18680b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
18690b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 8);
18700b57cec5SDimitry Andric       else
18710b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
18720b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 4);
18730b57cec5SDimitry Andric       MI->setFlag(MachineInstr::FrameSetup);
18740b57cec5SDimitry Andric       MBB.insert(MBBI, MI);
18750b57cec5SDimitry Andric     }
18760b57cec5SDimitry Andric   } else if (NumBytes) {
18770b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
18780b57cec5SDimitry Andric   }
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   if (NeedsWinCFI && NumBytes) {
18810b57cec5SDimitry Andric     HasWinCFI = true;
18820b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
18830b57cec5SDimitry Andric         .addImm(NumBytes)
18840b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
18850b57cec5SDimitry Andric   }
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric   int SEHFrameOffset = 0;
18880b57cec5SDimitry Andric   unsigned SPOrEstablisher;
18890b57cec5SDimitry Andric   if (IsFunclet) {
18900b57cec5SDimitry Andric     if (IsClrFunclet) {
18910b57cec5SDimitry Andric       // The establisher parameter passed to a CLR funclet is actually a pointer
18920b57cec5SDimitry Andric       // to the (mostly empty) frame of its nearest enclosing funclet; we have
18930b57cec5SDimitry Andric       // to find the root function establisher frame by loading the PSPSym from
18940b57cec5SDimitry Andric       // the intermediate frame.
18950b57cec5SDimitry Andric       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
18960b57cec5SDimitry Andric       MachinePointerInfo NoInfo;
18970b57cec5SDimitry Andric       MBB.addLiveIn(Establisher);
18980b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
18990b57cec5SDimitry Andric                    Establisher, false, PSPSlotOffset)
19000b57cec5SDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
19015ffd83dbSDimitry Andric               NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize)));
19020b57cec5SDimitry Andric       ;
19030b57cec5SDimitry Andric       // Save the root establisher back into the current funclet's (mostly
19040b57cec5SDimitry Andric       // empty) frame, in case a sub-funclet or the GC needs it.
19050b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
19060b57cec5SDimitry Andric                    false, PSPSlotOffset)
19070b57cec5SDimitry Andric           .addReg(Establisher)
19085ffd83dbSDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
19095ffd83dbSDimitry Andric               NoInfo,
19105ffd83dbSDimitry Andric               MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
19115ffd83dbSDimitry Andric               SlotSize, Align(SlotSize)));
19120b57cec5SDimitry Andric     }
19130b57cec5SDimitry Andric     SPOrEstablisher = Establisher;
19140b57cec5SDimitry Andric   } else {
19150b57cec5SDimitry Andric     SPOrEstablisher = StackPtr;
19160b57cec5SDimitry Andric   }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric   if (IsWin64Prologue && HasFP) {
19190b57cec5SDimitry Andric     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
19200b57cec5SDimitry Andric     // this calculation on the incoming establisher, which holds the value of
19210b57cec5SDimitry Andric     // RSP from the parent frame at the end of the prologue.
19220b57cec5SDimitry Andric     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
19230b57cec5SDimitry Andric     if (SEHFrameOffset)
19240b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
19250b57cec5SDimitry Andric                    SPOrEstablisher, false, SEHFrameOffset);
19260b57cec5SDimitry Andric     else
19270b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
19280b57cec5SDimitry Andric           .addReg(SPOrEstablisher);
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric     // If this is not a funclet, emit the CFI describing our frame pointer.
19310b57cec5SDimitry Andric     if (NeedsWinCFI && !IsFunclet) {
19320b57cec5SDimitry Andric       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
19330b57cec5SDimitry Andric       HasWinCFI = true;
19340b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
19350b57cec5SDimitry Andric           .addImm(FramePtr)
19360b57cec5SDimitry Andric           .addImm(SEHFrameOffset)
19370b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19380b57cec5SDimitry Andric       if (isAsynchronousEHPersonality(Personality))
19390b57cec5SDimitry Andric         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
19400b57cec5SDimitry Andric     }
19410b57cec5SDimitry Andric   } else if (IsFunclet && STI.is32Bit()) {
19420b57cec5SDimitry Andric     // Reset EBP / ESI to something good for funclets.
19430b57cec5SDimitry Andric     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
19440b57cec5SDimitry Andric     // If we're a catch funclet, we can be returned to via catchret. Save ESP
19450b57cec5SDimitry Andric     // into the registration node so that the runtime will restore it for us.
19460b57cec5SDimitry Andric     if (!MBB.isCleanupFuncletEntry()) {
19470b57cec5SDimitry Andric       assert(Personality == EHPersonality::MSVC_CXX);
19485ffd83dbSDimitry Andric       Register FrameReg;
19490b57cec5SDimitry Andric       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
1950e8d8bef9SDimitry Andric       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
19510b57cec5SDimitry Andric       // ESP is the first field, so no extra displacement is needed.
19520b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
19530b57cec5SDimitry Andric                    false, EHRegOffset)
19540b57cec5SDimitry Andric           .addReg(X86::ESP);
19550b57cec5SDimitry Andric     }
19560b57cec5SDimitry Andric   }
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
19590b57cec5SDimitry Andric     const MachineInstr &FrameInstr = *MBBI;
19600b57cec5SDimitry Andric     ++MBBI;
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric     if (NeedsWinCFI) {
19630b57cec5SDimitry Andric       int FI;
19640b57cec5SDimitry Andric       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
19650b57cec5SDimitry Andric         if (X86::FR64RegClass.contains(Reg)) {
1966c14a5a88SDimitry Andric           int Offset;
19675ffd83dbSDimitry Andric           Register IgnoredFrameReg;
1968c14a5a88SDimitry Andric           if (IsWin64Prologue && IsFunclet)
1969c14a5a88SDimitry Andric             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
1970c14a5a88SDimitry Andric           else
1971e8d8bef9SDimitry Andric             Offset =
1972e8d8bef9SDimitry Andric                 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
1973c14a5a88SDimitry Andric                 SEHFrameOffset;
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric           HasWinCFI = true;
19760b57cec5SDimitry Andric           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
19770b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
19780b57cec5SDimitry Andric               .addImm(Reg)
19790b57cec5SDimitry Andric               .addImm(Offset)
19800b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
19810b57cec5SDimitry Andric         }
19820b57cec5SDimitry Andric       }
19830b57cec5SDimitry Andric     }
19840b57cec5SDimitry Andric   }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   if (NeedsWinCFI && HasWinCFI)
19870b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
19880b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric   if (FnHasClrFunclet && !IsFunclet) {
19910b57cec5SDimitry Andric     // Save the so-called Initial-SP (i.e. the value of the stack pointer
19920b57cec5SDimitry Andric     // immediately after the prolog)  into the PSPSlot so that funclets
19930b57cec5SDimitry Andric     // and the GC can recover it.
19940b57cec5SDimitry Andric     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
19950b57cec5SDimitry Andric     auto PSPInfo = MachinePointerInfo::getFixedStack(
19960b57cec5SDimitry Andric         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
19970b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
19980b57cec5SDimitry Andric                  PSPSlotOffset)
19990b57cec5SDimitry Andric         .addReg(StackPtr)
20000b57cec5SDimitry Andric         .addMemOperand(MF.getMachineMemOperand(
20010b57cec5SDimitry Andric             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
20025ffd83dbSDimitry Andric             SlotSize, Align(SlotSize)));
20030b57cec5SDimitry Andric   }
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric   // Realign stack after we spilled callee-saved registers (so that we'll be
20060b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
20070b57cec5SDimitry Andric   // Win64 requires aligning the stack after the prologue.
2008fe6060f1SDimitry Andric   if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
20090b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
20100b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
20110b57cec5SDimitry Andric   }
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   // We already dealt with stack realignment and funclets above.
20140b57cec5SDimitry Andric   if (IsFunclet && STI.is32Bit())
20150b57cec5SDimitry Andric     return;
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
20180b57cec5SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
20190b57cec5SDimitry Andric   // will be allocated after this, so we can still use the base pointer
20200b57cec5SDimitry Andric   // to reference locals.
20210b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
20220b57cec5SDimitry Andric     // Update the base pointer with the current stack pointer.
20230b57cec5SDimitry Andric     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
20240b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
20250b57cec5SDimitry Andric       .addReg(SPOrEstablisher)
20260b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
20270b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer()) {
20280b57cec5SDimitry Andric       // Stash value of base pointer.  Saving RSP instead of EBP shortens
20290b57cec5SDimitry Andric       // dependence chain. Used by SjLj EH.
20300b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
20310b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
20320b57cec5SDimitry Andric                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
20330b57cec5SDimitry Andric         .addReg(SPOrEstablisher)
20340b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
20350b57cec5SDimitry Andric     }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
20380b57cec5SDimitry Andric       // Stash the value of the frame pointer relative to the base pointer for
20390b57cec5SDimitry Andric       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
20400b57cec5SDimitry Andric       // it recovers the frame pointer from the base pointer rather than the
20410b57cec5SDimitry Andric       // other way around.
20420b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
20435ffd83dbSDimitry Andric       Register UsedReg;
20440b57cec5SDimitry Andric       int Offset =
2045e8d8bef9SDimitry Andric           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2046e8d8bef9SDimitry Andric               .getFixed();
20470b57cec5SDimitry Andric       assert(UsedReg == BasePtr);
20480b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
20490b57cec5SDimitry Andric           .addReg(FramePtr)
20500b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
20510b57cec5SDimitry Andric     }
20520b57cec5SDimitry Andric   }
20530b57cec5SDimitry Andric 
20540b57cec5SDimitry Andric   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
20550b57cec5SDimitry Andric     // Mark end of stack pointer adjustment.
20560b57cec5SDimitry Andric     if (!HasFP && NumBytes) {
20570b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
20580b57cec5SDimitry Andric       assert(StackSize);
20595ffd83dbSDimitry Andric       BuildCFI(
20605ffd83dbSDimitry Andric           MBB, MBBI, DL,
206181ad6265SDimitry Andric           MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
206281ad6265SDimitry Andric           MachineInstr::FrameSetup);
20630b57cec5SDimitry Andric     }
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric     // Emit DWARF info specifying the offsets of the callee-saved registers.
20665ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DL, true);
20670b57cec5SDimitry Andric   }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric   // X86 Interrupt handling function cannot assume anything about the direction
20700b57cec5SDimitry Andric   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
20710b57cec5SDimitry Andric   // in each prologue of interrupt handler function.
20720b57cec5SDimitry Andric   //
20730b57cec5SDimitry Andric   // FIXME: Create "cld" instruction only in these cases:
20740b57cec5SDimitry Andric   // 1. The interrupt handling function uses any of the "rep" instructions.
20750b57cec5SDimitry Andric   // 2. Interrupt handling function calls another function.
20760b57cec5SDimitry Andric   //
20770b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR)
20780b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
20790b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric   // At this point we know if the function has WinCFI or not.
20820b57cec5SDimitry Andric   MF.setHasWinCFI(HasWinCFI);
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric bool X86FrameLowering::canUseLEAForSPInEpilogue(
20860b57cec5SDimitry Andric     const MachineFunction &MF) const {
20870b57cec5SDimitry Andric   // We can't use LEA instructions for adjusting the stack pointer if we don't
20880b57cec5SDimitry Andric   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
20890b57cec5SDimitry Andric   // to deallocate the stack.
20900b57cec5SDimitry Andric   // This means that we can use LEA for SP in two situations:
20910b57cec5SDimitry Andric   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
20920b57cec5SDimitry Andric   // 2. We *have* a frame pointer which means we are permitted to use LEA.
20930b57cec5SDimitry Andric   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
20940b57cec5SDimitry Andric }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric static bool isFuncletReturnInstr(MachineInstr &MI) {
20970b57cec5SDimitry Andric   switch (MI.getOpcode()) {
20980b57cec5SDimitry Andric   case X86::CATCHRET:
20990b57cec5SDimitry Andric   case X86::CLEANUPRET:
21000b57cec5SDimitry Andric     return true;
21010b57cec5SDimitry Andric   default:
21020b57cec5SDimitry Andric     return false;
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric   llvm_unreachable("impossible");
21050b57cec5SDimitry Andric }
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
21080b57cec5SDimitry Andric // stack. It holds a pointer to the bottom of the root function frame.  The
21090b57cec5SDimitry Andric // establisher frame pointer passed to a nested funclet may point to the
21100b57cec5SDimitry Andric // (mostly empty) frame of its parent funclet, but it will need to find
21110b57cec5SDimitry Andric // the frame of the root function to access locals.  To facilitate this,
21120b57cec5SDimitry Andric // every funclet copies the pointer to the bottom of the root function
21130b57cec5SDimitry Andric // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
21140b57cec5SDimitry Andric // same offset for the PSPSym in the root function frame that's used in the
21150b57cec5SDimitry Andric // funclets' frames allows each funclet to dynamically accept any ancestor
21160b57cec5SDimitry Andric // frame as its establisher argument (the runtime doesn't guarantee the
21170b57cec5SDimitry Andric // immediate parent for some reason lost to history), and also allows the GC,
21180b57cec5SDimitry Andric // which uses the PSPSym for some bookkeeping, to find it in any funclet's
21190b57cec5SDimitry Andric // frame with only a single offset reported for the entire method.
21200b57cec5SDimitry Andric unsigned
21210b57cec5SDimitry Andric X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
21220b57cec5SDimitry Andric   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
21235ffd83dbSDimitry Andric   Register SPReg;
21240b57cec5SDimitry Andric   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2125e8d8bef9SDimitry Andric                                               /*IgnoreSPUpdates*/ true)
2126e8d8bef9SDimitry Andric                    .getFixed();
21270b57cec5SDimitry Andric   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
21280b57cec5SDimitry Andric   return static_cast<unsigned>(Offset);
21290b57cec5SDimitry Andric }
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric unsigned
21320b57cec5SDimitry Andric X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2133c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
21340b57cec5SDimitry Andric   // This is the size of the pushed CSRs.
2135c14a5a88SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2136c14a5a88SDimitry Andric   // This is the size of callee saved XMMs.
2137c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2138c14a5a88SDimitry Andric   unsigned XMMSize = WinEHXMMSlotInfo.size() *
2139c14a5a88SDimitry Andric                      TRI->getSpillSize(X86::VR128RegClass);
21400b57cec5SDimitry Andric   // This is the amount of stack a funclet needs to allocate.
21410b57cec5SDimitry Andric   unsigned UsedSize;
21420b57cec5SDimitry Andric   EHPersonality Personality =
21430b57cec5SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn());
21440b57cec5SDimitry Andric   if (Personality == EHPersonality::CoreCLR) {
21450b57cec5SDimitry Andric     // CLR funclets need to hold enough space to include the PSPSym, at the
21460b57cec5SDimitry Andric     // same offset from the stack pointer (immediately after the prolog) as it
21470b57cec5SDimitry Andric     // resides at in the main function.
21480b57cec5SDimitry Andric     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
21490b57cec5SDimitry Andric   } else {
21500b57cec5SDimitry Andric     // Other funclets just need enough stack for outgoing call arguments.
21510b57cec5SDimitry Andric     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
21520b57cec5SDimitry Andric   }
21530b57cec5SDimitry Andric   // RBP is not included in the callee saved register block. After pushing RBP,
21540b57cec5SDimitry Andric   // everything is 16 byte aligned. Everything we allocate before an outgoing
21550b57cec5SDimitry Andric   // call must also be 16 byte aligned.
21565ffd83dbSDimitry Andric   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
21570b57cec5SDimitry Andric   // Subtract out the size of the callee saved registers. This is how much stack
21580b57cec5SDimitry Andric   // each funclet will allocate.
2159c14a5a88SDimitry Andric   return FrameSizeMinusRBP + XMMSize - CSSize;
21600b57cec5SDimitry Andric }
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric static bool isTailCallOpcode(unsigned Opc) {
21630b57cec5SDimitry Andric     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
21640b57cec5SDimitry Andric         Opc == X86::TCRETURNmi ||
21650b57cec5SDimitry Andric         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
21660b57cec5SDimitry Andric         Opc == X86::TCRETURNmi64;
21670b57cec5SDimitry Andric }
21680b57cec5SDimitry Andric 
21690b57cec5SDimitry Andric void X86FrameLowering::emitEpilogue(MachineFunction &MF,
21700b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
21710b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
21720b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
21730b57cec5SDimitry Andric   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
21740b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = Terminator;
21750b57cec5SDimitry Andric   DebugLoc DL;
21760b57cec5SDimitry Andric   if (MBBI != MBB.end())
21770b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
21780b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
21790b57cec5SDimitry Andric   const bool Is64BitILP32 = STI.isTarget64BitILP32();
21808bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
2181e8d8bef9SDimitry Andric   Register MachineFramePtr =
21828bcb0991SDimitry Andric       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
21850b57cec5SDimitry Andric   bool NeedsWin64CFI =
21860b57cec5SDimitry Andric       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
21870b57cec5SDimitry Andric   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric   // Get the number of bytes to allocate from the FrameInfo.
21900b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
21910b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF);
21920b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2193349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
21940b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
21950b57cec5SDimitry Andric   uint64_t NumBytes = 0;
21960b57cec5SDimitry Andric 
2197480093f4SDimitry Andric   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
21980b57cec5SDimitry Andric                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
2199480093f4SDimitry Andric                        MF.needsFrameMoves();
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   if (IsFunclet) {
22020b57cec5SDimitry Andric     assert(HasFP && "EH funclets without FP not yet implemented");
22030b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
22040b57cec5SDimitry Andric   } else if (HasFP) {
22050b57cec5SDimitry Andric     // Calculate required stack adjustment.
22060b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
2207349cc55cSDimitry Andric     NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric     // Callee-saved registers were pushed on stack before the stack was
22100b57cec5SDimitry Andric     // realigned.
2211fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
22120b57cec5SDimitry Andric       NumBytes = alignTo(FrameSize, MaxAlign);
22130b57cec5SDimitry Andric   } else {
2214349cc55cSDimitry Andric     NumBytes = StackSize - CSSize - TailCallArgReserveSize;
22150b57cec5SDimitry Andric   }
22160b57cec5SDimitry Andric   uint64_t SEHStackAllocAmt = NumBytes;
22170b57cec5SDimitry Andric 
22185ffd83dbSDimitry Andric   // AfterPop is the position to insert .cfi_restore.
22195ffd83dbSDimitry Andric   MachineBasicBlock::iterator AfterPop = MBBI;
22200b57cec5SDimitry Andric   if (HasFP) {
2221fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2222fe6060f1SDimitry Andric       // Discard the context.
2223fe6060f1SDimitry Andric       int Offset = 16 + mergeSPUpdates(MBB, MBBI, true);
2224fe6060f1SDimitry Andric       emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/true);
2225fe6060f1SDimitry Andric     }
22260b57cec5SDimitry Andric     // Pop EBP.
22270b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
22280b57cec5SDimitry Andric             MachineFramePtr)
22290b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
2230fe6060f1SDimitry Andric 
2231fe6060f1SDimitry Andric     // We need to reset FP to its untagged state on return. Bit 60 is currently
2232fe6060f1SDimitry Andric     // used to show the presence of an extended frame.
2233fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2234fe6060f1SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8),
2235fe6060f1SDimitry Andric               MachineFramePtr)
2236fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
2237fe6060f1SDimitry Andric           .addImm(60)
2238fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameDestroy);
2239fe6060f1SDimitry Andric     }
2240fe6060f1SDimitry Andric 
22410b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
22420b57cec5SDimitry Andric       unsigned DwarfStackPtr =
22430b57cec5SDimitry Andric           TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
22445ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
224581ad6265SDimitry Andric                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
224681ad6265SDimitry Andric                MachineInstr::FrameDestroy);
22475ffd83dbSDimitry Andric       if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
22485ffd83dbSDimitry Andric         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
22495ffd83dbSDimitry Andric         BuildCFI(MBB, AfterPop, DL,
225081ad6265SDimitry Andric                  MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
225181ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
22525ffd83dbSDimitry Andric         --MBBI;
22535ffd83dbSDimitry Andric         --AfterPop;
22545ffd83dbSDimitry Andric       }
22550b57cec5SDimitry Andric       --MBBI;
22560b57cec5SDimitry Andric     }
22570b57cec5SDimitry Andric   }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   MachineBasicBlock::iterator FirstCSPop = MBBI;
22600b57cec5SDimitry Andric   // Skip the callee-saved pop instructions.
22610b57cec5SDimitry Andric   while (MBBI != MBB.begin()) {
22620b57cec5SDimitry Andric     MachineBasicBlock::iterator PI = std::prev(MBBI);
22630b57cec5SDimitry Andric     unsigned Opc = PI->getOpcode();
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
22660b57cec5SDimitry Andric       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2267fe6060f1SDimitry Andric           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2268fe6060f1SDimitry Andric           (Opc != X86::BTR64ri8 || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2269fe6060f1SDimitry Andric           (Opc != X86::ADD64ri8 || !PI->getFlag(MachineInstr::FrameDestroy)))
22700b57cec5SDimitry Andric         break;
22710b57cec5SDimitry Andric       FirstCSPop = PI;
22720b57cec5SDimitry Andric     }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric     --MBBI;
22750b57cec5SDimitry Andric   }
22760b57cec5SDimitry Andric   MBBI = FirstCSPop;
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
22790b57cec5SDimitry Andric     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   if (MBBI != MBB.end())
22820b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
22830b57cec5SDimitry Andric   // If there is an ADD32ri or SUB32ri of ESP immediately before this
22840b57cec5SDimitry Andric   // instruction, merge the two instructions.
22850b57cec5SDimitry Andric   if (NumBytes || MFI.hasVarSizedObjects())
22860b57cec5SDimitry Andric     NumBytes += mergeSPUpdates(MBB, MBBI, true);
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric   // If dynamic alloca is used, then reset esp to point to the last callee-saved
22890b57cec5SDimitry Andric   // slot before popping them off! Same applies for the case, when stack was
22900b57cec5SDimitry Andric   // realigned. Don't do this if this was a funclet epilogue, since the funclets
22910b57cec5SDimitry Andric   // will not do realignment or dynamic stack allocation.
2292fe6060f1SDimitry Andric   if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
22930b57cec5SDimitry Andric       !IsFunclet) {
2294fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF))
22950b57cec5SDimitry Andric       MBBI = FirstCSPop;
22960b57cec5SDimitry Andric     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
22970b57cec5SDimitry Andric     uint64_t LEAAmount =
22980b57cec5SDimitry Andric         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
22990b57cec5SDimitry Andric 
2300fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext())
2301fe6060f1SDimitry Andric       LEAAmount -= 16;
2302fe6060f1SDimitry Andric 
23030b57cec5SDimitry Andric     // There are only two legal forms of epilogue:
23040b57cec5SDimitry Andric     // - add SEHAllocationSize, %rsp
23050b57cec5SDimitry Andric     // - lea SEHAllocationSize(%FramePtr), %rsp
23060b57cec5SDimitry Andric     //
23070b57cec5SDimitry Andric     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
23080b57cec5SDimitry Andric     // However, we may use this sequence if we have a frame pointer because the
23090b57cec5SDimitry Andric     // effects of the prologue can safely be undone.
23100b57cec5SDimitry Andric     if (LEAAmount != 0) {
23110b57cec5SDimitry Andric       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
23120b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
23130b57cec5SDimitry Andric                    FramePtr, false, LEAAmount);
23140b57cec5SDimitry Andric       --MBBI;
23150b57cec5SDimitry Andric     } else {
23160b57cec5SDimitry Andric       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
23170b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
23180b57cec5SDimitry Andric         .addReg(FramePtr);
23190b57cec5SDimitry Andric       --MBBI;
23200b57cec5SDimitry Andric     }
23210b57cec5SDimitry Andric   } else if (NumBytes) {
23220b57cec5SDimitry Andric     // Adjust stack pointer back: ESP += numbytes.
23230b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2324349cc55cSDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
23250b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
23265ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
2327349cc55cSDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(
232881ad6265SDimitry Andric                    nullptr, CSSize + TailCallArgReserveSize + SlotSize),
232981ad6265SDimitry Andric                MachineInstr::FrameDestroy);
23300b57cec5SDimitry Andric     }
23310b57cec5SDimitry Andric     --MBBI;
23320b57cec5SDimitry Andric   }
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric   // Windows unwinder will not invoke function's exception handler if IP is
23350b57cec5SDimitry Andric   // either in prologue or in epilogue.  This behavior causes a problem when a
23360b57cec5SDimitry Andric   // call immediately precedes an epilogue, because the return address points
23370b57cec5SDimitry Andric   // into the epilogue.  To cope with that, we insert an epilogue marker here,
23380b57cec5SDimitry Andric   // then replace it with a 'nop' if it ends up immediately after a CALL in the
23390b57cec5SDimitry Andric   // final emitted code.
23400b57cec5SDimitry Andric   if (NeedsWin64CFI && MF.hasWinCFI())
23410b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
23420b57cec5SDimitry Andric 
2343349cc55cSDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
23440b57cec5SDimitry Andric     MBBI = FirstCSPop;
23450b57cec5SDimitry Andric     int64_t Offset = -CSSize - SlotSize;
23460b57cec5SDimitry Andric     // Mark callee-saved pop instruction.
23470b57cec5SDimitry Andric     // Define the current CFA rule to use the provided offset.
23480b57cec5SDimitry Andric     while (MBBI != MBB.end()) {
23490b57cec5SDimitry Andric       MachineBasicBlock::iterator PI = MBBI;
23500b57cec5SDimitry Andric       unsigned Opc = PI->getOpcode();
23510b57cec5SDimitry Andric       ++MBBI;
23520b57cec5SDimitry Andric       if (Opc == X86::POP32r || Opc == X86::POP64r) {
23530b57cec5SDimitry Andric         Offset += SlotSize;
23540b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
235581ad6265SDimitry Andric                  MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset),
235681ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
23570b57cec5SDimitry Andric       }
23580b57cec5SDimitry Andric     }
23590b57cec5SDimitry Andric   }
23600b57cec5SDimitry Andric 
23615ffd83dbSDimitry Andric   // Emit DWARF info specifying the restores of the callee-saved registers.
23625ffd83dbSDimitry Andric   // For epilogue with return inside or being other block without successor,
23635ffd83dbSDimitry Andric   // no need to generate .cfi_restore for callee-saved registers.
2364349cc55cSDimitry Andric   if (NeedsDwarfCFI && !MBB.succ_empty())
23655ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
23665ffd83dbSDimitry Andric 
23670b57cec5SDimitry Andric   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
23680b57cec5SDimitry Andric     // Add the return addr area delta back since we are not tail calling.
23690b57cec5SDimitry Andric     int Offset = -1 * X86FI->getTCReturnAddrDelta();
23700b57cec5SDimitry Andric     assert(Offset >= 0 && "TCDelta should never be positive");
23710b57cec5SDimitry Andric     if (Offset) {
23720b57cec5SDimitry Andric       // Check for possible merge with preceding ADD instruction.
23730b57cec5SDimitry Andric       Offset += mergeSPUpdates(MBB, Terminator, true);
23740b57cec5SDimitry Andric       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
23750b57cec5SDimitry Andric     }
23760b57cec5SDimitry Andric   }
2377e8d8bef9SDimitry Andric 
2378e8d8bef9SDimitry Andric   // Emit tilerelease for AMX kernel.
2379349cc55cSDimitry Andric   if (X86FI->hasVirtualTileReg())
2380e8d8bef9SDimitry Andric     BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
2383e8d8bef9SDimitry Andric StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF,
2384e8d8bef9SDimitry Andric                                                      int FI,
23855ffd83dbSDimitry Andric                                                      Register &FrameReg) const {
23860b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
23870b57cec5SDimitry Andric 
23880b57cec5SDimitry Andric   bool IsFixed = MFI.isFixedObjectIndex(FI);
23890b57cec5SDimitry Andric   // We can't calculate offset from frame pointer if the stack is realigned,
23900b57cec5SDimitry Andric   // so enforce usage of stack/base pointer.  The base pointer is used when we
23910b57cec5SDimitry Andric   // have dynamic allocas in addition to dynamic realignment.
23920b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF))
23930b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2394fe6060f1SDimitry Andric   else if (TRI->hasStackRealignment(MF))
23950b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
23960b57cec5SDimitry Andric   else
23970b57cec5SDimitry Andric     FrameReg = TRI->getFrameRegister(MF);
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric   // Offset will hold the offset from the stack pointer at function entry to the
24000b57cec5SDimitry Andric   // object.
24010b57cec5SDimitry Andric   // We need to factor in additional offsets applied during the prologue to the
24020b57cec5SDimitry Andric   // frame, base, and stack pointer depending on which is used.
24030b57cec5SDimitry Andric   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
24040b57cec5SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
24050b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
24060b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
24070b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
24080b57cec5SDimitry Andric   int64_t FPDelta = 0;
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   // In an x86 interrupt, remove the offset we added to account for the return
24110b57cec5SDimitry Andric   // address from any stack object allocated in the caller's frame. Interrupts
24120b57cec5SDimitry Andric   // do not have a standard return address. Fixed objects in the current frame,
24130b57cec5SDimitry Andric   // such as SSE register spills, should not get this treatment.
24140b57cec5SDimitry Andric   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
24150b57cec5SDimitry Andric       Offset >= 0) {
24160b57cec5SDimitry Andric     Offset += getOffsetOfLocalArea();
24170b57cec5SDimitry Andric   }
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   if (IsWin64Prologue) {
24200b57cec5SDimitry Andric     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric     // Calculate required stack adjustment.
24230b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
24240b57cec5SDimitry Andric     // If required, include space for extra hidden slot for stashing base pointer.
24250b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
24260b57cec5SDimitry Andric       FrameSize += SlotSize;
24270b57cec5SDimitry Andric     uint64_t NumBytes = FrameSize - CSSize;
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
24300b57cec5SDimitry Andric     if (FI && FI == X86FI->getFAIndex())
2431e8d8bef9SDimitry Andric       return StackOffset::getFixed(-SEHFrameOffset);
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric     // FPDelta is the offset from the "traditional" FP location of the old base
24340b57cec5SDimitry Andric     // pointer followed by return address and the location required by the
24350b57cec5SDimitry Andric     // restricted Win64 prologue.
24360b57cec5SDimitry Andric     // Add FPDelta to all offsets below that go through the frame pointer.
24370b57cec5SDimitry Andric     FPDelta = FrameSize - SEHFrameOffset;
24380b57cec5SDimitry Andric     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
24390b57cec5SDimitry Andric            "FPDelta isn't aligned per the Win64 ABI!");
24400b57cec5SDimitry Andric   }
24410b57cec5SDimitry Andric 
2442349cc55cSDimitry Andric   if (FrameReg == TRI->getFramePtr()) {
2443349cc55cSDimitry Andric     // Skip saved EBP/RBP
24440b57cec5SDimitry Andric     Offset += SlotSize;
24450b57cec5SDimitry Andric 
2446349cc55cSDimitry Andric     // Account for restricted Windows prologue.
2447349cc55cSDimitry Andric     Offset += FPDelta;
2448349cc55cSDimitry Andric 
24490b57cec5SDimitry Andric     // Skip the RETADDR move area
24500b57cec5SDimitry Andric     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
24510b57cec5SDimitry Andric     if (TailCallReturnAddrDelta < 0)
24520b57cec5SDimitry Andric       Offset -= TailCallReturnAddrDelta;
2453349cc55cSDimitry Andric 
2454349cc55cSDimitry Andric     return StackOffset::getFixed(Offset);
24550b57cec5SDimitry Andric   }
24560b57cec5SDimitry Andric 
2457349cc55cSDimitry Andric   // FrameReg is either the stack pointer or a base pointer. But the base is
2458349cc55cSDimitry Andric   // located at the end of the statically known StackSize so the distinction
2459349cc55cSDimitry Andric   // doesn't really matter.
2460349cc55cSDimitry Andric   if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
2461349cc55cSDimitry Andric     assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2462349cc55cSDimitry Andric   return StackOffset::getFixed(Offset + StackSize);
24630b57cec5SDimitry Andric }
24640b57cec5SDimitry Andric 
24655ffd83dbSDimitry Andric int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI,
24665ffd83dbSDimitry Andric                                               Register &FrameReg) const {
2467c14a5a88SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
2468c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2469c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2470c14a5a88SDimitry Andric   const auto it = WinEHXMMSlotInfo.find(FI);
2471c14a5a88SDimitry Andric 
2472c14a5a88SDimitry Andric   if (it == WinEHXMMSlotInfo.end())
2473e8d8bef9SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg).getFixed();
2474c14a5a88SDimitry Andric 
2475c14a5a88SDimitry Andric   FrameReg = TRI->getStackRegister();
24765ffd83dbSDimitry Andric   return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
24775ffd83dbSDimitry Andric          it->second;
2478c14a5a88SDimitry Andric }
2479c14a5a88SDimitry Andric 
2480e8d8bef9SDimitry Andric StackOffset
2481e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI,
2482e8d8bef9SDimitry Andric                                            Register &FrameReg,
24830b57cec5SDimitry Andric                                            int Adjustment) const {
24840b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
24850b57cec5SDimitry Andric   FrameReg = TRI->getStackRegister();
2486e8d8bef9SDimitry Andric   return StackOffset::getFixed(MFI.getObjectOffset(FI) -
2487e8d8bef9SDimitry Andric                                getOffsetOfLocalArea() + Adjustment);
24880b57cec5SDimitry Andric }
24890b57cec5SDimitry Andric 
2490e8d8bef9SDimitry Andric StackOffset
2491e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2492e8d8bef9SDimitry Andric                                                  int FI, Register &FrameReg,
24930b57cec5SDimitry Andric                                                  bool IgnoreSPUpdates) const {
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
24960b57cec5SDimitry Andric   // Does not include any dynamic realign.
24970b57cec5SDimitry Andric   const uint64_t StackSize = MFI.getStackSize();
24980b57cec5SDimitry Andric   // LLVM arranges the stack as follows:
24990b57cec5SDimitry Andric   //   ...
25000b57cec5SDimitry Andric   //   ARG2
25010b57cec5SDimitry Andric   //   ARG1
25020b57cec5SDimitry Andric   //   RETADDR
25030b57cec5SDimitry Andric   //   PUSH RBP   <-- RBP points here
25040b57cec5SDimitry Andric   //   PUSH CSRs
25050b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (non-win64)
25060b57cec5SDimitry Andric   //   ...
25070b57cec5SDimitry Andric   //   STACK OBJECTS
25080b57cec5SDimitry Andric   //   ...        <-- RSP after prologue points here
25090b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (win64)
25100b57cec5SDimitry Andric   //
25110b57cec5SDimitry Andric   // if (hasVarSizedObjects()):
25120b57cec5SDimitry Andric   //   ...        <-- "base pointer" (ESI/RBX) points here
25130b57cec5SDimitry Andric   //   DYNAMIC ALLOCAS
25140b57cec5SDimitry Andric   //   ...        <-- RSP points here
25150b57cec5SDimitry Andric   //
25160b57cec5SDimitry Andric   // Case 1: In the simple case of no stack realignment and no dynamic
25170b57cec5SDimitry Andric   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
25180b57cec5SDimitry Andric   // with fixed offsets from RSP.
25190b57cec5SDimitry Andric   //
25200b57cec5SDimitry Andric   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
25210b57cec5SDimitry Andric   // stack objects are addressed with RBP and regular stack objects with RSP.
25220b57cec5SDimitry Andric   //
25230b57cec5SDimitry Andric   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
25240b57cec5SDimitry Andric   // to address stack arguments for outgoing calls and nothing else. The "base
25250b57cec5SDimitry Andric   // pointer" points to local variables, and RBP points to fixed objects.
25260b57cec5SDimitry Andric   //
25270b57cec5SDimitry Andric   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
25280b57cec5SDimitry Andric   // answer we give is relative to the SP after the prologue, and not the
25290b57cec5SDimitry Andric   // SP in the middle of the function.
25300b57cec5SDimitry Andric 
2531fe6060f1SDimitry Andric   if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
25320b57cec5SDimitry Andric       !STI.isTargetWin64())
25330b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   // If !hasReservedCallFrame the function might have SP adjustement in the
25360b57cec5SDimitry Andric   // body.  So, even though the offset is statically known, it depends on where
25370b57cec5SDimitry Andric   // we are in the function.
25380b57cec5SDimitry Andric   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
25390b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric   // We don't handle tail calls, and shouldn't be seeing them either.
25420b57cec5SDimitry Andric   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
25430b57cec5SDimitry Andric          "we don't handle this case!");
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric   // This is how the math works out:
25460b57cec5SDimitry Andric   //
25470b57cec5SDimitry Andric   //  %rsp grows (i.e. gets lower) left to right. Each box below is
25480b57cec5SDimitry Andric   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
25490b57cec5SDimitry Andric   //  get to.
25500b57cec5SDimitry Andric   //
25510b57cec5SDimitry Andric   //    ----------------------------------
25520b57cec5SDimitry Andric   //    | BP | Obj0 | Obj1 | ... | ObjN |
25530b57cec5SDimitry Andric   //    ----------------------------------
25540b57cec5SDimitry Andric   //    ^    ^      ^                   ^
25550b57cec5SDimitry Andric   //    A    B      C                   E
25560b57cec5SDimitry Andric   //
25570b57cec5SDimitry Andric   // A is the incoming stack pointer.
25580b57cec5SDimitry Andric   // (B - A) is the local area offset (-8 for x86-64) [1]
25590b57cec5SDimitry Andric   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
25600b57cec5SDimitry Andric   //
25610b57cec5SDimitry Andric   // |(E - B)| is the StackSize (absolute value, positive).  For a
25620b57cec5SDimitry Andric   // stack that grown down, this works out to be (B - E). [3]
25630b57cec5SDimitry Andric   //
25640b57cec5SDimitry Andric   // E is also the value of %rsp after stack has been set up, and we
25650b57cec5SDimitry Andric   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
25660b57cec5SDimitry Andric   // (C - E) == (C - A) - (B - A) + (B - E)
25670b57cec5SDimitry Andric   //            { Using [1], [2] and [3] above }
25680b57cec5SDimitry Andric   //         == getObjectOffset - LocalAreaOffset + StackSize
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
25710b57cec5SDimitry Andric }
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric bool X86FrameLowering::assignCalleeSavedSpillSlots(
25740b57cec5SDimitry Andric     MachineFunction &MF, const TargetRegisterInfo *TRI,
25750b57cec5SDimitry Andric     std::vector<CalleeSavedInfo> &CSI) const {
25760b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
25770b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   unsigned CalleeSavedFrameSize = 0;
2580c14a5a88SDimitry Andric   unsigned XMMCalleeSavedFrameSize = 0;
2581c14a5a88SDimitry Andric   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
25820b57cec5SDimitry Andric   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
25830b57cec5SDimitry Andric 
25840b57cec5SDimitry Andric   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0) {
25870b57cec5SDimitry Andric     // create RETURNADDR area
25880b57cec5SDimitry Andric     //   arg
25890b57cec5SDimitry Andric     //   arg
25900b57cec5SDimitry Andric     //   RETADDR
25910b57cec5SDimitry Andric     //   { ...
25920b57cec5SDimitry Andric     //     RETADDR area
25930b57cec5SDimitry Andric     //     ...
25940b57cec5SDimitry Andric     //   }
25950b57cec5SDimitry Andric     //   [EBP]
25960b57cec5SDimitry Andric     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
25970b57cec5SDimitry Andric                            TailCallReturnAddrDelta - SlotSize, true);
25980b57cec5SDimitry Andric   }
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
26010b57cec5SDimitry Andric   if (this->TRI->hasBasePointer(MF)) {
26020b57cec5SDimitry Andric     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
26030b57cec5SDimitry Andric     if (MF.hasEHFunclets()) {
26045ffd83dbSDimitry Andric       int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize));
26050b57cec5SDimitry Andric       X86FI->setHasSEHFramePtrSave(true);
26060b57cec5SDimitry Andric       X86FI->setSEHFramePtrSaveIndex(FI);
26070b57cec5SDimitry Andric     }
26080b57cec5SDimitry Andric   }
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric   if (hasFP(MF)) {
26110b57cec5SDimitry Andric     // emitPrologue always spills frame register the first thing.
26120b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
26130b57cec5SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
26140b57cec5SDimitry Andric 
2615fe6060f1SDimitry Andric     // The async context lives directly before the frame pointer, and we
2616fe6060f1SDimitry Andric     // allocate a second slot to preserve stack alignment.
2617fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2618fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2619fe6060f1SDimitry Andric       MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2620fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2621fe6060f1SDimitry Andric     }
2622fe6060f1SDimitry Andric 
26230b57cec5SDimitry Andric     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
26240b57cec5SDimitry Andric     // the frame register, we can delete it from CSI list and not have to worry
26250b57cec5SDimitry Andric     // about avoiding it later.
26268bcb0991SDimitry Andric     Register FPReg = TRI->getFrameRegister(MF);
26270b57cec5SDimitry Andric     for (unsigned i = 0; i < CSI.size(); ++i) {
26280b57cec5SDimitry Andric       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
26290b57cec5SDimitry Andric         CSI.erase(CSI.begin() + i);
26300b57cec5SDimitry Andric         break;
26310b57cec5SDimitry Andric       }
26320b57cec5SDimitry Andric     }
26330b57cec5SDimitry Andric   }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   // Assign slots for GPRs. It increases frame size.
26360eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
263704eeddc0SDimitry Andric     Register Reg = I.getReg();
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
26400b57cec5SDimitry Andric       continue;
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
26430b57cec5SDimitry Andric     CalleeSavedFrameSize += SlotSize;
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
26460eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
26470b57cec5SDimitry Andric   }
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
26500b57cec5SDimitry Andric   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
26510b57cec5SDimitry Andric 
26520b57cec5SDimitry Andric   // Assign slots for XMMs.
26530eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
265404eeddc0SDimitry Andric     Register Reg = I.getReg();
26550b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
26560b57cec5SDimitry Andric       continue;
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
26590b57cec5SDimitry Andric     MVT VT = MVT::Other;
26600b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
26610b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
26640b57cec5SDimitry Andric     unsigned Size = TRI->getSpillSize(*RC);
26655ffd83dbSDimitry Andric     Align Alignment = TRI->getSpillAlign(*RC);
26660b57cec5SDimitry Andric     // ensure alignment
2667c14a5a88SDimitry Andric     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
26685ffd83dbSDimitry Andric     SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
2669c14a5a88SDimitry Andric 
26700b57cec5SDimitry Andric     // spill into slot
26710b57cec5SDimitry Andric     SpillSlotOffset -= Size;
26720b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
26730eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
26745ffd83dbSDimitry Andric     MFI.ensureMaxAlignment(Alignment);
2675c14a5a88SDimitry Andric 
2676c14a5a88SDimitry Andric     // Save the start offset and size of XMM in stack frame for funclets.
2677c14a5a88SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
2678c14a5a88SDimitry Andric       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2679c14a5a88SDimitry Andric       XMMCalleeSavedFrameSize += Size;
2680c14a5a88SDimitry Andric     }
26810b57cec5SDimitry Andric   }
26820b57cec5SDimitry Andric 
26830b57cec5SDimitry Andric   return true;
26840b57cec5SDimitry Andric }
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric bool X86FrameLowering::spillCalleeSavedRegisters(
26870b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
26885ffd83dbSDimitry Andric     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
26890b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
26900b57cec5SDimitry Andric 
26910b57cec5SDimitry Andric   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
26920b57cec5SDimitry Andric   // for us, and there are no XMM CSRs on Win32.
26930b57cec5SDimitry Andric   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
26940b57cec5SDimitry Andric     return true;
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric   // Push GPRs. It increases frame size.
26970b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
26980b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
26990eae32dcSDimitry Andric   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
270004eeddc0SDimitry Andric     Register Reg = I.getReg();
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
27030b57cec5SDimitry Andric       continue;
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
27060b57cec5SDimitry Andric     bool isLiveIn = MRI.isLiveIn(Reg);
27070b57cec5SDimitry Andric     if (!isLiveIn)
27080b57cec5SDimitry Andric       MBB.addLiveIn(Reg);
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric     // Decide whether we can add a kill flag to the use.
27110b57cec5SDimitry Andric     bool CanKill = !isLiveIn;
27120b57cec5SDimitry Andric     // Check if any subregister is live-in
27130b57cec5SDimitry Andric     if (CanKill) {
27140b57cec5SDimitry Andric       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
27150b57cec5SDimitry Andric         if (MRI.isLiveIn(*AReg)) {
27160b57cec5SDimitry Andric           CanKill = false;
27170b57cec5SDimitry Andric           break;
27180b57cec5SDimitry Andric         }
27190b57cec5SDimitry Andric       }
27200b57cec5SDimitry Andric     }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric     // Do not set a kill flag on values that are also marked as live-in. This
27230b57cec5SDimitry Andric     // happens with the @llvm-returnaddress intrinsic and with arguments
27240b57cec5SDimitry Andric     // passed in callee saved registers.
27250b57cec5SDimitry Andric     // Omitting the kill flags is conservatively correct even if the live-in
27260b57cec5SDimitry Andric     // is not used after all.
27270b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
27280b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
27290b57cec5SDimitry Andric   }
27300b57cec5SDimitry Andric 
27310b57cec5SDimitry Andric   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
27320b57cec5SDimitry Andric   // It can be done by spilling XMMs to stack frame.
27330eae32dcSDimitry Andric   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
273404eeddc0SDimitry Andric     Register Reg = I.getReg();
27350b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
27360b57cec5SDimitry Andric       continue;
27370b57cec5SDimitry Andric 
27380b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
27390b57cec5SDimitry Andric     MVT VT = MVT::Other;
27400b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
27410b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric     // Add the callee-saved register as live-in. It's killed at the spill.
27440b57cec5SDimitry Andric     MBB.addLiveIn(Reg);
27450b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
27460b57cec5SDimitry Andric 
2747*bdd1243dSDimitry Andric     TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, TRI,
2748*bdd1243dSDimitry Andric                             Register());
27490b57cec5SDimitry Andric     --MI;
27500b57cec5SDimitry Andric     MI->setFlag(MachineInstr::FrameSetup);
27510b57cec5SDimitry Andric     ++MI;
27520b57cec5SDimitry Andric   }
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric   return true;
27550b57cec5SDimitry Andric }
27560b57cec5SDimitry Andric 
27570b57cec5SDimitry Andric void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
27580b57cec5SDimitry Andric                                                MachineBasicBlock::iterator MBBI,
27590b57cec5SDimitry Andric                                                MachineInstr *CatchRet) const {
27600b57cec5SDimitry Andric   // SEH shouldn't use catchret.
27610b57cec5SDimitry Andric   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
27620b57cec5SDimitry Andric              MBB.getParent()->getFunction().getPersonalityFn())) &&
27630b57cec5SDimitry Andric          "SEH should not use CATCHRET");
2764fe6060f1SDimitry Andric   const DebugLoc &DL = CatchRet->getDebugLoc();
27650b57cec5SDimitry Andric   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric   // Fill EAX/RAX with the address of the target block.
27680b57cec5SDimitry Andric   if (STI.is64Bit()) {
27690b57cec5SDimitry Andric     // LEA64r CatchRetTarget(%rip), %rax
27700b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
27710b57cec5SDimitry Andric         .addReg(X86::RIP)
27720b57cec5SDimitry Andric         .addImm(0)
27730b57cec5SDimitry Andric         .addReg(0)
27740b57cec5SDimitry Andric         .addMBB(CatchRetTarget)
27750b57cec5SDimitry Andric         .addReg(0);
27760b57cec5SDimitry Andric   } else {
27770b57cec5SDimitry Andric     // MOV32ri $CatchRetTarget, %eax
27780b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
27790b57cec5SDimitry Andric         .addMBB(CatchRetTarget);
27800b57cec5SDimitry Andric   }
27810b57cec5SDimitry Andric 
27820b57cec5SDimitry Andric   // Record that we've taken the address of CatchRetTarget and no longer just
27830b57cec5SDimitry Andric   // reference it in a terminator.
2784*bdd1243dSDimitry Andric   CatchRetTarget->setMachineBlockAddressTaken();
27850b57cec5SDimitry Andric }
27860b57cec5SDimitry Andric 
27875ffd83dbSDimitry Andric bool X86FrameLowering::restoreCalleeSavedRegisters(
27885ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
27895ffd83dbSDimitry Andric     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
27900b57cec5SDimitry Andric   if (CSI.empty())
27910b57cec5SDimitry Andric     return false;
27920b57cec5SDimitry Andric 
27930b57cec5SDimitry Andric   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
27940b57cec5SDimitry Andric     // Don't restore CSRs in 32-bit EH funclets. Matches
27950b57cec5SDimitry Andric     // spillCalleeSavedRegisters.
27960b57cec5SDimitry Andric     if (STI.is32Bit())
27970b57cec5SDimitry Andric       return true;
27980b57cec5SDimitry Andric     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
27990b57cec5SDimitry Andric     // funclets. emitEpilogue transforms these to normal jumps.
28000b57cec5SDimitry Andric     if (MI->getOpcode() == X86::CATCHRET) {
28010b57cec5SDimitry Andric       const Function &F = MBB.getParent()->getFunction();
28020b57cec5SDimitry Andric       bool IsSEH = isAsynchronousEHPersonality(
28030b57cec5SDimitry Andric           classifyEHPersonality(F.getPersonalityFn()));
28040b57cec5SDimitry Andric       if (IsSEH)
28050b57cec5SDimitry Andric         return true;
28060b57cec5SDimitry Andric     }
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric   // Reload XMMs from stack frame.
28124824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
281304eeddc0SDimitry Andric     Register Reg = I.getReg();
28140b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) ||
28150b57cec5SDimitry Andric         X86::GR32RegClass.contains(Reg))
28160b57cec5SDimitry Andric       continue;
28170b57cec5SDimitry Andric 
28180b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
28190b57cec5SDimitry Andric     MVT VT = MVT::Other;
28200b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
28210b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2824*bdd1243dSDimitry Andric     TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, TRI,
2825*bdd1243dSDimitry Andric                              Register());
28260b57cec5SDimitry Andric   }
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   // POP GPRs.
28290b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
28304824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
283104eeddc0SDimitry Andric     Register Reg = I.getReg();
28320b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) &&
28330b57cec5SDimitry Andric         !X86::GR32RegClass.contains(Reg))
28340b57cec5SDimitry Andric       continue;
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
28370b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
28380b57cec5SDimitry Andric   }
28390b57cec5SDimitry Andric   return true;
28400b57cec5SDimitry Andric }
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
28430b57cec5SDimitry Andric                                             BitVector &SavedRegs,
28440b57cec5SDimitry Andric                                             RegScavenger *RS) const {
28450b57cec5SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
28480b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)){
28498bcb0991SDimitry Andric     Register BasePtr = TRI->getBaseRegister();
28500b57cec5SDimitry Andric     if (STI.isTarget64BitILP32())
28510b57cec5SDimitry Andric       BasePtr = getX86SubSuperRegister(BasePtr, 64);
28520b57cec5SDimitry Andric     SavedRegs.set(BasePtr);
28530b57cec5SDimitry Andric   }
28540b57cec5SDimitry Andric }
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric static bool
28570b57cec5SDimitry Andric HasNestArgument(const MachineFunction *MF) {
28580b57cec5SDimitry Andric   const Function &F = MF->getFunction();
28590b57cec5SDimitry Andric   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
28600b57cec5SDimitry Andric        I != E; I++) {
28618bcb0991SDimitry Andric     if (I->hasNestAttr() && !I->use_empty())
28620b57cec5SDimitry Andric       return true;
28630b57cec5SDimitry Andric   }
28640b57cec5SDimitry Andric   return false;
28650b57cec5SDimitry Andric }
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric /// GetScratchRegister - Get a temp register for performing work in the
28680b57cec5SDimitry Andric /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
28690b57cec5SDimitry Andric /// and the properties of the function either one or two registers will be
28700b57cec5SDimitry Andric /// needed. Set primary to true for the first register, false for the second.
28710b57cec5SDimitry Andric static unsigned
28720b57cec5SDimitry Andric GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
28730b57cec5SDimitry Andric   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric   // Erlang stuff.
28760b57cec5SDimitry Andric   if (CallingConvention == CallingConv::HiPE) {
28770b57cec5SDimitry Andric     if (Is64Bit)
28780b57cec5SDimitry Andric       return Primary ? X86::R14 : X86::R13;
28790b57cec5SDimitry Andric     else
28800b57cec5SDimitry Andric       return Primary ? X86::EBX : X86::EDI;
28810b57cec5SDimitry Andric   }
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric   if (Is64Bit) {
28840b57cec5SDimitry Andric     if (IsLP64)
28850b57cec5SDimitry Andric       return Primary ? X86::R11 : X86::R12;
28860b57cec5SDimitry Andric     else
28870b57cec5SDimitry Andric       return Primary ? X86::R11D : X86::R12D;
28880b57cec5SDimitry Andric   }
28890b57cec5SDimitry Andric 
28900b57cec5SDimitry Andric   bool IsNested = HasNestArgument(&MF);
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric   if (CallingConvention == CallingConv::X86_FastCall ||
28938bcb0991SDimitry Andric       CallingConvention == CallingConv::Fast ||
28948bcb0991SDimitry Andric       CallingConvention == CallingConv::Tail) {
28950b57cec5SDimitry Andric     if (IsNested)
28960b57cec5SDimitry Andric       report_fatal_error("Segmented stacks does not support fastcall with "
28970b57cec5SDimitry Andric                          "nested function.");
28980b57cec5SDimitry Andric     return Primary ? X86::EAX : X86::ECX;
28990b57cec5SDimitry Andric   }
29000b57cec5SDimitry Andric   if (IsNested)
29010b57cec5SDimitry Andric     return Primary ? X86::EDX : X86::EAX;
29020b57cec5SDimitry Andric   return Primary ? X86::ECX : X86::EAX;
29030b57cec5SDimitry Andric }
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual stack
29060b57cec5SDimitry Andric // limit.
29070b57cec5SDimitry Andric static const uint64_t kSplitStackAvailable = 256;
29080b57cec5SDimitry Andric 
29090b57cec5SDimitry Andric void X86FrameLowering::adjustForSegmentedStacks(
29100b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
29110b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
29120b57cec5SDimitry Andric   uint64_t StackSize;
29130b57cec5SDimitry Andric   unsigned TlsReg, TlsOffset;
29140b57cec5SDimitry Andric   DebugLoc DL;
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
29170b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
29180b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
29210b57cec5SDimitry Andric   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
29220b57cec5SDimitry Andric          "Scratch register is live-in");
29230b57cec5SDimitry Andric 
29240b57cec5SDimitry Andric   if (MF.getFunction().isVarArg())
29250b57cec5SDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
29260b57cec5SDimitry Andric   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
29270b57cec5SDimitry Andric       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
29280b57cec5SDimitry Andric       !STI.isTargetDragonFly())
29290b57cec5SDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric   // Eventually StackSize will be calculated by a link-time pass; which will
29320b57cec5SDimitry Andric   // also decide whether checking code needs to be injected into this particular
29330b57cec5SDimitry Andric   // prologue.
29340b57cec5SDimitry Andric   StackSize = MFI.getStackSize();
29350b57cec5SDimitry Andric 
293681ad6265SDimitry Andric   if (!MFI.needsSplitStackProlog())
29370b57cec5SDimitry Andric     return;
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
29400b57cec5SDimitry Andric   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
29410b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
29420b57cec5SDimitry Andric   bool IsNested = false;
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric   // We need to know if the function has a nest argument only in 64 bit mode.
29450b57cec5SDimitry Andric   if (Is64Bit)
29460b57cec5SDimitry Andric     IsNested = HasNestArgument(&MF);
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
29490b57cec5SDimitry Andric   // allocMBB needs to be last (terminating) instruction.
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
29520b57cec5SDimitry Andric     allocMBB->addLiveIn(LI);
29530b57cec5SDimitry Andric     checkMBB->addLiveIn(LI);
29540b57cec5SDimitry Andric   }
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric   if (IsNested)
29570b57cec5SDimitry Andric     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   MF.push_front(allocMBB);
29600b57cec5SDimitry Andric   MF.push_front(checkMBB);
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric   // When the frame size is less than 256 we just compare the stack
29630b57cec5SDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
29640b57cec5SDimitry Andric   bool CompareStackPointer = StackSize < kSplitStackAvailable;
29650b57cec5SDimitry Andric 
29660b57cec5SDimitry Andric   // Read the limit off the current stacklet off the stack_guard location.
29670b57cec5SDimitry Andric   if (Is64Bit) {
29680b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
29690b57cec5SDimitry Andric       TlsReg = X86::FS;
29700b57cec5SDimitry Andric       TlsOffset = IsLP64 ? 0x70 : 0x40;
29710b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
29720b57cec5SDimitry Andric       TlsReg = X86::GS;
29730b57cec5SDimitry Andric       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
29740b57cec5SDimitry Andric     } else if (STI.isTargetWin64()) {
29750b57cec5SDimitry Andric       TlsReg = X86::GS;
29760b57cec5SDimitry Andric       TlsOffset = 0x28; // pvArbitrary, reserved for application use
29770b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
29780b57cec5SDimitry Andric       TlsReg = X86::FS;
29790b57cec5SDimitry Andric       TlsOffset = 0x18;
29800b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
29810b57cec5SDimitry Andric       TlsReg = X86::FS;
29820b57cec5SDimitry Andric       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
29830b57cec5SDimitry Andric     } else {
29840b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
29850b57cec5SDimitry Andric     }
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric     if (CompareStackPointer)
29880b57cec5SDimitry Andric       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
29890b57cec5SDimitry Andric     else
29900b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
29910b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
29940b57cec5SDimitry Andric       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
29950b57cec5SDimitry Andric   } else {
29960b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
29970b57cec5SDimitry Andric       TlsReg = X86::GS;
29980b57cec5SDimitry Andric       TlsOffset = 0x30;
29990b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
30000b57cec5SDimitry Andric       TlsReg = X86::GS;
30010b57cec5SDimitry Andric       TlsOffset = 0x48 + 90*4;
30020b57cec5SDimitry Andric     } else if (STI.isTargetWin32()) {
30030b57cec5SDimitry Andric       TlsReg = X86::FS;
30040b57cec5SDimitry Andric       TlsOffset = 0x14; // pvArbitrary, reserved for application use
30050b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
30060b57cec5SDimitry Andric       TlsReg = X86::FS;
30070b57cec5SDimitry Andric       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
30080b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
30090b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
30100b57cec5SDimitry Andric     } else {
30110b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
30120b57cec5SDimitry Andric     }
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric     if (CompareStackPointer)
30150b57cec5SDimitry Andric       ScratchReg = X86::ESP;
30160b57cec5SDimitry Andric     else
30170b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
30180b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
30210b57cec5SDimitry Andric         STI.isTargetDragonFly()) {
30220b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
30230b57cec5SDimitry Andric         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
30240b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
30270b57cec5SDimitry Andric       unsigned ScratchReg2;
30280b57cec5SDimitry Andric       bool SaveScratch2;
30290b57cec5SDimitry Andric       if (CompareStackPointer) {
30300b57cec5SDimitry Andric         // The primary scratch register is available for holding the TLS offset.
30310b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
30320b57cec5SDimitry Andric         SaveScratch2 = false;
30330b57cec5SDimitry Andric       } else {
30340b57cec5SDimitry Andric         // Need to use a second register to hold the TLS offset
30350b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
30360b57cec5SDimitry Andric 
30370b57cec5SDimitry Andric         // Unfortunately, with fastcc the second scratch register may hold an
30380b57cec5SDimitry Andric         // argument.
30390b57cec5SDimitry Andric         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
30400b57cec5SDimitry Andric       }
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric       // If Scratch2 is live-in then it needs to be saved.
30430b57cec5SDimitry Andric       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
30440b57cec5SDimitry Andric              "Scratch register is live-in and not saved");
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric       if (SaveScratch2)
30470b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
30480b57cec5SDimitry Andric           .addReg(ScratchReg2, RegState::Kill);
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
30510b57cec5SDimitry Andric         .addImm(TlsOffset);
30520b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
30530b57cec5SDimitry Andric         .addReg(ScratchReg)
30540b57cec5SDimitry Andric         .addReg(ScratchReg2).addImm(1).addReg(0)
30550b57cec5SDimitry Andric         .addImm(0)
30560b57cec5SDimitry Andric         .addReg(TlsReg);
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric       if (SaveScratch2)
30590b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
30600b57cec5SDimitry Andric     }
30610b57cec5SDimitry Andric   }
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
30640b57cec5SDimitry Andric   // It jumps to normal execution of the function body.
30650b57cec5SDimitry Andric   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric   // On 32 bit we first push the arguments size and then the frame size. On 64
30680b57cec5SDimitry Andric   // bit, we pass the stack frame size in r10 and the argument size in r11.
30690b57cec5SDimitry Andric   if (Is64Bit) {
30700b57cec5SDimitry Andric     // Functions with nested arguments use R10, so it needs to be saved across
30710b57cec5SDimitry Andric     // the call to _morestack
30720b57cec5SDimitry Andric 
30730b57cec5SDimitry Andric     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
30740b57cec5SDimitry Andric     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
30750b57cec5SDimitry Andric     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
30760b57cec5SDimitry Andric     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
30770b57cec5SDimitry Andric 
30780b57cec5SDimitry Andric     if (IsNested)
30790b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
30800b57cec5SDimitry Andric 
308104eeddc0SDimitry Andric     BuildMI(allocMBB, DL, TII.get(getMOVriOpcode(IsLP64, StackSize)), Reg10)
30820b57cec5SDimitry Andric         .addImm(StackSize);
308304eeddc0SDimitry Andric     BuildMI(allocMBB, DL,
308404eeddc0SDimitry Andric             TII.get(getMOVriOpcode(IsLP64, X86FI->getArgumentStackSize())),
308504eeddc0SDimitry Andric             Reg11)
30860b57cec5SDimitry Andric         .addImm(X86FI->getArgumentStackSize());
30870b57cec5SDimitry Andric   } else {
30880b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
30890b57cec5SDimitry Andric       .addImm(X86FI->getArgumentStackSize());
30900b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
30910b57cec5SDimitry Andric       .addImm(StackSize);
30920b57cec5SDimitry Andric   }
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric   // __morestack is in libgcc
30950b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
30960b57cec5SDimitry Andric     // Under the large code model, we cannot assume that __morestack lives
30970b57cec5SDimitry Andric     // within 2^31 bytes of the call site, so we cannot use pc-relative
30980b57cec5SDimitry Andric     // addressing. We cannot perform the call via a temporary register,
30990b57cec5SDimitry Andric     // as the rax register may be used to store the static chain, and all
31000b57cec5SDimitry Andric     // other suitable registers may be either callee-save or used for
31010b57cec5SDimitry Andric     // parameter passing. We cannot use the stack at this point either
31020b57cec5SDimitry Andric     // because __morestack manipulates the stack directly.
31030b57cec5SDimitry Andric     //
31040b57cec5SDimitry Andric     // To avoid these issues, perform an indirect call via a read-only memory
31050b57cec5SDimitry Andric     // location containing the address.
31060b57cec5SDimitry Andric     //
31070b57cec5SDimitry Andric     // This solution is not perfect, as it assumes that the .rodata section
31080b57cec5SDimitry Andric     // is laid out within 2^31 bytes of each function body, but this seems
31090b57cec5SDimitry Andric     // to be sufficient for JIT.
31100b57cec5SDimitry Andric     // FIXME: Add retpoline support and remove the error here..
31110946e70aSDimitry Andric     if (STI.useIndirectThunkCalls())
31120b57cec5SDimitry Andric       report_fatal_error("Emitting morestack calls on 64-bit with the large "
31130946e70aSDimitry Andric                          "code model and thunks not yet implemented.");
31140b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
31150b57cec5SDimitry Andric         .addReg(X86::RIP)
31160b57cec5SDimitry Andric         .addImm(0)
31170b57cec5SDimitry Andric         .addReg(0)
31180b57cec5SDimitry Andric         .addExternalSymbol("__morestack_addr")
31190b57cec5SDimitry Andric         .addReg(0);
31200b57cec5SDimitry Andric   } else {
31210b57cec5SDimitry Andric     if (Is64Bit)
31220b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
31230b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
31240b57cec5SDimitry Andric     else
31250b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
31260b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
31270b57cec5SDimitry Andric   }
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   if (IsNested)
31300b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
31310b57cec5SDimitry Andric   else
31320b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric   allocMBB->addSuccessor(&PrologueMBB);
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
31370b57cec5SDimitry Andric   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
31400b57cec5SDimitry Andric   MF.verify();
31410b57cec5SDimitry Andric #endif
31420b57cec5SDimitry Andric }
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
31450b57cec5SDimitry Andric /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
31460b57cec5SDimitry Andric /// to fields it needs, through a named metadata node "hipe.literals" containing
31470b57cec5SDimitry Andric /// name-value pairs.
31480b57cec5SDimitry Andric static unsigned getHiPELiteral(
31490b57cec5SDimitry Andric     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
31500b57cec5SDimitry Andric   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
31510b57cec5SDimitry Andric     MDNode *Node = HiPELiteralsMD->getOperand(i);
31520b57cec5SDimitry Andric     if (Node->getNumOperands() != 2) continue;
31530b57cec5SDimitry Andric     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
31540b57cec5SDimitry Andric     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
31550b57cec5SDimitry Andric     if (!NodeName || !NodeVal) continue;
31560b57cec5SDimitry Andric     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
31570b57cec5SDimitry Andric     if (ValConst && NodeName->getString() == LiteralName) {
31580b57cec5SDimitry Andric       return ValConst->getZExtValue();
31590b57cec5SDimitry Andric     }
31600b57cec5SDimitry Andric   }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric   report_fatal_error("HiPE literal " + LiteralName
31630b57cec5SDimitry Andric                      + " required but not provided");
31640b57cec5SDimitry Andric }
31650b57cec5SDimitry Andric 
31668bcb0991SDimitry Andric // Return true if there are no non-ehpad successors to MBB and there are no
31678bcb0991SDimitry Andric // non-meta instructions between MBBI and MBB.end().
31688bcb0991SDimitry Andric static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
31698bcb0991SDimitry Andric                                   MachineBasicBlock::const_iterator MBBI) {
3170e8d8bef9SDimitry Andric   return llvm::all_of(
3171e8d8bef9SDimitry Andric              MBB.successors(),
31728bcb0991SDimitry Andric              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
31738bcb0991SDimitry Andric          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
31748bcb0991SDimitry Andric            return MI.isMetaInstruction();
31758bcb0991SDimitry Andric          });
31768bcb0991SDimitry Andric }
31778bcb0991SDimitry Andric 
31780b57cec5SDimitry Andric /// Erlang programs may need a special prologue to handle the stack size they
31790b57cec5SDimitry Andric /// might need at runtime. That is because Erlang/OTP does not implement a C
31800b57cec5SDimitry Andric /// stack but uses a custom implementation of hybrid stack/heap architecture.
31810b57cec5SDimitry Andric /// (for more information see Eric Stenman's Ph.D. thesis:
31820b57cec5SDimitry Andric /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
31830b57cec5SDimitry Andric ///
31840b57cec5SDimitry Andric /// CheckStack:
31850b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
31860b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
31870b57cec5SDimitry Andric /// OldStart:
31880b57cec5SDimitry Andric ///       ...
31890b57cec5SDimitry Andric /// IncStack:
31900b57cec5SDimitry Andric ///       call inc_stack   # doubles the stack space
31910b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
31920b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
31930b57cec5SDimitry Andric void X86FrameLowering::adjustForHiPEPrologue(
31940b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
31950b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
31960b57cec5SDimitry Andric   DebugLoc DL;
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
31990b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
32000b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric   // HiPE-specific values
32030b57cec5SDimitry Andric   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
32040b57cec5SDimitry Andric     ->getNamedMetadata("hipe.literals");
32050b57cec5SDimitry Andric   if (!HiPELiteralsMD)
32060b57cec5SDimitry Andric     report_fatal_error(
32070b57cec5SDimitry Andric         "Can't generate HiPE prologue without runtime parameters");
32080b57cec5SDimitry Andric   const unsigned HipeLeafWords
32090b57cec5SDimitry Andric     = getHiPELiteral(HiPELiteralsMD,
32100b57cec5SDimitry Andric                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
32110b57cec5SDimitry Andric   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
32120b57cec5SDimitry Andric   const unsigned Guaranteed = HipeLeafWords * SlotSize;
32130b57cec5SDimitry Andric   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
32140b57cec5SDimitry Andric                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
32150b57cec5SDimitry Andric   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric   assert(STI.isTargetLinux() &&
32180b57cec5SDimitry Andric          "HiPE prologue is only supported on Linux operating systems.");
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric   // Compute the largest caller's frame that is needed to fit the callees'
32210b57cec5SDimitry Andric   // frames. This 'MaxStack' is computed from:
32220b57cec5SDimitry Andric   //
32230b57cec5SDimitry Andric   // a) the fixed frame size, which is the space needed for all spilled temps,
32240b57cec5SDimitry Andric   // b) outgoing on-stack parameter areas, and
32250b57cec5SDimitry Andric   // c) the minimum stack space this function needs to make available for the
32260b57cec5SDimitry Andric   //    functions it calls (a tunable ABI property).
32270b57cec5SDimitry Andric   if (MFI.hasCalls()) {
32280b57cec5SDimitry Andric     unsigned MoreStackForCalls = 0;
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric     for (auto &MBB : MF) {
32310b57cec5SDimitry Andric       for (auto &MI : MBB) {
32320b57cec5SDimitry Andric         if (!MI.isCall())
32330b57cec5SDimitry Andric           continue;
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric         // Get callee operand.
32360b57cec5SDimitry Andric         const MachineOperand &MO = MI.getOperand(0);
32370b57cec5SDimitry Andric 
32380b57cec5SDimitry Andric         // Only take account of global function calls (no closures etc.).
32390b57cec5SDimitry Andric         if (!MO.isGlobal())
32400b57cec5SDimitry Andric           continue;
32410b57cec5SDimitry Andric 
32420b57cec5SDimitry Andric         const Function *F = dyn_cast<Function>(MO.getGlobal());
32430b57cec5SDimitry Andric         if (!F)
32440b57cec5SDimitry Andric           continue;
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric         // Do not update 'MaxStack' for primitive and built-in functions
32470b57cec5SDimitry Andric         // (encoded with names either starting with "erlang."/"bif_" or not
32480b57cec5SDimitry Andric         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
32490b57cec5SDimitry Andric         // "_", such as the BIF "suspend_0") as they are executed on another
32500b57cec5SDimitry Andric         // stack.
3251349cc55cSDimitry Andric         if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
32520b57cec5SDimitry Andric             F->getName().find_first_of("._") == StringRef::npos)
32530b57cec5SDimitry Andric           continue;
32540b57cec5SDimitry Andric 
32550b57cec5SDimitry Andric         unsigned CalleeStkArity =
32560b57cec5SDimitry Andric           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
32570b57cec5SDimitry Andric         if (HipeLeafWords - 1 > CalleeStkArity)
32580b57cec5SDimitry Andric           MoreStackForCalls = std::max(MoreStackForCalls,
32590b57cec5SDimitry Andric                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
32600b57cec5SDimitry Andric       }
32610b57cec5SDimitry Andric     }
32620b57cec5SDimitry Andric     MaxStack += MoreStackForCalls;
32630b57cec5SDimitry Andric   }
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric   // If the stack frame needed is larger than the guaranteed then runtime checks
32660b57cec5SDimitry Andric   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
32670b57cec5SDimitry Andric   if (MaxStack > Guaranteed) {
32680b57cec5SDimitry Andric     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
32690b57cec5SDimitry Andric     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
32700b57cec5SDimitry Andric 
32710b57cec5SDimitry Andric     for (const auto &LI : PrologueMBB.liveins()) {
32720b57cec5SDimitry Andric       stackCheckMBB->addLiveIn(LI);
32730b57cec5SDimitry Andric       incStackMBB->addLiveIn(LI);
32740b57cec5SDimitry Andric     }
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric     MF.push_front(incStackMBB);
32770b57cec5SDimitry Andric     MF.push_front(stackCheckMBB);
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
32800b57cec5SDimitry Andric     unsigned LEAop, CMPop, CALLop;
32810b57cec5SDimitry Andric     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
32820b57cec5SDimitry Andric     if (Is64Bit) {
32830b57cec5SDimitry Andric       SPReg = X86::RSP;
32840b57cec5SDimitry Andric       PReg  = X86::RBP;
32850b57cec5SDimitry Andric       LEAop = X86::LEA64r;
32860b57cec5SDimitry Andric       CMPop = X86::CMP64rm;
32870b57cec5SDimitry Andric       CALLop = X86::CALL64pcrel32;
32880b57cec5SDimitry Andric     } else {
32890b57cec5SDimitry Andric       SPReg = X86::ESP;
32900b57cec5SDimitry Andric       PReg  = X86::EBP;
32910b57cec5SDimitry Andric       LEAop = X86::LEA32r;
32920b57cec5SDimitry Andric       CMPop = X86::CMP32rm;
32930b57cec5SDimitry Andric       CALLop = X86::CALLpcrel32;
32940b57cec5SDimitry Andric     }
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
32970b57cec5SDimitry Andric     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
32980b57cec5SDimitry Andric            "HiPE prologue scratch register is live-in");
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric     // Create new MBB for StackCheck:
33010b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
33020b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
33030b57cec5SDimitry Andric     // SPLimitOffset is in a fixed heap location (pointed by BP).
33040b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
33050b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
33060b57cec5SDimitry Andric     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric     // Create new MBB for IncStack:
33090b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(CALLop)).
33100b57cec5SDimitry Andric       addExternalSymbol("inc_stack_0");
33110b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
33120b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
33130b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
33140b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
33150b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
33180b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
33190b57cec5SDimitry Andric     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
33200b57cec5SDimitry Andric     incStackMBB->addSuccessor(incStackMBB, {1, 100});
33210b57cec5SDimitry Andric   }
33220b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
33230b57cec5SDimitry Andric   MF.verify();
33240b57cec5SDimitry Andric #endif
33250b57cec5SDimitry Andric }
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
33280b57cec5SDimitry Andric                                            MachineBasicBlock::iterator MBBI,
33290b57cec5SDimitry Andric                                            const DebugLoc &DL,
33300b57cec5SDimitry Andric                                            int Offset) const {
33310b57cec5SDimitry Andric   if (Offset <= 0)
33320b57cec5SDimitry Andric     return false;
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric   if (Offset % SlotSize)
33350b57cec5SDimitry Andric     return false;
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric   int NumPops = Offset / SlotSize;
33380b57cec5SDimitry Andric   // This is only worth it if we have at most 2 pops.
33390b57cec5SDimitry Andric   if (NumPops != 1 && NumPops != 2)
33400b57cec5SDimitry Andric     return false;
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   // Handle only the trivial case where the adjustment directly follows
33430b57cec5SDimitry Andric   // a call. This is the most common one, anyway.
33440b57cec5SDimitry Andric   if (MBBI == MBB.begin())
33450b57cec5SDimitry Andric     return false;
33460b57cec5SDimitry Andric   MachineBasicBlock::iterator Prev = std::prev(MBBI);
33470b57cec5SDimitry Andric   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
33480b57cec5SDimitry Andric     return false;
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric   unsigned Regs[2];
33510b57cec5SDimitry Andric   unsigned FoundRegs = 0;
33520b57cec5SDimitry Andric 
3353e8d8bef9SDimitry Andric   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3354e8d8bef9SDimitry Andric   const MachineOperand &RegMask = Prev->getOperand(1);
33550b57cec5SDimitry Andric 
33560b57cec5SDimitry Andric   auto &RegClass =
33570b57cec5SDimitry Andric       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
33580b57cec5SDimitry Andric   // Try to find up to NumPops free registers.
33590b57cec5SDimitry Andric   for (auto Candidate : RegClass) {
33600b57cec5SDimitry Andric     // Poor man's liveness:
33610b57cec5SDimitry Andric     // Since we're immediately after a call, any register that is clobbered
33620b57cec5SDimitry Andric     // by the call and not defined by it can be considered dead.
33630b57cec5SDimitry Andric     if (!RegMask.clobbersPhysReg(Candidate))
33640b57cec5SDimitry Andric       continue;
33650b57cec5SDimitry Andric 
33660b57cec5SDimitry Andric     // Don't clobber reserved registers
33670b57cec5SDimitry Andric     if (MRI.isReserved(Candidate))
33680b57cec5SDimitry Andric       continue;
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric     bool IsDef = false;
33710b57cec5SDimitry Andric     for (const MachineOperand &MO : Prev->implicit_operands()) {
33720b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() &&
33730b57cec5SDimitry Andric           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
33740b57cec5SDimitry Andric         IsDef = true;
33750b57cec5SDimitry Andric         break;
33760b57cec5SDimitry Andric       }
33770b57cec5SDimitry Andric     }
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric     if (IsDef)
33800b57cec5SDimitry Andric       continue;
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric     Regs[FoundRegs++] = Candidate;
33830b57cec5SDimitry Andric     if (FoundRegs == (unsigned)NumPops)
33840b57cec5SDimitry Andric       break;
33850b57cec5SDimitry Andric   }
33860b57cec5SDimitry Andric 
33870b57cec5SDimitry Andric   if (FoundRegs == 0)
33880b57cec5SDimitry Andric     return false;
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric   // If we found only one free register, but need two, reuse the same one twice.
33910b57cec5SDimitry Andric   while (FoundRegs < (unsigned)NumPops)
33920b57cec5SDimitry Andric     Regs[FoundRegs++] = Regs[0];
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric   for (int i = 0; i < NumPops; ++i)
33950b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL,
33960b57cec5SDimitry Andric             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
33970b57cec5SDimitry Andric 
33980b57cec5SDimitry Andric   return true;
33990b57cec5SDimitry Andric }
34000b57cec5SDimitry Andric 
34010b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::
34020b57cec5SDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
34030b57cec5SDimitry Andric                               MachineBasicBlock::iterator I) const {
34040b57cec5SDimitry Andric   bool reserveCallFrame = hasReservedCallFrame(MF);
34050b57cec5SDimitry Andric   unsigned Opcode = I->getOpcode();
34060b57cec5SDimitry Andric   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
3407fe6060f1SDimitry Andric   DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
34088bcb0991SDimitry Andric   uint64_t Amount = TII.getFrameSize(*I);
34090b57cec5SDimitry Andric   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
34100b57cec5SDimitry Andric   I = MBB.erase(I);
34110b57cec5SDimitry Andric   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
34120b57cec5SDimitry Andric 
34135ffd83dbSDimitry Andric   // Try to avoid emitting dead SP adjustments if the block end is unreachable,
34145ffd83dbSDimitry Andric   // typically because the function is marked noreturn (abort, throw,
34155ffd83dbSDimitry Andric   // assert_fail, etc).
34165ffd83dbSDimitry Andric   if (isDestroy && blockEndIsUnreachable(MBB, I))
34175ffd83dbSDimitry Andric     return I;
34185ffd83dbSDimitry Andric 
34190b57cec5SDimitry Andric   if (!reserveCallFrame) {
34200b57cec5SDimitry Andric     // If the stack pointer can be changed after prologue, turn the
34210b57cec5SDimitry Andric     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
34220b57cec5SDimitry Andric     // adjcallstackdown instruction into 'add ESP, <amt>'
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric     // We need to keep the stack aligned properly.  To do this, we round the
34250b57cec5SDimitry Andric     // amount of space needed for the outgoing arguments up to the next
34260b57cec5SDimitry Andric     // alignment boundary.
34275ffd83dbSDimitry Andric     Amount = alignTo(Amount, getStackAlign());
34280b57cec5SDimitry Andric 
34290b57cec5SDimitry Andric     const Function &F = MF.getFunction();
34300b57cec5SDimitry Andric     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
3431480093f4SDimitry Andric     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric     // If we have any exception handlers in this function, and we adjust
34340b57cec5SDimitry Andric     // the SP before calls, we may need to indicate this to the unwinder
34350b57cec5SDimitry Andric     // using GNU_ARGS_SIZE. Note that this may be necessary even when
34360b57cec5SDimitry Andric     // Amount == 0, because the preceding function may have set a non-0
34370b57cec5SDimitry Andric     // GNU_ARGS_SIZE.
34380b57cec5SDimitry Andric     // TODO: We don't need to reset this between subsequent functions,
34390b57cec5SDimitry Andric     // if it didn't change.
34400b57cec5SDimitry Andric     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
34410b57cec5SDimitry Andric 
34420b57cec5SDimitry Andric     if (HasDwarfEHHandlers && !isDestroy &&
34430b57cec5SDimitry Andric         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
34440b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
34450b57cec5SDimitry Andric                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric     if (Amount == 0)
34480b57cec5SDimitry Andric       return I;
34490b57cec5SDimitry Andric 
34500b57cec5SDimitry Andric     // Factor out the amount that gets handled inside the sequence
34510b57cec5SDimitry Andric     // (Pushes of argument for frame setup, callee pops for frame destroy)
34520b57cec5SDimitry Andric     Amount -= InternalAmt;
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric     // TODO: This is needed only if we require precise CFA.
34550b57cec5SDimitry Andric     // If this is a callee-pop calling convention, emit a CFA adjust for
34560b57cec5SDimitry Andric     // the amount the callee popped.
34570b57cec5SDimitry Andric     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
34580b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
34590b57cec5SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
34600b57cec5SDimitry Andric 
34610b57cec5SDimitry Andric     // Add Amount to SP to destroy a frame, or subtract to setup.
34620b57cec5SDimitry Andric     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric     if (StackAdjustment) {
34650b57cec5SDimitry Andric       // Merge with any previous or following adjustment instruction. Note: the
34660b57cec5SDimitry Andric       // instructions merged with here do not have CFI, so their stack
34670b57cec5SDimitry Andric       // adjustments do not feed into CfaAdjustment.
34680b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
34690b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric       if (StackAdjustment) {
34720b57cec5SDimitry Andric         if (!(F.hasMinSize() &&
34730b57cec5SDimitry Andric               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
34740b57cec5SDimitry Andric           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
34750b57cec5SDimitry Andric                                /*InEpilogue=*/false);
34760b57cec5SDimitry Andric       }
34770b57cec5SDimitry Andric     }
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric     if (DwarfCFI && !hasFP(MF)) {
34800b57cec5SDimitry Andric       // If we don't have FP, but need to generate unwind information,
34810b57cec5SDimitry Andric       // we need to set the correct CFA offset after the stack adjustment.
34820b57cec5SDimitry Andric       // How much we adjust the CFA offset depends on whether we're emitting
34830b57cec5SDimitry Andric       // CFI only for EH purposes or for debugging. EH only requires the CFA
34840b57cec5SDimitry Andric       // offset to be correct at each call site, while for debugging we want
34850b57cec5SDimitry Andric       // it to be more precise.
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric       int64_t CfaAdjustment = -StackAdjustment;
34880b57cec5SDimitry Andric       // TODO: When not using precise CFA, we also need to adjust for the
34890b57cec5SDimitry Andric       // InternalAmt here.
34900b57cec5SDimitry Andric       if (CfaAdjustment) {
34910b57cec5SDimitry Andric         BuildCFI(MBB, InsertPos, DL,
34920b57cec5SDimitry Andric                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
34930b57cec5SDimitry Andric                                                          CfaAdjustment));
34940b57cec5SDimitry Andric       }
34950b57cec5SDimitry Andric     }
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric     return I;
34980b57cec5SDimitry Andric   }
34990b57cec5SDimitry Andric 
35005ffd83dbSDimitry Andric   if (InternalAmt) {
35010b57cec5SDimitry Andric     MachineBasicBlock::iterator CI = I;
35020b57cec5SDimitry Andric     MachineBasicBlock::iterator B = MBB.begin();
35030b57cec5SDimitry Andric     while (CI != B && !std::prev(CI)->isCall())
35040b57cec5SDimitry Andric       --CI;
35050b57cec5SDimitry Andric     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
35060b57cec5SDimitry Andric   }
35070b57cec5SDimitry Andric 
35080b57cec5SDimitry Andric   return I;
35090b57cec5SDimitry Andric }
35100b57cec5SDimitry Andric 
35110b57cec5SDimitry Andric bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
35120b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
35130b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3514fe6060f1SDimitry Andric   if (!MBB.isLiveIn(X86::EFLAGS))
3515fe6060f1SDimitry Andric     return true;
3516fe6060f1SDimitry Andric 
3517*bdd1243dSDimitry Andric   // If stack probes have to loop inline or call, that will clobber EFLAGS.
3518*bdd1243dSDimitry Andric   // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
3519*bdd1243dSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
3520*bdd1243dSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
3521*bdd1243dSDimitry Andric   if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
3522*bdd1243dSDimitry Andric     return false;
3523*bdd1243dSDimitry Andric 
3524fe6060f1SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3525fe6060f1SDimitry Andric   return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
35260b57cec5SDimitry Andric }
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
35290b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
35300b57cec5SDimitry Andric 
35310b57cec5SDimitry Andric   // Win64 has strict requirements in terms of epilogue and we are
35320b57cec5SDimitry Andric   // not taking a chance at messing with them.
35330b57cec5SDimitry Andric   // I.e., unless this block is already an exit block, we can't use
35340b57cec5SDimitry Andric   // it as an epilogue.
35350b57cec5SDimitry Andric   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
35360b57cec5SDimitry Andric     return false;
35370b57cec5SDimitry Andric 
3538fe6060f1SDimitry Andric   // Swift async context epilogue has a BTR instruction that clobbers parts of
3539fe6060f1SDimitry Andric   // EFLAGS.
3540fe6060f1SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3541fe6060f1SDimitry Andric   if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext())
3542fe6060f1SDimitry Andric     return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
3543fe6060f1SDimitry Andric 
35440b57cec5SDimitry Andric   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
35450b57cec5SDimitry Andric     return true;
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric   // If we cannot use LEA to adjust SP, we may need to use ADD, which
35480b57cec5SDimitry Andric   // clobbers the EFLAGS. Check that we do not need to preserve it,
35490b57cec5SDimitry Andric   // otherwise, conservatively assume this is not
35500b57cec5SDimitry Andric   // safe to insert the epilogue here.
35510b57cec5SDimitry Andric   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
35520b57cec5SDimitry Andric }
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
35550b57cec5SDimitry Andric   // If we may need to emit frameless compact unwind information, give
35560b57cec5SDimitry Andric   // up as this is currently broken: PR25614.
3557e8d8bef9SDimitry Andric   bool CompactUnwind =
3558e8d8bef9SDimitry Andric       MF.getMMI().getContext().getObjectFileInfo()->getCompactUnwindSection() !=
3559e8d8bef9SDimitry Andric       nullptr;
3560e8d8bef9SDimitry Andric   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
3561e8d8bef9SDimitry Andric           !CompactUnwind) &&
3562e8d8bef9SDimitry Andric          // The lowering of segmented stack and HiPE only support entry
3563e8d8bef9SDimitry Andric          // blocks as prologue blocks: PR26107. This limitation may be
3564e8d8bef9SDimitry Andric          // lifted if we fix:
35650b57cec5SDimitry Andric          // - adjustForSegmentedStacks
35660b57cec5SDimitry Andric          // - adjustForHiPEPrologue
35670b57cec5SDimitry Andric          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
35680b57cec5SDimitry Andric          !MF.shouldSplitStack();
35690b57cec5SDimitry Andric }
35700b57cec5SDimitry Andric 
35710b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
35720b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
35730b57cec5SDimitry Andric     const DebugLoc &DL, bool RestoreSP) const {
35740b57cec5SDimitry Andric   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
35750b57cec5SDimitry Andric   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
35760b57cec5SDimitry Andric   assert(STI.is32Bit() && !Uses64BitFramePtr &&
35770b57cec5SDimitry Andric          "restoring EBP/ESI on non-32-bit target");
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
35808bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
35818bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
35820b57cec5SDimitry Andric   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
35830b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
35840b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   // FIXME: Don't set FrameSetup flag in catchret case.
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
35890b57cec5SDimitry Andric   int EHRegSize = MFI.getObjectSize(FI);
35900b57cec5SDimitry Andric 
35910b57cec5SDimitry Andric   if (RestoreSP) {
35920b57cec5SDimitry Andric     // MOV32rm -EHRegSize(%ebp), %esp
35930b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
35940b57cec5SDimitry Andric                  X86::EBP, true, -EHRegSize)
35950b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
35960b57cec5SDimitry Andric   }
35970b57cec5SDimitry Andric 
35985ffd83dbSDimitry Andric   Register UsedReg;
3599e8d8bef9SDimitry Andric   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
36000b57cec5SDimitry Andric   int EndOffset = -EHRegOffset - EHRegSize;
36010b57cec5SDimitry Andric   FuncInfo.EHRegNodeEndOffset = EndOffset;
36020b57cec5SDimitry Andric 
36030b57cec5SDimitry Andric   if (UsedReg == FramePtr) {
36040b57cec5SDimitry Andric     // ADD $offset, %ebp
36050b57cec5SDimitry Andric     unsigned ADDri = getADDriOpcode(false, EndOffset);
36060b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
36070b57cec5SDimitry Andric         .addReg(FramePtr)
36080b57cec5SDimitry Andric         .addImm(EndOffset)
36090b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup)
36100b57cec5SDimitry Andric         ->getOperand(3)
36110b57cec5SDimitry Andric         .setIsDead();
36120b57cec5SDimitry Andric     assert(EndOffset >= 0 &&
36130b57cec5SDimitry Andric            "end of registration object above normal EBP position!");
36140b57cec5SDimitry Andric   } else if (UsedReg == BasePtr) {
36150b57cec5SDimitry Andric     // LEA offset(%ebp), %esi
36160b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
36170b57cec5SDimitry Andric                  FramePtr, false, EndOffset)
36180b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
36190b57cec5SDimitry Andric     // MOV32rm SavedEBPOffset(%esi), %ebp
36200b57cec5SDimitry Andric     assert(X86FI->getHasSEHFramePtrSave());
36210b57cec5SDimitry Andric     int Offset =
3622e8d8bef9SDimitry Andric         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
3623e8d8bef9SDimitry Andric             .getFixed();
36240b57cec5SDimitry Andric     assert(UsedReg == BasePtr);
36250b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
36260b57cec5SDimitry Andric                  UsedReg, true, Offset)
36270b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
36280b57cec5SDimitry Andric   } else {
36290b57cec5SDimitry Andric     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
36300b57cec5SDimitry Andric   }
36310b57cec5SDimitry Andric   return MBBI;
36320b57cec5SDimitry Andric }
36330b57cec5SDimitry Andric 
36340b57cec5SDimitry Andric int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
36350b57cec5SDimitry Andric   return TRI->getSlotSize();
36360b57cec5SDimitry Andric }
36370b57cec5SDimitry Andric 
36385ffd83dbSDimitry Andric Register
36395ffd83dbSDimitry Andric X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const {
36400b57cec5SDimitry Andric   return TRI->getDwarfRegNum(StackPtr, true);
36410b57cec5SDimitry Andric }
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric namespace {
36440b57cec5SDimitry Andric // Struct used by orderFrameObjects to help sort the stack objects.
36450b57cec5SDimitry Andric struct X86FrameSortingObject {
36460b57cec5SDimitry Andric   bool IsValid = false;         // true if we care about this Object.
36470b57cec5SDimitry Andric   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
36480b57cec5SDimitry Andric   unsigned ObjectSize = 0;      // Size of Object in bytes.
36495ffd83dbSDimitry Andric   Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
36500b57cec5SDimitry Andric   unsigned ObjectNumUses = 0;   // Object static number of uses.
36510b57cec5SDimitry Andric };
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric // The comparison function we use for std::sort to order our local
36540b57cec5SDimitry Andric // stack symbols. The current algorithm is to use an estimated
36550b57cec5SDimitry Andric // "density". This takes into consideration the size and number of
36560b57cec5SDimitry Andric // uses each object has in order to roughly minimize code size.
36570b57cec5SDimitry Andric // So, for example, an object of size 16B that is referenced 5 times
36580b57cec5SDimitry Andric // will get higher priority than 4 4B objects referenced 1 time each.
36590b57cec5SDimitry Andric // It's not perfect and we may be able to squeeze a few more bytes out of
36600b57cec5SDimitry Andric // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
36610b57cec5SDimitry Andric // fringe end can have special consideration, given their size is less
36620b57cec5SDimitry Andric // important, etc.), but the algorithmic complexity grows too much to be
36630b57cec5SDimitry Andric // worth the extra gains we get. This gets us pretty close.
36640b57cec5SDimitry Andric // The final order leaves us with objects with highest priority going
36650b57cec5SDimitry Andric // at the end of our list.
36660b57cec5SDimitry Andric struct X86FrameSortingComparator {
36670b57cec5SDimitry Andric   inline bool operator()(const X86FrameSortingObject &A,
3668e8d8bef9SDimitry Andric                          const X86FrameSortingObject &B) const {
36690b57cec5SDimitry Andric     uint64_t DensityAScaled, DensityBScaled;
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric     // For consistency in our comparison, all invalid objects are placed
36720b57cec5SDimitry Andric     // at the end. This also allows us to stop walking when we hit the
36730b57cec5SDimitry Andric     // first invalid item after it's all sorted.
36740b57cec5SDimitry Andric     if (!A.IsValid)
36750b57cec5SDimitry Andric       return false;
36760b57cec5SDimitry Andric     if (!B.IsValid)
36770b57cec5SDimitry Andric       return true;
36780b57cec5SDimitry Andric 
36790b57cec5SDimitry Andric     // The density is calculated by doing :
36800b57cec5SDimitry Andric     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
36810b57cec5SDimitry Andric     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
36820b57cec5SDimitry Andric     // Since this approach may cause inconsistencies in
36830b57cec5SDimitry Andric     // the floating point <, >, == comparisons, depending on the floating
36840b57cec5SDimitry Andric     // point model with which the compiler was built, we're going
36850b57cec5SDimitry Andric     // to scale both sides by multiplying with
36860b57cec5SDimitry Andric     // A.ObjectSize * B.ObjectSize. This ends up factoring away
36870b57cec5SDimitry Andric     // the division and, with it, the need for any floating point
36880b57cec5SDimitry Andric     // arithmetic.
36890b57cec5SDimitry Andric     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
36900b57cec5SDimitry Andric       static_cast<uint64_t>(B.ObjectSize);
36910b57cec5SDimitry Andric     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
36920b57cec5SDimitry Andric       static_cast<uint64_t>(A.ObjectSize);
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric     // If the two densities are equal, prioritize highest alignment
36950b57cec5SDimitry Andric     // objects. This allows for similar alignment objects
36960b57cec5SDimitry Andric     // to be packed together (given the same density).
36970b57cec5SDimitry Andric     // There's room for improvement here, also, since we can pack
36980b57cec5SDimitry Andric     // similar alignment (different density) objects next to each
36990b57cec5SDimitry Andric     // other to save padding. This will also require further
37000b57cec5SDimitry Andric     // complexity/iterations, and the overall gain isn't worth it,
37010b57cec5SDimitry Andric     // in general. Something to keep in mind, though.
37020b57cec5SDimitry Andric     if (DensityAScaled == DensityBScaled)
37030b57cec5SDimitry Andric       return A.ObjectAlignment < B.ObjectAlignment;
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric     return DensityAScaled < DensityBScaled;
37060b57cec5SDimitry Andric   }
37070b57cec5SDimitry Andric };
37080b57cec5SDimitry Andric } // namespace
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric // Order the symbols in the local stack.
37110b57cec5SDimitry Andric // We want to place the local stack objects in some sort of sensible order.
37120b57cec5SDimitry Andric // The heuristic we use is to try and pack them according to static number
37130b57cec5SDimitry Andric // of uses and size of object in order to minimize code size.
37140b57cec5SDimitry Andric void X86FrameLowering::orderFrameObjects(
37150b57cec5SDimitry Andric     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
37160b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric   // Don't waste time if there's nothing to do.
37190b57cec5SDimitry Andric   if (ObjectsToAllocate.empty())
37200b57cec5SDimitry Andric     return;
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric   // Create an array of all MFI objects. We won't need all of these
37230b57cec5SDimitry Andric   // objects, but we're going to create a full array of them to make
37240b57cec5SDimitry Andric   // it easier to index into when we're counting "uses" down below.
37250b57cec5SDimitry Andric   // We want to be able to easily/cheaply access an object by simply
37260b57cec5SDimitry Andric   // indexing into it, instead of having to search for it every time.
37270b57cec5SDimitry Andric   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric   // Walk the objects we care about and mark them as such in our working
37300b57cec5SDimitry Andric   // struct.
37310b57cec5SDimitry Andric   for (auto &Obj : ObjectsToAllocate) {
37320b57cec5SDimitry Andric     SortingObjects[Obj].IsValid = true;
37330b57cec5SDimitry Andric     SortingObjects[Obj].ObjectIndex = Obj;
37345ffd83dbSDimitry Andric     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
37350b57cec5SDimitry Andric     // Set the size.
37360b57cec5SDimitry Andric     int ObjectSize = MFI.getObjectSize(Obj);
37370b57cec5SDimitry Andric     if (ObjectSize == 0)
37380b57cec5SDimitry Andric       // Variable size. Just use 4.
37390b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = 4;
37400b57cec5SDimitry Andric     else
37410b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = ObjectSize;
37420b57cec5SDimitry Andric   }
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric   // Count the number of uses for each object.
37450b57cec5SDimitry Andric   for (auto &MBB : MF) {
37460b57cec5SDimitry Andric     for (auto &MI : MBB) {
37470b57cec5SDimitry Andric       if (MI.isDebugInstr())
37480b57cec5SDimitry Andric         continue;
37490b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
37500b57cec5SDimitry Andric         // Check to see if it's a local stack symbol.
37510b57cec5SDimitry Andric         if (!MO.isFI())
37520b57cec5SDimitry Andric           continue;
37530b57cec5SDimitry Andric         int Index = MO.getIndex();
37540b57cec5SDimitry Andric         // Check to see if it falls within our range, and is tagged
37550b57cec5SDimitry Andric         // to require ordering.
37560b57cec5SDimitry Andric         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
37570b57cec5SDimitry Andric             SortingObjects[Index].IsValid)
37580b57cec5SDimitry Andric           SortingObjects[Index].ObjectNumUses++;
37590b57cec5SDimitry Andric       }
37600b57cec5SDimitry Andric     }
37610b57cec5SDimitry Andric   }
37620b57cec5SDimitry Andric 
37630b57cec5SDimitry Andric   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
37640b57cec5SDimitry Andric   // info).
37650b57cec5SDimitry Andric   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
37660b57cec5SDimitry Andric 
37670b57cec5SDimitry Andric   // Now modify the original list to represent the final order that
37680b57cec5SDimitry Andric   // we want. The order will depend on whether we're going to access them
37690b57cec5SDimitry Andric   // from the stack pointer or the frame pointer. For SP, the list should
37700b57cec5SDimitry Andric   // end up with the END containing objects that we want with smaller offsets.
37710b57cec5SDimitry Andric   // For FP, it should be flipped.
37720b57cec5SDimitry Andric   int i = 0;
37730b57cec5SDimitry Andric   for (auto &Obj : SortingObjects) {
37740b57cec5SDimitry Andric     // All invalid items are sorted at the end, so it's safe to stop.
37750b57cec5SDimitry Andric     if (!Obj.IsValid)
37760b57cec5SDimitry Andric       break;
37770b57cec5SDimitry Andric     ObjectsToAllocate[i++] = Obj.ObjectIndex;
37780b57cec5SDimitry Andric   }
37790b57cec5SDimitry Andric 
37800b57cec5SDimitry Andric   // Flip it if we're accessing off of the FP.
3781fe6060f1SDimitry Andric   if (!TRI->hasStackRealignment(MF) && hasFP(MF))
37820b57cec5SDimitry Andric     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
37830b57cec5SDimitry Andric }
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric 
37860b57cec5SDimitry Andric unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
37870b57cec5SDimitry Andric   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
37880b57cec5SDimitry Andric   unsigned Offset = 16;
37890b57cec5SDimitry Andric   // RBP is immediately pushed.
37900b57cec5SDimitry Andric   Offset += SlotSize;
37910b57cec5SDimitry Andric   // All callee-saved registers are then pushed.
37920b57cec5SDimitry Andric   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
37930b57cec5SDimitry Andric   // Every funclet allocates enough stack space for the largest outgoing call.
37940b57cec5SDimitry Andric   Offset += getWinEHFuncletFrameSize(MF);
37950b57cec5SDimitry Andric   return Offset;
37960b57cec5SDimitry Andric }
37970b57cec5SDimitry Andric 
37980b57cec5SDimitry Andric void X86FrameLowering::processFunctionBeforeFrameFinalized(
37990b57cec5SDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
38000b57cec5SDimitry Andric   // Mark the function as not having WinCFI. We will set it back to true in
38010b57cec5SDimitry Andric   // emitPrologue if it gets called and emits CFI.
38020b57cec5SDimitry Andric   MF.setHasWinCFI(false);
38030b57cec5SDimitry Andric 
3804e8d8bef9SDimitry Andric   // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
3805e8d8bef9SDimitry Andric   // aligned. The format doesn't support misaligned stack adjustments.
3806e8d8bef9SDimitry Andric   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
3807e8d8bef9SDimitry Andric     MF.getFrameInfo().ensureMaxAlignment(Align(SlotSize));
3808e8d8bef9SDimitry Andric 
38090b57cec5SDimitry Andric   // If this function isn't doing Win64-style C++ EH, we don't need to do
38100b57cec5SDimitry Andric   // anything.
3811e8d8bef9SDimitry Andric   if (STI.is64Bit() && MF.hasEHFunclets() &&
3812e8d8bef9SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()) ==
3813e8d8bef9SDimitry Andric           EHPersonality::MSVC_CXX) {
3814e8d8bef9SDimitry Andric     adjustFrameForMsvcCxxEh(MF);
3815e8d8bef9SDimitry Andric   }
3816e8d8bef9SDimitry Andric }
38170b57cec5SDimitry Andric 
3818e8d8bef9SDimitry Andric void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
38190b57cec5SDimitry Andric   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
38200b57cec5SDimitry Andric   // relative to RSP after the prologue.  Find the offset of the last fixed
38210b57cec5SDimitry Andric   // object, so that we can allocate a slot immediately following it. If there
38220b57cec5SDimitry Andric   // were no fixed objects, use offset -SlotSize, which is immediately after the
38230b57cec5SDimitry Andric   // return address. Fixed objects have negative frame indices.
38240b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
38250b57cec5SDimitry Andric   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
38260b57cec5SDimitry Andric   int64_t MinFixedObjOffset = -SlotSize;
38270b57cec5SDimitry Andric   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
38280b57cec5SDimitry Andric     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
38310b57cec5SDimitry Andric     for (WinEHHandlerType &H : TBME.HandlerArray) {
38320b57cec5SDimitry Andric       int FrameIndex = H.CatchObj.FrameIndex;
38330b57cec5SDimitry Andric       if (FrameIndex != INT_MAX) {
38340b57cec5SDimitry Andric         // Ensure alignment.
38355ffd83dbSDimitry Andric         unsigned Align = MFI.getObjectAlign(FrameIndex).value();
38360b57cec5SDimitry Andric         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
38370b57cec5SDimitry Andric         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
38380b57cec5SDimitry Andric         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
38390b57cec5SDimitry Andric       }
38400b57cec5SDimitry Andric     }
38410b57cec5SDimitry Andric   }
38420b57cec5SDimitry Andric 
38430b57cec5SDimitry Andric   // Ensure alignment.
38440b57cec5SDimitry Andric   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
38450b57cec5SDimitry Andric   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
38460b57cec5SDimitry Andric   int UnwindHelpFI =
38470b57cec5SDimitry Andric       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
38480b57cec5SDimitry Andric   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
38510b57cec5SDimitry Andric   // other frame setup instructions.
38520b57cec5SDimitry Andric   MachineBasicBlock &MBB = MF.front();
38530b57cec5SDimitry Andric   auto MBBI = MBB.begin();
38540b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
38550b57cec5SDimitry Andric     ++MBBI;
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MBBI);
38580b57cec5SDimitry Andric   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
38590b57cec5SDimitry Andric                     UnwindHelpFI)
38600b57cec5SDimitry Andric       .addImm(-2);
38610b57cec5SDimitry Andric }
38625ffd83dbSDimitry Andric 
38635ffd83dbSDimitry Andric void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
38645ffd83dbSDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
38655ffd83dbSDimitry Andric   if (STI.is32Bit() && MF.hasEHFunclets())
38665ffd83dbSDimitry Andric     restoreWinEHStackPointersInParent(MF);
38675ffd83dbSDimitry Andric }
38685ffd83dbSDimitry Andric 
38695ffd83dbSDimitry Andric void X86FrameLowering::restoreWinEHStackPointersInParent(
38705ffd83dbSDimitry Andric     MachineFunction &MF) const {
38715ffd83dbSDimitry Andric   // 32-bit functions have to restore stack pointers when control is transferred
38725ffd83dbSDimitry Andric   // back to the parent function. These blocks are identified as eh pads that
38735ffd83dbSDimitry Andric   // are not funclet entries.
38745ffd83dbSDimitry Andric   bool IsSEH = isAsynchronousEHPersonality(
38755ffd83dbSDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
38765ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : MF) {
38775ffd83dbSDimitry Andric     bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
38785ffd83dbSDimitry Andric     if (NeedsRestore)
38795ffd83dbSDimitry Andric       restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(),
38805ffd83dbSDimitry Andric                                   /*RestoreSP=*/IsSEH);
38815ffd83dbSDimitry Andric   }
38825ffd83dbSDimitry Andric }
3883