xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
2281ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
290b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
30*06c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.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"
36*06c3fb27SDimitry Andric #include "llvm/Support/LEB128.h"
370b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
380b57cec5SDimitry Andric #include <cstdlib>
390b57cec5SDimitry Andric 
405ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-fl"
415ffd83dbSDimitry Andric 
425ffd83dbSDimitry Andric STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
435ffd83dbSDimitry Andric STATISTIC(NumFrameExtraProbe,
445ffd83dbSDimitry Andric           "Number of extra stack probes generated in prologue");
455ffd83dbSDimitry Andric 
460b57cec5SDimitry Andric using namespace llvm;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
498bcb0991SDimitry Andric                                    MaybeAlign StackAlignOverride)
508bcb0991SDimitry Andric     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
510b57cec5SDimitry Andric                           STI.is64Bit() ? -8 : -4),
520b57cec5SDimitry Andric       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
530b57cec5SDimitry Andric   // Cache a bunch of frame-related predicates for this subtarget.
540b57cec5SDimitry Andric   SlotSize = TRI->getSlotSize();
550b57cec5SDimitry Andric   Is64Bit = STI.is64Bit();
560b57cec5SDimitry Andric   IsLP64 = STI.isTarget64BitLP64();
570b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
580b57cec5SDimitry Andric   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
590b57cec5SDimitry Andric   StackPtr = TRI->getStackRegister();
600b57cec5SDimitry Andric }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
630b57cec5SDimitry Andric   return !MF.getFrameInfo().hasVarSizedObjects() &&
645ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
655ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
660b57cec5SDimitry Andric }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
690b57cec5SDimitry Andric /// call frame pseudos can be simplified.  Having a FP, as in the default
700b57cec5SDimitry Andric /// implementation, is not sufficient here since we can't always use it.
710b57cec5SDimitry Andric /// Use a more nuanced condition.
720b57cec5SDimitry Andric bool
730b57cec5SDimitry Andric X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
740b57cec5SDimitry Andric   return hasReservedCallFrame(MF) ||
755ffd83dbSDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
76fe6060f1SDimitry Andric          (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
770b57cec5SDimitry Andric          TRI->hasBasePointer(MF);
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // needsFrameIndexResolution - Do we need to perform FI resolution for
810b57cec5SDimitry Andric // this function. Normally, this is required only when the function
820b57cec5SDimitry Andric // has any stack objects. However, FI resolution actually has another job,
830b57cec5SDimitry Andric // not apparent from the title - it resolves callframesetup/destroy
840b57cec5SDimitry Andric // that were not simplified earlier.
850b57cec5SDimitry Andric // So, this is required for x86 functions that have push sequences even
860b57cec5SDimitry Andric // when there are no stack objects.
870b57cec5SDimitry Andric bool
880b57cec5SDimitry Andric X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
890b57cec5SDimitry Andric   return MF.getFrameInfo().hasStackObjects() ||
900b57cec5SDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
940b57cec5SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
950b57cec5SDimitry Andric /// or if frame pointer elimination is disabled.
960b57cec5SDimitry Andric bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
970b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
980b57cec5SDimitry Andric   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
99fe6060f1SDimitry Andric           TRI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
1000b57cec5SDimitry Andric           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
1010b57cec5SDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
1025ffd83dbSDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
1030b57cec5SDimitry Andric           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
1040b57cec5SDimitry Andric           MFI.hasStackMap() || MFI.hasPatchPoint() ||
105d56accc7SDimitry Andric           (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment()));
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
108*06c3fb27SDimitry Andric static unsigned getSUBriOpcode(bool IsLP64) {
109*06c3fb27SDimitry Andric   return IsLP64 ? X86::SUB64ri32 : X86::SUB32ri;
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
112*06c3fb27SDimitry Andric static unsigned getADDriOpcode(bool IsLP64) {
113*06c3fb27SDimitry Andric   return IsLP64 ? X86::ADD64ri32 : X86::ADD32ri;
1140b57cec5SDimitry Andric }
1150b57cec5SDimitry Andric 
116480093f4SDimitry Andric static unsigned getSUBrrOpcode(bool IsLP64) {
117480093f4SDimitry Andric   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
120480093f4SDimitry Andric static unsigned getADDrrOpcode(bool IsLP64) {
121480093f4SDimitry Andric   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
125*06c3fb27SDimitry Andric   return IsLP64 ? X86::AND64ri32 : X86::AND32ri;
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
128480093f4SDimitry Andric static unsigned getLEArOpcode(bool IsLP64) {
1290b57cec5SDimitry Andric   return IsLP64 ? X86::LEA64r : X86::LEA32r;
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
13204eeddc0SDimitry Andric static unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm) {
13304eeddc0SDimitry Andric   if (Use64BitReg) {
13404eeddc0SDimitry Andric     if (isUInt<32>(Imm))
13504eeddc0SDimitry Andric       return X86::MOV32ri64;
13604eeddc0SDimitry Andric     if (isInt<32>(Imm))
13704eeddc0SDimitry Andric       return X86::MOV64ri32;
13804eeddc0SDimitry Andric     return X86::MOV64ri;
13904eeddc0SDimitry Andric   }
14004eeddc0SDimitry Andric   return X86::MOV32ri;
14104eeddc0SDimitry Andric }
14204eeddc0SDimitry Andric 
1430b57cec5SDimitry Andric static bool isEAXLiveIn(MachineBasicBlock &MBB) {
1440b57cec5SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
1450b57cec5SDimitry Andric     unsigned Reg = RegMask.PhysReg;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
1480b57cec5SDimitry Andric         Reg == X86::AH || Reg == X86::AL)
1490b57cec5SDimitry Andric       return true;
1500b57cec5SDimitry Andric   }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   return false;
1530b57cec5SDimitry Andric }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric /// Check if the flags need to be preserved before the terminators.
1560b57cec5SDimitry Andric /// This would be the case, if the eflags is live-in of the region
1570b57cec5SDimitry Andric /// composed by the terminators or live-out of that region, without
1580b57cec5SDimitry Andric /// being defined by a terminator.
1590b57cec5SDimitry Andric static bool
1600b57cec5SDimitry Andric flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
1610b57cec5SDimitry Andric   for (const MachineInstr &MI : MBB.terminators()) {
1620b57cec5SDimitry Andric     bool BreakNext = false;
1630b57cec5SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1640b57cec5SDimitry Andric       if (!MO.isReg())
1650b57cec5SDimitry Andric         continue;
1668bcb0991SDimitry Andric       Register Reg = MO.getReg();
1670b57cec5SDimitry Andric       if (Reg != X86::EFLAGS)
1680b57cec5SDimitry Andric         continue;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric       // This terminator needs an eflags that is not defined
1710b57cec5SDimitry Andric       // by a previous another terminator:
1720b57cec5SDimitry Andric       // EFLAGS is live-in of the region composed by the terminators.
1730b57cec5SDimitry Andric       if (!MO.isDef())
1740b57cec5SDimitry Andric         return true;
1750b57cec5SDimitry Andric       // This terminator defines the eflags, i.e., we don't need to preserve it.
1760b57cec5SDimitry Andric       // However, we still need to check this specific terminator does not
1770b57cec5SDimitry Andric       // read a live-in value.
1780b57cec5SDimitry Andric       BreakNext = true;
1790b57cec5SDimitry Andric     }
1800b57cec5SDimitry Andric     // We found a definition of the eflags, no need to preserve them.
1810b57cec5SDimitry Andric     if (BreakNext)
1820b57cec5SDimitry Andric       return false;
1830b57cec5SDimitry Andric   }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   // None of the terminators use or define the eflags.
1860b57cec5SDimitry Andric   // Check if they are live-out, that would imply we need to preserve them.
1870b57cec5SDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors())
1880b57cec5SDimitry Andric     if (Succ->isLiveIn(X86::EFLAGS))
1890b57cec5SDimitry Andric       return true;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   return false;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric /// emitSPUpdate - Emit a series of instructions to increment / decrement the
1950b57cec5SDimitry Andric /// stack pointer by a constant value.
1960b57cec5SDimitry Andric void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
1970b57cec5SDimitry Andric                                     MachineBasicBlock::iterator &MBBI,
1980b57cec5SDimitry Andric                                     const DebugLoc &DL,
1990b57cec5SDimitry Andric                                     int64_t NumBytes, bool InEpilogue) const {
2000b57cec5SDimitry Andric   bool isSub = NumBytes < 0;
2010b57cec5SDimitry Andric   uint64_t Offset = isSub ? -NumBytes : NumBytes;
2020b57cec5SDimitry Andric   MachineInstr::MIFlag Flag =
2030b57cec5SDimitry Andric       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   uint64_t Chunk = (1LL << 31) - 1;
2060b57cec5SDimitry Andric 
2075ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
2085ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
2095ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
2105ffd83dbSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
2115ffd83dbSDimitry Andric 
2125ffd83dbSDimitry Andric   // It's ok to not take into account large chunks when probing, as the
2135ffd83dbSDimitry Andric   // allocation is split in smaller chunks anyway.
2145ffd83dbSDimitry Andric   if (EmitInlineStackProbe && !InEpilogue) {
2155ffd83dbSDimitry Andric 
2165ffd83dbSDimitry Andric     // This pseudo-instruction is going to be expanded, potentially using a
2175ffd83dbSDimitry Andric     // loop, by inlineStackProbe().
2185ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset);
2195ffd83dbSDimitry Andric     return;
2205ffd83dbSDimitry Andric   } else if (Offset > Chunk) {
2210b57cec5SDimitry Andric     // Rather than emit a long series of instructions for large offsets,
2220b57cec5SDimitry Andric     // load the offset into a register and do one sub/add
2230b57cec5SDimitry Andric     unsigned Reg = 0;
2240b57cec5SDimitry Andric     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric     if (isSub && !isEAXLiveIn(MBB))
2270b57cec5SDimitry Andric       Reg = Rax;
2280b57cec5SDimitry Andric     else
229e8d8bef9SDimitry Andric       Reg = TRI->findDeadCallerSavedReg(MBB, MBBI);
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     unsigned AddSubRROpc =
2320b57cec5SDimitry Andric         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
2330b57cec5SDimitry Andric     if (Reg) {
23404eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Reg)
2350b57cec5SDimitry Andric           .addImm(Offset)
2360b57cec5SDimitry Andric           .setMIFlag(Flag);
2370b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
2380b57cec5SDimitry Andric                              .addReg(StackPtr)
2390b57cec5SDimitry Andric                              .addReg(Reg);
2400b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2410b57cec5SDimitry Andric       return;
2420b57cec5SDimitry Andric     } else if (Offset > 8 * Chunk) {
2430b57cec5SDimitry Andric       // If we would need more than 8 add or sub instructions (a >16GB stack
2440b57cec5SDimitry Andric       // frame), it's worth spilling RAX to materialize this immediate.
2450b57cec5SDimitry Andric       //   pushq %rax
2460b57cec5SDimitry Andric       //   movabsq +-$Offset+-SlotSize, %rax
2470b57cec5SDimitry Andric       //   addq %rsp, %rax
2480b57cec5SDimitry Andric       //   xchg %rax, (%rsp)
2490b57cec5SDimitry Andric       //   movq (%rsp), %rsp
2500b57cec5SDimitry Andric       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
2510b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2520b57cec5SDimitry Andric           .addReg(Rax, RegState::Kill)
2530b57cec5SDimitry Andric           .setMIFlag(Flag);
2540b57cec5SDimitry Andric       // Subtract is not commutative, so negate the offset and always use add.
2550b57cec5SDimitry Andric       // Subtract 8 less and add 8 more to account for the PUSH we just did.
2560b57cec5SDimitry Andric       if (isSub)
2570b57cec5SDimitry Andric         Offset = -(Offset - SlotSize);
2580b57cec5SDimitry Andric       else
2590b57cec5SDimitry Andric         Offset = Offset + SlotSize;
26004eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Rax)
2610b57cec5SDimitry Andric           .addImm(Offset)
2620b57cec5SDimitry Andric           .setMIFlag(Flag);
2630b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
2640b57cec5SDimitry Andric                              .addReg(Rax)
2650b57cec5SDimitry Andric                              .addReg(StackPtr);
2660b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2670b57cec5SDimitry Andric       // Exchange the new SP in RAX with the top of the stack.
2680b57cec5SDimitry Andric       addRegOffset(
2690b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
2700b57cec5SDimitry Andric           StackPtr, false, 0);
2710b57cec5SDimitry Andric       // Load new SP from the top of the stack into RSP.
2720b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
2730b57cec5SDimitry Andric                    StackPtr, false, 0);
2740b57cec5SDimitry Andric       return;
2750b57cec5SDimitry Andric     }
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   while (Offset) {
2790b57cec5SDimitry Andric     uint64_t ThisVal = std::min(Offset, Chunk);
2800b57cec5SDimitry Andric     if (ThisVal == SlotSize) {
2810b57cec5SDimitry Andric       // Use push / pop for slot sized adjustments as a size optimization. We
2820b57cec5SDimitry Andric       // need to find a dead register when using pop.
2830b57cec5SDimitry Andric       unsigned Reg = isSub
2840b57cec5SDimitry Andric         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
285e8d8bef9SDimitry Andric         : TRI->findDeadCallerSavedReg(MBB, MBBI);
2860b57cec5SDimitry Andric       if (Reg) {
2870b57cec5SDimitry Andric         unsigned Opc = isSub
2880b57cec5SDimitry Andric           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
2890b57cec5SDimitry Andric           : (Is64Bit ? X86::POP64r  : X86::POP32r);
2900b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(Opc))
2910b57cec5SDimitry Andric             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
2920b57cec5SDimitry Andric             .setMIFlag(Flag);
2930b57cec5SDimitry Andric         Offset -= ThisVal;
2940b57cec5SDimitry Andric         continue;
2950b57cec5SDimitry Andric       }
2960b57cec5SDimitry Andric     }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
2990b57cec5SDimitry Andric         .setMIFlag(Flag);
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric     Offset -= ThisVal;
3020b57cec5SDimitry Andric   }
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
3060b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3070b57cec5SDimitry Andric     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
3080b57cec5SDimitry Andric   assert(Offset != 0 && "zero offset stack adjustment requested");
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
3110b57cec5SDimitry Andric   // is tricky.
3120b57cec5SDimitry Andric   bool UseLEA;
3130b57cec5SDimitry Andric   if (!InEpilogue) {
3140b57cec5SDimitry Andric     // Check if inserting the prologue at the beginning
3150b57cec5SDimitry Andric     // of MBB would require to use LEA operations.
3160b57cec5SDimitry Andric     // We need to use LEA operations if EFLAGS is live in, because
3170b57cec5SDimitry Andric     // it means an instruction will read it before it gets defined.
3180b57cec5SDimitry Andric     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
3190b57cec5SDimitry Andric   } else {
3200b57cec5SDimitry Andric     // If we can use LEA for SP but we shouldn't, check that none
3210b57cec5SDimitry Andric     // of the terminators uses the eflags. Otherwise we will insert
3220b57cec5SDimitry Andric     // a ADD that will redefine the eflags and break the condition.
3230b57cec5SDimitry Andric     // Alternatively, we could move the ADD, but this may not be possible
3240b57cec5SDimitry Andric     // and is an optimization anyway.
3250b57cec5SDimitry Andric     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
3260b57cec5SDimitry Andric     if (UseLEA && !STI.useLeaForSP())
3270b57cec5SDimitry Andric       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
3280b57cec5SDimitry Andric     // If that assert breaks, that means we do not do the right thing
3290b57cec5SDimitry Andric     // in canUseAsEpilogue.
3300b57cec5SDimitry Andric     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
3310b57cec5SDimitry Andric            "We shouldn't have allowed this insertion point");
3320b57cec5SDimitry Andric   }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   MachineInstrBuilder MI;
3350b57cec5SDimitry Andric   if (UseLEA) {
3360b57cec5SDimitry Andric     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
3370b57cec5SDimitry Andric                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
3380b57cec5SDimitry Andric                               StackPtr),
3390b57cec5SDimitry Andric                       StackPtr, false, Offset);
3400b57cec5SDimitry Andric   } else {
3410b57cec5SDimitry Andric     bool IsSub = Offset < 0;
3420b57cec5SDimitry Andric     uint64_t AbsOffset = IsSub ? -Offset : Offset;
343*06c3fb27SDimitry Andric     const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr)
344*06c3fb27SDimitry Andric                                : getADDriOpcode(Uses64BitFramePtr);
3450b57cec5SDimitry Andric     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
3460b57cec5SDimitry Andric              .addReg(StackPtr)
3470b57cec5SDimitry Andric              .addImm(AbsOffset);
3480b57cec5SDimitry Andric     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric   return MI;
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
3540b57cec5SDimitry Andric                                      MachineBasicBlock::iterator &MBBI,
3550b57cec5SDimitry Andric                                      bool doMergeWithPrevious) const {
3560b57cec5SDimitry Andric   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
3570b57cec5SDimitry Andric       (!doMergeWithPrevious && MBBI == MBB.end()))
3580b57cec5SDimitry Andric     return 0;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   PI = skipDebugInstructionsBackward(PI, MBB.begin());
3630b57cec5SDimitry Andric   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
3640b57cec5SDimitry Andric   // instruction, and that there are no DBG_VALUE or other instructions between
3650b57cec5SDimitry Andric   // ADD/SUB/LEA and its corresponding CFI instruction.
3660b57cec5SDimitry Andric   /* TODO: Add support for the case where there are multiple CFI instructions
3670b57cec5SDimitry Andric     below the ADD/SUB/LEA, e.g.:
3680b57cec5SDimitry Andric     ...
3690b57cec5SDimitry Andric     add
3700b57cec5SDimitry Andric     cfi_def_cfa_offset
3710b57cec5SDimitry Andric     cfi_offset
3720b57cec5SDimitry Andric     ...
3730b57cec5SDimitry Andric   */
3740b57cec5SDimitry Andric   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
3750b57cec5SDimitry Andric     PI = std::prev(PI);
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   unsigned Opc = PI->getOpcode();
3780b57cec5SDimitry Andric   int Offset = 0;
3790b57cec5SDimitry Andric 
380*06c3fb27SDimitry Andric   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD32ri) &&
3810b57cec5SDimitry Andric       PI->getOperand(0).getReg() == StackPtr) {
3820b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
3830b57cec5SDimitry Andric     Offset = PI->getOperand(2).getImm();
3840b57cec5SDimitry Andric   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
3850b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr &&
3860b57cec5SDimitry Andric              PI->getOperand(1).getReg() == StackPtr &&
3870b57cec5SDimitry Andric              PI->getOperand(2).getImm() == 1 &&
3880b57cec5SDimitry Andric              PI->getOperand(3).getReg() == X86::NoRegister &&
3890b57cec5SDimitry Andric              PI->getOperand(5).getReg() == X86::NoRegister) {
3900b57cec5SDimitry Andric     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
3910b57cec5SDimitry Andric     Offset = PI->getOperand(4).getImm();
392*06c3fb27SDimitry Andric   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB32ri) &&
3930b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr) {
3940b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
3950b57cec5SDimitry Andric     Offset = -PI->getOperand(2).getImm();
3960b57cec5SDimitry Andric   } else
3970b57cec5SDimitry Andric     return 0;
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   PI = MBB.erase(PI);
400fe6060f1SDimitry Andric   if (PI != MBB.end() && PI->isCFIInstruction()) {
401fe6060f1SDimitry Andric     auto CIs = MBB.getParent()->getFrameInstructions();
402fe6060f1SDimitry Andric     MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()];
403fe6060f1SDimitry Andric     if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset ||
404fe6060f1SDimitry Andric         CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
405fe6060f1SDimitry Andric       PI = MBB.erase(PI);
406fe6060f1SDimitry Andric   }
4070b57cec5SDimitry Andric   if (!doMergeWithPrevious)
4080b57cec5SDimitry Andric     MBBI = skipDebugInstructionsForward(PI, MBB.end());
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   return Offset;
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
4140b57cec5SDimitry Andric                                 MachineBasicBlock::iterator MBBI,
4150b57cec5SDimitry Andric                                 const DebugLoc &DL,
41681ad6265SDimitry Andric                                 const MCCFIInstruction &CFIInst,
41781ad6265SDimitry Andric                                 MachineInstr::MIFlag Flag) const {
4180b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4190b57cec5SDimitry Andric   unsigned CFIIndex = MF.addFrameInst(CFIInst);
420*06c3fb27SDimitry Andric 
421*06c3fb27SDimitry Andric   if (CFIInst.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
422*06c3fb27SDimitry Andric     MF.getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true);
423*06c3fb27SDimitry Andric 
4240b57cec5SDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
42581ad6265SDimitry Andric       .addCFIIndex(CFIIndex)
42681ad6265SDimitry Andric       .setMIFlag(Flag);
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
4295ffd83dbSDimitry Andric /// Emits Dwarf Info specifying offsets of callee saved registers and
4305ffd83dbSDimitry Andric /// frame pointer. This is called only when basic block sections are enabled.
43104eeddc0SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA(
4325ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
4335ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
4345ffd83dbSDimitry Andric   if (!hasFP(MF)) {
4355ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4365ffd83dbSDimitry Andric     return;
4375ffd83dbSDimitry Andric   }
4385ffd83dbSDimitry Andric   const MachineModuleInfo &MMI = MF.getMMI();
4395ffd83dbSDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
440e8d8bef9SDimitry Andric   const Register FramePtr = TRI->getFrameRegister(MF);
441e8d8bef9SDimitry Andric   const Register MachineFramePtr =
442e8d8bef9SDimitry Andric       STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
4435ffd83dbSDimitry Andric                                : FramePtr;
4445ffd83dbSDimitry Andric   unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true);
4455ffd83dbSDimitry Andric   // Offset = space for return address + size of the frame pointer itself.
4465ffd83dbSDimitry Andric   unsigned Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
4475ffd83dbSDimitry Andric   BuildCFI(MBB, MBBI, DebugLoc{},
4485ffd83dbSDimitry Andric            MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset));
4495ffd83dbSDimitry Andric   emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4505ffd83dbSDimitry Andric }
4515ffd83dbSDimitry Andric 
4520b57cec5SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMoves(
4530b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
4545ffd83dbSDimitry Andric     const DebugLoc &DL, bool IsPrologue) const {
4550b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4560b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
4570b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
4580b57cec5SDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
459*06c3fb27SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   // Add callee saved registers to move list.
4620b57cec5SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Calculate offsets.
4654824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
4664824e7fdSDimitry Andric     int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
46704eeddc0SDimitry Andric     Register Reg = I.getReg();
4680b57cec5SDimitry Andric     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
4695ffd83dbSDimitry Andric 
4705ffd83dbSDimitry Andric     if (IsPrologue) {
471*06c3fb27SDimitry Andric       if (X86FI->getStackPtrSaveMI()) {
472*06c3fb27SDimitry Andric         // +2*SlotSize because there is return address and ebp at the bottom
473*06c3fb27SDimitry Andric         // of the stack.
474*06c3fb27SDimitry Andric         // | retaddr |
475*06c3fb27SDimitry Andric         // | ebp     |
476*06c3fb27SDimitry Andric         // |         |<--ebp
477*06c3fb27SDimitry Andric         Offset += 2 * SlotSize;
478*06c3fb27SDimitry Andric         SmallString<64> CfaExpr;
479*06c3fb27SDimitry Andric         CfaExpr.push_back(dwarf::DW_CFA_expression);
480*06c3fb27SDimitry Andric         uint8_t buffer[16];
481*06c3fb27SDimitry Andric         CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
482*06c3fb27SDimitry Andric         CfaExpr.push_back(2);
483*06c3fb27SDimitry Andric         Register FramePtr = TRI->getFrameRegister(MF);
484*06c3fb27SDimitry Andric         const Register MachineFramePtr =
485*06c3fb27SDimitry Andric             STI.isTarget64BitILP32()
486*06c3fb27SDimitry Andric                 ? Register(getX86SubSuperRegister(FramePtr, 64))
487*06c3fb27SDimitry Andric                 : FramePtr;
488*06c3fb27SDimitry Andric         unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
489*06c3fb27SDimitry Andric         CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
490*06c3fb27SDimitry Andric         CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
491*06c3fb27SDimitry Andric         BuildCFI(MBB, MBBI, DL,
492*06c3fb27SDimitry Andric                  MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
493*06c3fb27SDimitry Andric                  MachineInstr::FrameSetup);
494*06c3fb27SDimitry Andric       } else {
4950b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
4960b57cec5SDimitry Andric                  MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
497*06c3fb27SDimitry Andric       }
4985ffd83dbSDimitry Andric     } else {
4995ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
5005ffd83dbSDimitry Andric                MCCFIInstruction::createRestore(nullptr, DwarfReg));
5015ffd83dbSDimitry Andric     }
5020b57cec5SDimitry Andric   }
503*06c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
504*06c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
505*06c3fb27SDimitry Andric     int64_t Offset = MFI.getObjectOffset(FI) + 2 * SlotSize;
506*06c3fb27SDimitry Andric     SmallString<64> CfaExpr;
507*06c3fb27SDimitry Andric     Register FramePtr = TRI->getFrameRegister(MF);
508*06c3fb27SDimitry Andric     const Register MachineFramePtr =
509*06c3fb27SDimitry Andric         STI.isTarget64BitILP32()
510*06c3fb27SDimitry Andric             ? Register(getX86SubSuperRegister(FramePtr, 64))
511*06c3fb27SDimitry Andric             : FramePtr;
512*06c3fb27SDimitry Andric     unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
513*06c3fb27SDimitry Andric     CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
514*06c3fb27SDimitry Andric     uint8_t buffer[16];
515*06c3fb27SDimitry Andric     CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
516*06c3fb27SDimitry Andric     CfaExpr.push_back(dwarf::DW_OP_deref);
517*06c3fb27SDimitry Andric 
518*06c3fb27SDimitry Andric     SmallString<64> DefCfaExpr;
519*06c3fb27SDimitry Andric     DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
520*06c3fb27SDimitry Andric     DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer));
521*06c3fb27SDimitry Andric     DefCfaExpr.append(CfaExpr.str());
522*06c3fb27SDimitry Andric     // DW_CFA_def_cfa_expression: DW_OP_breg5 offset, DW_OP_deref
523*06c3fb27SDimitry Andric     BuildCFI(MBB, MBBI, DL,
524*06c3fb27SDimitry Andric              MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()),
525*06c3fb27SDimitry Andric              MachineInstr::FrameSetup);
526*06c3fb27SDimitry Andric   }
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric 
52981ad6265SDimitry Andric void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
53081ad6265SDimitry Andric                                             MachineBasicBlock &MBB) const {
53181ad6265SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
53281ad6265SDimitry Andric 
53381ad6265SDimitry Andric   // Insertion point.
53481ad6265SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
53581ad6265SDimitry Andric 
53681ad6265SDimitry Andric   // Fake a debug loc.
53781ad6265SDimitry Andric   DebugLoc DL;
53881ad6265SDimitry Andric   if (MBBI != MBB.end())
53981ad6265SDimitry Andric     DL = MBBI->getDebugLoc();
54081ad6265SDimitry Andric 
54181ad6265SDimitry Andric   // Zero out FP stack if referenced. Do this outside of the loop below so that
54281ad6265SDimitry Andric   // it's done only once.
54381ad6265SDimitry Andric   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
54481ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits()) {
54581ad6265SDimitry Andric     if (!X86::RFP80RegClass.contains(Reg))
54681ad6265SDimitry Andric       continue;
54781ad6265SDimitry Andric 
54881ad6265SDimitry Andric     unsigned NumFPRegs = ST.is64Bit() ? 8 : 7;
54981ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
55081ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0));
55181ad6265SDimitry Andric 
55281ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
55381ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0);
55481ad6265SDimitry Andric     break;
55581ad6265SDimitry Andric   }
55681ad6265SDimitry Andric 
55781ad6265SDimitry Andric   // For GPRs, we only care to clear out the 32-bit register.
55881ad6265SDimitry Andric   BitVector GPRsToZero(TRI->getNumRegs());
55981ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits())
56081ad6265SDimitry Andric     if (TRI->isGeneralPurposeRegister(MF, Reg)) {
561*06c3fb27SDimitry Andric       GPRsToZero.set(getX86SubSuperRegister(Reg, 32));
56281ad6265SDimitry Andric       RegsToZero.reset(Reg);
56381ad6265SDimitry Andric     }
56481ad6265SDimitry Andric 
56581ad6265SDimitry Andric   for (MCRegister Reg : GPRsToZero.set_bits())
56681ad6265SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::XOR32rr), Reg)
56781ad6265SDimitry Andric         .addReg(Reg, RegState::Undef)
56881ad6265SDimitry Andric         .addReg(Reg, RegState::Undef);
56981ad6265SDimitry Andric 
57081ad6265SDimitry Andric   // Zero out registers.
57181ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits()) {
57281ad6265SDimitry Andric     if (ST.hasMMX() && X86::VR64RegClass.contains(Reg))
57381ad6265SDimitry Andric       // FIXME: Ignore MMX registers?
57481ad6265SDimitry Andric       continue;
57581ad6265SDimitry Andric 
57681ad6265SDimitry Andric     unsigned XorOp;
57781ad6265SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
57881ad6265SDimitry Andric       // XMM#
57981ad6265SDimitry Andric       if (!ST.hasSSE1())
58081ad6265SDimitry Andric         continue;
58181ad6265SDimitry Andric       XorOp = X86::PXORrr;
58281ad6265SDimitry Andric     } else if (X86::VR256RegClass.contains(Reg)) {
58381ad6265SDimitry Andric       // YMM#
58481ad6265SDimitry Andric       if (!ST.hasAVX())
58581ad6265SDimitry Andric         continue;
58681ad6265SDimitry Andric       XorOp = X86::VPXORrr;
58781ad6265SDimitry Andric     } else if (X86::VR512RegClass.contains(Reg)) {
58881ad6265SDimitry Andric       // ZMM#
58981ad6265SDimitry Andric       if (!ST.hasAVX512())
59081ad6265SDimitry Andric         continue;
59181ad6265SDimitry Andric       XorOp = X86::VPXORYrr;
59281ad6265SDimitry Andric     } else if (X86::VK1RegClass.contains(Reg) ||
59381ad6265SDimitry Andric                X86::VK2RegClass.contains(Reg) ||
59481ad6265SDimitry Andric                X86::VK4RegClass.contains(Reg) ||
59581ad6265SDimitry Andric                X86::VK8RegClass.contains(Reg) ||
59681ad6265SDimitry Andric                X86::VK16RegClass.contains(Reg)) {
59781ad6265SDimitry Andric       if (!ST.hasVLX())
59881ad6265SDimitry Andric         continue;
59981ad6265SDimitry Andric       XorOp = ST.hasBWI() ? X86::KXORQrr : X86::KXORWrr;
60081ad6265SDimitry Andric     } else {
60181ad6265SDimitry Andric       continue;
60281ad6265SDimitry Andric     }
60381ad6265SDimitry Andric 
60481ad6265SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(XorOp), Reg)
60581ad6265SDimitry Andric       .addReg(Reg, RegState::Undef)
60681ad6265SDimitry Andric       .addReg(Reg, RegState::Undef);
60781ad6265SDimitry Andric   }
60881ad6265SDimitry Andric }
60981ad6265SDimitry Andric 
6104824e7fdSDimitry Andric void X86FrameLowering::emitStackProbe(
6114824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
6124824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
613bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
6140b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6150b57cec5SDimitry Andric   if (STI.isTargetWindowsCoreCLR()) {
6160b57cec5SDimitry Andric     if (InProlog) {
6175ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING))
6185ffd83dbSDimitry Andric           .addImm(0 /* no explicit stack size */);
6190b57cec5SDimitry Andric     } else {
6200b57cec5SDimitry Andric       emitStackProbeInline(MF, MBB, MBBI, DL, false);
6210b57cec5SDimitry Andric     }
6220b57cec5SDimitry Andric   } else {
6234824e7fdSDimitry Andric     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
6274824e7fdSDimitry Andric bool X86FrameLowering::stackProbeFunctionModifiesSP() const {
6284824e7fdSDimitry Andric   return STI.isOSWindows() && !STI.isTargetWin64();
6294824e7fdSDimitry Andric }
6304824e7fdSDimitry Andric 
6310b57cec5SDimitry Andric void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
6320b57cec5SDimitry Andric                                         MachineBasicBlock &PrologMBB) const {
6335ffd83dbSDimitry Andric   auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
6345ffd83dbSDimitry Andric     return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
6355ffd83dbSDimitry Andric   });
6365ffd83dbSDimitry Andric   if (Where != PrologMBB.end()) {
6375ffd83dbSDimitry Andric     DebugLoc DL = PrologMBB.findDebugLoc(Where);
6385ffd83dbSDimitry Andric     emitStackProbeInline(MF, PrologMBB, Where, DL, true);
6395ffd83dbSDimitry Andric     Where->eraseFromParent();
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
6440b57cec5SDimitry Andric                                             MachineBasicBlock &MBB,
6450b57cec5SDimitry Andric                                             MachineBasicBlock::iterator MBBI,
6460b57cec5SDimitry Andric                                             const DebugLoc &DL,
6470b57cec5SDimitry Andric                                             bool InProlog) const {
6480b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6495ffd83dbSDimitry Andric   if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
6505ffd83dbSDimitry Andric     emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
6515ffd83dbSDimitry Andric   else
6525ffd83dbSDimitry Andric     emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
6535ffd83dbSDimitry Andric }
6545ffd83dbSDimitry Andric 
6555ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGeneric(
6565ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
6575ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
6585ffd83dbSDimitry Andric   MachineInstr &AllocWithProbe = *MBBI;
6595ffd83dbSDimitry Andric   uint64_t Offset = AllocWithProbe.getOperand(0).getImm();
6605ffd83dbSDimitry Andric 
6615ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6625ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6635ffd83dbSDimitry Andric   assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
6645ffd83dbSDimitry Andric          "different expansion expected for CoreCLR 64 bit");
6655ffd83dbSDimitry Andric 
6665ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6675ffd83dbSDimitry Andric   uint64_t ProbeChunk = StackProbeSize * 8;
6685ffd83dbSDimitry Andric 
669eaeb601bSDimitry Andric   uint64_t MaxAlign =
670fe6060f1SDimitry Andric       TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
671eaeb601bSDimitry Andric 
6725ffd83dbSDimitry Andric   // Synthesize a loop or unroll it, depending on the number of iterations.
673eaeb601bSDimitry Andric   // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
674eaeb601bSDimitry Andric   // between the unaligned rsp and current rsp.
6755ffd83dbSDimitry Andric   if (Offset > ProbeChunk) {
676eaeb601bSDimitry Andric     emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
677eaeb601bSDimitry Andric                                     MaxAlign % StackProbeSize);
6785ffd83dbSDimitry Andric   } else {
679eaeb601bSDimitry Andric     emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
680eaeb601bSDimitry Andric                                      MaxAlign % StackProbeSize);
6815ffd83dbSDimitry Andric   }
6825ffd83dbSDimitry Andric }
6835ffd83dbSDimitry Andric 
6845ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericBlock(
6855ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
686eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
687eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
6885ffd83dbSDimitry Andric 
689fe6060f1SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
690fe6060f1SDimitry Andric   const bool HasFP = hasFP(MF);
6915ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6925ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6935ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
6945ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6955ffd83dbSDimitry Andric 
696eaeb601bSDimitry Andric   uint64_t CurrentOffset = 0;
697eaeb601bSDimitry Andric 
698eaeb601bSDimitry Andric   assert(AlignOffset < StackProbeSize);
699eaeb601bSDimitry Andric 
700eaeb601bSDimitry Andric   // If the offset is so small it fits within a page, there's nothing to do.
701eaeb601bSDimitry Andric   if (StackProbeSize < Offset + AlignOffset) {
702eaeb601bSDimitry Andric 
703bdd1243dSDimitry Andric     uint64_t StackAdjustment = StackProbeSize - AlignOffset;
704bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
705eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
706fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
707bdd1243dSDimitry Andric       BuildCFI(
708bdd1243dSDimitry Andric           MBB, MBBI, DL,
709bdd1243dSDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
710fe6060f1SDimitry Andric     }
711eaeb601bSDimitry Andric 
712eaeb601bSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
713eaeb601bSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
714eaeb601bSDimitry Andric                  StackPtr, false, 0)
715eaeb601bSDimitry Andric         .addImm(0)
716eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
717eaeb601bSDimitry Andric     NumFrameExtraProbe++;
718eaeb601bSDimitry Andric     CurrentOffset = StackProbeSize - AlignOffset;
719eaeb601bSDimitry Andric   }
720eaeb601bSDimitry Andric 
721eaeb601bSDimitry Andric   // For the next N - 1 pages, just probe. I tried to take advantage of
7225ffd83dbSDimitry Andric   // natural probes but it implies much more logic and there was very few
7235ffd83dbSDimitry Andric   // interesting natural probes to interleave.
7245ffd83dbSDimitry Andric   while (CurrentOffset + StackProbeSize < Offset) {
725bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
7265ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
7275ffd83dbSDimitry Andric 
728fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
729fe6060f1SDimitry Andric       BuildCFI(
730fe6060f1SDimitry Andric           MBB, MBBI, DL,
731fe6060f1SDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
732fe6060f1SDimitry Andric     }
7335ffd83dbSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
7345ffd83dbSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
7355ffd83dbSDimitry Andric                  StackPtr, false, 0)
7365ffd83dbSDimitry Andric         .addImm(0)
7375ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
7385ffd83dbSDimitry Andric     NumFrameExtraProbe++;
7395ffd83dbSDimitry Andric     CurrentOffset += StackProbeSize;
7405ffd83dbSDimitry Andric   }
7415ffd83dbSDimitry Andric 
742eaeb601bSDimitry Andric   // No need to probe the tail, it is smaller than a Page.
7435ffd83dbSDimitry Andric   uint64_t ChunkSize = Offset - CurrentOffset;
744bdd1243dSDimitry Andric   if (ChunkSize == SlotSize) {
745bdd1243dSDimitry Andric     // Use push for slot sized adjustments as a size optimization,
746bdd1243dSDimitry Andric     // like emitSPUpdate does when not probing.
747bdd1243dSDimitry Andric     unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
748bdd1243dSDimitry Andric     unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
749bdd1243dSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc))
750bdd1243dSDimitry Andric         .addReg(Reg, RegState::Undef)
7515ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
752bdd1243dSDimitry Andric   } else {
753bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
754bdd1243dSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
755bdd1243dSDimitry Andric   }
756fe6060f1SDimitry Andric   // No need to adjust Dwarf CFA offset here, the last position of the stack has
757fe6060f1SDimitry Andric   // been defined
7585ffd83dbSDimitry Andric }
7595ffd83dbSDimitry Andric 
7605ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericLoop(
7615ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
762eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
763eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
7645ffd83dbSDimitry Andric   assert(Offset && "null offset");
7655ffd83dbSDimitry Andric 
766bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
767bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
768bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
769bdd1243dSDimitry Andric 
77004eeddc0SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
77104eeddc0SDimitry Andric   const bool HasFP = hasFP(MF);
7725ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
7735ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
7745ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
7755ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
7765ffd83dbSDimitry Andric 
777eaeb601bSDimitry Andric   if (AlignOffset) {
778eaeb601bSDimitry Andric     if (AlignOffset < StackProbeSize) {
779eaeb601bSDimitry Andric       // Perform a first smaller allocation followed by a probe.
780bdd1243dSDimitry Andric       BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
781eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
782eaeb601bSDimitry Andric 
783eaeb601bSDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
784eaeb601bSDimitry Andric                        .setMIFlag(MachineInstr::FrameSetup),
785eaeb601bSDimitry Andric                    StackPtr, false, 0)
786eaeb601bSDimitry Andric           .addImm(0)
787eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
788eaeb601bSDimitry Andric       NumFrameExtraProbe++;
789eaeb601bSDimitry Andric       Offset -= AlignOffset;
790eaeb601bSDimitry Andric     }
791eaeb601bSDimitry Andric   }
792eaeb601bSDimitry Andric 
7935ffd83dbSDimitry Andric   // Synthesize a loop
7945ffd83dbSDimitry Andric   NumFrameLoopProbe++;
7955ffd83dbSDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
7965ffd83dbSDimitry Andric 
7975ffd83dbSDimitry Andric   MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7985ffd83dbSDimitry Andric   MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7995ffd83dbSDimitry Andric 
8005ffd83dbSDimitry Andric   MachineFunction::iterator MBBIter = ++MBB.getIterator();
8015ffd83dbSDimitry Andric   MF.insert(MBBIter, testMBB);
8025ffd83dbSDimitry Andric   MF.insert(MBBIter, tailMBB);
8035ffd83dbSDimitry Andric 
8048c6f6c0cSDimitry Andric   Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
8058c6f6c0cSDimitry Andric                               : Is64Bit         ? X86::R11D
8068c6f6c0cSDimitry Andric                                                 : X86::EAX;
80704eeddc0SDimitry Andric 
8085ffd83dbSDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
8095ffd83dbSDimitry Andric       .addReg(StackPtr)
8105ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8115ffd83dbSDimitry Andric 
8125ffd83dbSDimitry Andric   // save loop bound
8135ffd83dbSDimitry Andric   {
81404eeddc0SDimitry Andric     const unsigned BoundOffset = alignDown(Offset, StackProbeSize);
815*06c3fb27SDimitry Andric     const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
816eaeb601bSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
8175ffd83dbSDimitry Andric         .addReg(FinalStackProbed)
81804eeddc0SDimitry Andric         .addImm(BoundOffset)
8195ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
82004eeddc0SDimitry Andric 
82104eeddc0SDimitry Andric     // while in the loop, use loop-invariant reg for CFI,
82204eeddc0SDimitry Andric     // instead of the stack pointer, which changes during the loop
82304eeddc0SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
82404eeddc0SDimitry Andric       // x32 uses the same DWARF register numbers as x86-64,
82504eeddc0SDimitry Andric       // so there isn't a register number for r11d, we must use r11 instead
82604eeddc0SDimitry Andric       const Register DwarfFinalStackProbed =
82704eeddc0SDimitry Andric           STI.isTarget64BitILP32()
82804eeddc0SDimitry Andric               ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
82904eeddc0SDimitry Andric               : FinalStackProbed;
83004eeddc0SDimitry Andric 
83104eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
83204eeddc0SDimitry Andric                MCCFIInstruction::createDefCfaRegister(
83304eeddc0SDimitry Andric                    nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
83404eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
83504eeddc0SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
83604eeddc0SDimitry Andric     }
8375ffd83dbSDimitry Andric   }
8385ffd83dbSDimitry Andric 
8395ffd83dbSDimitry Andric   // allocate a page
840bdd1243dSDimitry Andric   BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
841bdd1243dSDimitry Andric                        /*InEpilogue=*/false)
8425ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8435ffd83dbSDimitry Andric 
8445ffd83dbSDimitry Andric   // touch the page
8455ffd83dbSDimitry Andric   addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
8465ffd83dbSDimitry Andric                    .setMIFlag(MachineInstr::FrameSetup),
8475ffd83dbSDimitry Andric                StackPtr, false, 0)
8485ffd83dbSDimitry Andric       .addImm(0)
8495ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8505ffd83dbSDimitry Andric 
8515ffd83dbSDimitry Andric   // cmp with stack pointer bound
8525ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
8535ffd83dbSDimitry Andric       .addReg(StackPtr)
8545ffd83dbSDimitry Andric       .addReg(FinalStackProbed)
8555ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8565ffd83dbSDimitry Andric 
8575ffd83dbSDimitry Andric   // jump
8585ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(X86::JCC_1))
8595ffd83dbSDimitry Andric       .addMBB(testMBB)
8605ffd83dbSDimitry Andric       .addImm(X86::COND_NE)
8615ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8625ffd83dbSDimitry Andric   testMBB->addSuccessor(testMBB);
8635ffd83dbSDimitry Andric   testMBB->addSuccessor(tailMBB);
8645ffd83dbSDimitry Andric 
8655ffd83dbSDimitry Andric   // BB management
8665ffd83dbSDimitry Andric   tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
8675ffd83dbSDimitry Andric   tailMBB->transferSuccessorsAndUpdatePHIs(&MBB);
8685ffd83dbSDimitry Andric   MBB.addSuccessor(testMBB);
8695ffd83dbSDimitry Andric 
8705ffd83dbSDimitry Andric   // handle tail
871bdd1243dSDimitry Andric   const uint64_t TailOffset = Offset % StackProbeSize;
87204eeddc0SDimitry Andric   MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
8735ffd83dbSDimitry Andric   if (TailOffset) {
874bdd1243dSDimitry Andric     BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
875bdd1243dSDimitry Andric                          /*InEpilogue=*/false)
8765ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
8775ffd83dbSDimitry Andric   }
8785ffd83dbSDimitry Andric 
87904eeddc0SDimitry Andric   // after the loop, switch back to stack pointer for CFI
88004eeddc0SDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
88104eeddc0SDimitry Andric     // x32 uses the same DWARF register numbers as x86-64,
88204eeddc0SDimitry Andric     // so there isn't a register number for esp, we must use rsp instead
88304eeddc0SDimitry Andric     const Register DwarfStackPtr =
88404eeddc0SDimitry Andric         STI.isTarget64BitILP32()
88504eeddc0SDimitry Andric             ? Register(getX86SubSuperRegister(StackPtr, 64))
88604eeddc0SDimitry Andric             : Register(StackPtr);
88704eeddc0SDimitry Andric 
88804eeddc0SDimitry Andric     BuildCFI(*tailMBB, TailMBBIter, DL,
88904eeddc0SDimitry Andric              MCCFIInstruction::createDefCfaRegister(
89004eeddc0SDimitry Andric                  nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
89104eeddc0SDimitry Andric   }
89204eeddc0SDimitry Andric 
8935ffd83dbSDimitry Andric   // Update Live In information
8945ffd83dbSDimitry Andric   recomputeLiveIns(*testMBB);
8955ffd83dbSDimitry Andric   recomputeLiveIns(*tailMBB);
8965ffd83dbSDimitry Andric }
8975ffd83dbSDimitry Andric 
8985ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
8995ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
9005ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
9015ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
9020b57cec5SDimitry Andric   assert(STI.is64Bit() && "different expansion needed for 32 bit");
9030b57cec5SDimitry Andric   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
9040b57cec5SDimitry Andric   const TargetInstrInfo &TII = *STI.getInstrInfo();
9050b57cec5SDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
9060b57cec5SDimitry Andric 
907bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
908bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
909bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
910bdd1243dSDimitry Andric 
9110b57cec5SDimitry Andric   // RAX contains the number of bytes of desired stack adjustment.
9120b57cec5SDimitry Andric   // The handling here assumes this value has already been updated so as to
9130b57cec5SDimitry Andric   // maintain stack alignment.
9140b57cec5SDimitry Andric   //
9150b57cec5SDimitry Andric   // We need to exit with RSP modified by this amount and execute suitable
9160b57cec5SDimitry Andric   // page touches to notify the OS that we're growing the stack responsibly.
9170b57cec5SDimitry Andric   // All stack probing must be done without modifying RSP.
9180b57cec5SDimitry Andric   //
9190b57cec5SDimitry Andric   // MBB:
9200b57cec5SDimitry Andric   //    SizeReg = RAX;
9210b57cec5SDimitry Andric   //    ZeroReg = 0
9220b57cec5SDimitry Andric   //    CopyReg = RSP
9230b57cec5SDimitry Andric   //    Flags, TestReg = CopyReg - SizeReg
9240b57cec5SDimitry Andric   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
9250b57cec5SDimitry Andric   //    LimitReg = gs magic thread env access
9260b57cec5SDimitry Andric   //    if FinalReg >= LimitReg goto ContinueMBB
9270b57cec5SDimitry Andric   // RoundBB:
9280b57cec5SDimitry Andric   //    RoundReg = page address of FinalReg
9290b57cec5SDimitry Andric   // LoopMBB:
9300b57cec5SDimitry Andric   //    LoopReg = PHI(LimitReg,ProbeReg)
9310b57cec5SDimitry Andric   //    ProbeReg = LoopReg - PageSize
9320b57cec5SDimitry Andric   //    [ProbeReg] = 0
9330b57cec5SDimitry Andric   //    if (ProbeReg > RoundReg) goto LoopMBB
9340b57cec5SDimitry Andric   // ContinueMBB:
9350b57cec5SDimitry Andric   //    RSP = RSP - RAX
9360b57cec5SDimitry Andric   //    [rest of original MBB]
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // Set up the new basic blocks
9390b57cec5SDimitry Andric   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9400b57cec5SDimitry Andric   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9410b57cec5SDimitry Andric   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
9440b57cec5SDimitry Andric   MF.insert(MBBIter, RoundMBB);
9450b57cec5SDimitry Andric   MF.insert(MBBIter, LoopMBB);
9460b57cec5SDimitry Andric   MF.insert(MBBIter, ContinueMBB);
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   // Split MBB and move the tail portion down to ContinueMBB.
9490b57cec5SDimitry Andric   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
9500b57cec5SDimitry Andric   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
9510b57cec5SDimitry Andric   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   // Some useful constants
9540b57cec5SDimitry Andric   const int64_t ThreadEnvironmentStackLimit = 0x10;
9550b57cec5SDimitry Andric   const int64_t PageSize = 0x1000;
9560b57cec5SDimitry Andric   const int64_t PageMask = ~(PageSize - 1);
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric   // Registers we need. For the normal case we use virtual
9590b57cec5SDimitry Andric   // registers. For the prolog expansion we use RAX, RCX and RDX.
9600b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
9610b57cec5SDimitry Andric   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
9620b57cec5SDimitry Andric   const Register SizeReg = InProlog ? X86::RAX
9630b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9640b57cec5SDimitry Andric                  ZeroReg = InProlog ? X86::RCX
9650b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9660b57cec5SDimitry Andric                  CopyReg = InProlog ? X86::RDX
9670b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9680b57cec5SDimitry Andric                  TestReg = InProlog ? X86::RDX
9690b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9700b57cec5SDimitry Andric                  FinalReg = InProlog ? X86::RDX
9710b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
9720b57cec5SDimitry Andric                  RoundedReg = InProlog ? X86::RDX
9730b57cec5SDimitry Andric                                        : MRI.createVirtualRegister(RegClass),
9740b57cec5SDimitry Andric                  LimitReg = InProlog ? X86::RCX
9750b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
9760b57cec5SDimitry Andric                  JoinReg = InProlog ? X86::RCX
9770b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
9780b57cec5SDimitry Andric                  ProbeReg = InProlog ? X86::RCX
9790b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass);
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   // SP-relative offsets where we can save RCX and RDX.
9820b57cec5SDimitry Andric   int64_t RCXShadowSlot = 0;
9830b57cec5SDimitry Andric   int64_t RDXShadowSlot = 0;
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   // If inlining in the prolog, save RCX and RDX.
9860b57cec5SDimitry Andric   if (InProlog) {
9870b57cec5SDimitry Andric     // Compute the offsets. We need to account for things already
9880b57cec5SDimitry Andric     // pushed onto the stack at this point: return address, frame
9890b57cec5SDimitry Andric     // pointer (if used), and callee saves.
9900b57cec5SDimitry Andric     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9910b57cec5SDimitry Andric     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
9920b57cec5SDimitry Andric     const bool HasFP = hasFP(MF);
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric     // Check if we need to spill RCX and/or RDX.
9950b57cec5SDimitry Andric     // Here we assume that no earlier prologue instruction changes RCX and/or
9960b57cec5SDimitry Andric     // RDX, so checking the block live-ins is enough.
9970b57cec5SDimitry Andric     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
9980b57cec5SDimitry Andric     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
9990b57cec5SDimitry Andric     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
10000b57cec5SDimitry Andric     // Assign the initial slot to both registers, then change RDX's slot if both
10010b57cec5SDimitry Andric     // need to be spilled.
10020b57cec5SDimitry Andric     if (IsRCXLiveIn)
10030b57cec5SDimitry Andric       RCXShadowSlot = InitSlot;
10040b57cec5SDimitry Andric     if (IsRDXLiveIn)
10050b57cec5SDimitry Andric       RDXShadowSlot = InitSlot;
10060b57cec5SDimitry Andric     if (IsRDXLiveIn && IsRCXLiveIn)
10070b57cec5SDimitry Andric       RDXShadowSlot += 8;
10080b57cec5SDimitry Andric     // Emit the saves if needed.
10090b57cec5SDimitry Andric     if (IsRCXLiveIn)
10100b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
10110b57cec5SDimitry Andric                    RCXShadowSlot)
10120b57cec5SDimitry Andric           .addReg(X86::RCX);
10130b57cec5SDimitry Andric     if (IsRDXLiveIn)
10140b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
10150b57cec5SDimitry Andric                    RDXShadowSlot)
10160b57cec5SDimitry Andric           .addReg(X86::RDX);
10170b57cec5SDimitry Andric   } else {
10180b57cec5SDimitry Andric     // Not in the prolog. Copy RAX to a virtual reg.
10190b57cec5SDimitry Andric     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   // Add code to MBB to check for overflow and set the new target stack pointer
10230b57cec5SDimitry Andric   // to zero if so.
10240b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
10250b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef)
10260b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef);
10270b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
10280b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
10290b57cec5SDimitry Andric       .addReg(CopyReg)
10300b57cec5SDimitry Andric       .addReg(SizeReg);
10310b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
10320b57cec5SDimitry Andric       .addReg(TestReg)
10330b57cec5SDimitry Andric       .addReg(ZeroReg)
10340b57cec5SDimitry Andric       .addImm(X86::COND_B);
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric   // FinalReg now holds final stack pointer value, or zero if
10370b57cec5SDimitry Andric   // allocation would overflow. Compare against the current stack
10380b57cec5SDimitry Andric   // limit from the thread environment block. Note this limit is the
10390b57cec5SDimitry Andric   // lowest touched page on the stack, not the point at which the OS
10400b57cec5SDimitry Andric   // will cause an overflow exception, so this is just an optimization
10410b57cec5SDimitry Andric   // to avoid unnecessarily touching pages that are below the current
10420b57cec5SDimitry Andric   // SP but already committed to the stack by the OS.
10430b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
10440b57cec5SDimitry Andric       .addReg(0)
10450b57cec5SDimitry Andric       .addImm(1)
10460b57cec5SDimitry Andric       .addReg(0)
10470b57cec5SDimitry Andric       .addImm(ThreadEnvironmentStackLimit)
10480b57cec5SDimitry Andric       .addReg(X86::GS);
10490b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
10500b57cec5SDimitry Andric   // Jump if the desired stack pointer is at or above the stack limit.
10510b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   // Add code to roundMBB to round the final stack pointer to a page boundary.
10540b57cec5SDimitry Andric   RoundMBB->addLiveIn(FinalReg);
10550b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
10560b57cec5SDimitry Andric       .addReg(FinalReg)
10570b57cec5SDimitry Andric       .addImm(PageMask);
10580b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   // LimitReg now holds the current stack limit, RoundedReg page-rounded
10610b57cec5SDimitry Andric   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
10620b57cec5SDimitry Andric   // and probe until we reach RoundedReg.
10630b57cec5SDimitry Andric   if (!InProlog) {
10640b57cec5SDimitry Andric     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
10650b57cec5SDimitry Andric         .addReg(LimitReg)
10660b57cec5SDimitry Andric         .addMBB(RoundMBB)
10670b57cec5SDimitry Andric         .addReg(ProbeReg)
10680b57cec5SDimitry Andric         .addMBB(LoopMBB);
10690b57cec5SDimitry Andric   }
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   LoopMBB->addLiveIn(JoinReg);
10720b57cec5SDimitry Andric   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
10730b57cec5SDimitry Andric                false, -PageSize);
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   // Probe by storing a byte onto the stack.
10760b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
10770b57cec5SDimitry Andric       .addReg(ProbeReg)
10780b57cec5SDimitry Andric       .addImm(1)
10790b57cec5SDimitry Andric       .addReg(0)
10800b57cec5SDimitry Andric       .addImm(0)
10810b57cec5SDimitry Andric       .addReg(0)
10820b57cec5SDimitry Andric       .addImm(0);
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric   LoopMBB->addLiveIn(RoundedReg);
10850b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
10860b57cec5SDimitry Andric       .addReg(RoundedReg)
10870b57cec5SDimitry Andric       .addReg(ProbeReg);
10880b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   // If in prolog, restore RDX and RCX.
10930b57cec5SDimitry Andric   if (InProlog) {
10940b57cec5SDimitry Andric     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
10950b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
10960b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RCX),
10970b57cec5SDimitry Andric                    X86::RSP, false, RCXShadowSlot);
10980b57cec5SDimitry Andric     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
10990b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
11000b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RDX),
11010b57cec5SDimitry Andric                    X86::RSP, false, RDXShadowSlot);
11020b57cec5SDimitry Andric   }
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric   // Now that the probing is done, add code to continueMBB to update
11050b57cec5SDimitry Andric   // the stack pointer for real.
11060b57cec5SDimitry Andric   ContinueMBB->addLiveIn(SizeReg);
11070b57cec5SDimitry Andric   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
11080b57cec5SDimitry Andric       .addReg(X86::RSP)
11090b57cec5SDimitry Andric       .addReg(SizeReg);
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Add the control flow edges we need.
11120b57cec5SDimitry Andric   MBB.addSuccessor(ContinueMBB);
11130b57cec5SDimitry Andric   MBB.addSuccessor(RoundMBB);
11140b57cec5SDimitry Andric   RoundMBB->addSuccessor(LoopMBB);
11150b57cec5SDimitry Andric   LoopMBB->addSuccessor(ContinueMBB);
11160b57cec5SDimitry Andric   LoopMBB->addSuccessor(LoopMBB);
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   // Mark all the instructions added to the prolog as frame setup.
11190b57cec5SDimitry Andric   if (InProlog) {
11200b57cec5SDimitry Andric     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
11210b57cec5SDimitry Andric       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
11220b57cec5SDimitry Andric     }
11230b57cec5SDimitry Andric     for (MachineInstr &MI : *RoundMBB) {
11240b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11250b57cec5SDimitry Andric     }
11260b57cec5SDimitry Andric     for (MachineInstr &MI : *LoopMBB) {
11270b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11280b57cec5SDimitry Andric     }
1129bdd1243dSDimitry Andric     for (MachineInstr &MI :
1130bdd1243dSDimitry Andric          llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1131bdd1243dSDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11320b57cec5SDimitry Andric     }
11330b57cec5SDimitry Andric   }
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric 
11364824e7fdSDimitry Andric void X86FrameLowering::emitStackProbeCall(
11374824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
11384824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1139bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
11400b57cec5SDimitry Andric   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
11410b57cec5SDimitry Andric 
11420946e70aSDimitry Andric   // FIXME: Add indirect thunk support and remove this.
11430946e70aSDimitry Andric   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
11440b57cec5SDimitry Andric     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
11450946e70aSDimitry Andric                        "code model and indirect thunks not yet implemented.");
11460b57cec5SDimitry Andric 
1147bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1148bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
1149bdd1243dSDimitry Andric          "Stack probe calls will clobber live EFLAGS.");
1150bdd1243dSDimitry Andric 
11510b57cec5SDimitry Andric   unsigned CallOp;
11520b57cec5SDimitry Andric   if (Is64Bit)
11530b57cec5SDimitry Andric     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
11540b57cec5SDimitry Andric   else
11550b57cec5SDimitry Andric     CallOp = X86::CALLpcrel32;
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   MachineInstrBuilder CI;
11600b57cec5SDimitry Andric   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   // All current stack probes take AX and SP as input, clobber flags, and
11630b57cec5SDimitry Andric   // preserve all registers. x86_64 probes leave RSP unmodified.
11640b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
11650b57cec5SDimitry Andric     // For the large code model, we have to call through a register. Use R11,
11660b57cec5SDimitry Andric     // as it is scratch in all supported calling conventions.
11670b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
11680b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11690b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
11700b57cec5SDimitry Andric   } else {
11710b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
11720b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11730b57cec5SDimitry Andric   }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
11760b57cec5SDimitry Andric   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
11770b57cec5SDimitry Andric   CI.addReg(AX, RegState::Implicit)
11780b57cec5SDimitry Andric       .addReg(SP, RegState::Implicit)
11790b57cec5SDimitry Andric       .addReg(AX, RegState::Define | RegState::Implicit)
11800b57cec5SDimitry Andric       .addReg(SP, RegState::Define | RegState::Implicit)
11810b57cec5SDimitry Andric       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11820b57cec5SDimitry Andric 
11834824e7fdSDimitry Andric   MachineInstr *ModInst = CI;
11840b57cec5SDimitry Andric   if (STI.isTargetWin64() || !STI.isOSWindows()) {
11850b57cec5SDimitry Andric     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
11860b57cec5SDimitry Andric     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
11870b57cec5SDimitry Andric     // themselves. They also does not clobber %rax so we can reuse it when
11880b57cec5SDimitry Andric     // adjusting %rsp.
11890b57cec5SDimitry Andric     // All other platforms do not specify a particular ABI for the stack probe
11900b57cec5SDimitry Andric     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
11914824e7fdSDimitry Andric     ModInst =
11920b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
11930b57cec5SDimitry Andric             .addReg(SP)
11940b57cec5SDimitry Andric             .addReg(AX);
11950b57cec5SDimitry Andric   }
11960b57cec5SDimitry Andric 
11974824e7fdSDimitry Andric   // DebugInfo variable locations -- if there's an instruction number for the
11984824e7fdSDimitry Andric   // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
11994824e7fdSDimitry Andric   // modifies SP.
12004824e7fdSDimitry Andric   if (InstrNum) {
12014824e7fdSDimitry Andric     if (STI.isTargetWin64() || !STI.isOSWindows()) {
12024824e7fdSDimitry Andric       // Label destination operand of the subtract.
12034824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(*InstrNum,
12044824e7fdSDimitry Andric                                     {ModInst->getDebugInstrNum(), 0});
12054824e7fdSDimitry Andric     } else {
12064824e7fdSDimitry Andric       // Label the call. The operand number is the penultimate operand, zero
12074824e7fdSDimitry Andric       // based.
12084824e7fdSDimitry Andric       unsigned SPDefOperand = ModInst->getNumOperands() - 2;
12094824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(
12104824e7fdSDimitry Andric           *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
12114824e7fdSDimitry Andric     }
12124824e7fdSDimitry Andric   }
12134824e7fdSDimitry Andric 
12140b57cec5SDimitry Andric   if (InProlog) {
12150b57cec5SDimitry Andric     // Apply the frame setup flag to all inserted instrs.
12160b57cec5SDimitry Andric     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
12170b57cec5SDimitry Andric       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
12180b57cec5SDimitry Andric   }
12190b57cec5SDimitry Andric }
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric static unsigned calculateSetFPREG(uint64_t SPAdjust) {
12220b57cec5SDimitry Andric   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
12230b57cec5SDimitry Andric   // and might require smaller successive adjustments.
12240b57cec5SDimitry Andric   const uint64_t Win64MaxSEHOffset = 128;
12250b57cec5SDimitry Andric   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
12260b57cec5SDimitry Andric   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
12270b57cec5SDimitry Andric   return SEHFrameOffset & -16;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric // If we're forcing a stack realignment we can't rely on just the frame
12310b57cec5SDimitry Andric // info, we need to know the ABI stack alignment as well in case we
12320b57cec5SDimitry Andric // have a call out.  Otherwise just make sure we have some alignment - we'll
12330b57cec5SDimitry Andric // go with the minimum SlotSize.
12340b57cec5SDimitry Andric uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
12350b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
12365ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
12375ffd83dbSDimitry Andric   Align StackAlign = getStackAlign();
1238*06c3fb27SDimitry Andric   bool HasRealign = MF.getFunction().hasFnAttribute("stackrealign");
1239*06c3fb27SDimitry Andric   if (HasRealign) {
12400b57cec5SDimitry Andric     if (MFI.hasCalls())
12410b57cec5SDimitry Andric       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
12420b57cec5SDimitry Andric     else if (MaxAlign < SlotSize)
12435ffd83dbSDimitry Andric       MaxAlign = Align(SlotSize);
12440b57cec5SDimitry Andric   }
1245*06c3fb27SDimitry Andric 
1246*06c3fb27SDimitry Andric   if (!Is64Bit && MF.getFunction().getCallingConv() == CallingConv::X86_INTR) {
1247*06c3fb27SDimitry Andric     if (HasRealign)
1248*06c3fb27SDimitry Andric       MaxAlign = (MaxAlign > 16) ? MaxAlign : Align(16);
1249*06c3fb27SDimitry Andric     else
1250*06c3fb27SDimitry Andric       MaxAlign = Align(16);
1251*06c3fb27SDimitry Andric   }
12525ffd83dbSDimitry Andric   return MaxAlign.value();
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
12560b57cec5SDimitry Andric                                           MachineBasicBlock::iterator MBBI,
12570b57cec5SDimitry Andric                                           const DebugLoc &DL, unsigned Reg,
12580b57cec5SDimitry Andric                                           uint64_t MaxAlign) const {
12590b57cec5SDimitry Andric   uint64_t Val = -MaxAlign;
12600b57cec5SDimitry Andric   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1261eaeb601bSDimitry Andric 
1262eaeb601bSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1263eaeb601bSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1264eaeb601bSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
1265eaeb601bSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1266eaeb601bSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1267eaeb601bSDimitry Andric 
1268eaeb601bSDimitry Andric   // We want to make sure that (in worst case) less than StackProbeSize bytes
1269eaeb601bSDimitry Andric   // are not probed after the AND. This assumption is used in
1270eaeb601bSDimitry Andric   // emitStackProbeInlineGeneric.
1271eaeb601bSDimitry Andric   if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1272eaeb601bSDimitry Andric     {
1273eaeb601bSDimitry Andric       NumFrameLoopProbe++;
1274eaeb601bSDimitry Andric       MachineBasicBlock *entryMBB =
1275eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1276eaeb601bSDimitry Andric       MachineBasicBlock *headMBB =
1277eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1278eaeb601bSDimitry Andric       MachineBasicBlock *bodyMBB =
1279eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1280eaeb601bSDimitry Andric       MachineBasicBlock *footMBB =
1281eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1282eaeb601bSDimitry Andric 
1283eaeb601bSDimitry Andric       MachineFunction::iterator MBBIter = MBB.getIterator();
1284eaeb601bSDimitry Andric       MF.insert(MBBIter, entryMBB);
1285eaeb601bSDimitry Andric       MF.insert(MBBIter, headMBB);
1286eaeb601bSDimitry Andric       MF.insert(MBBIter, bodyMBB);
1287eaeb601bSDimitry Andric       MF.insert(MBBIter, footMBB);
1288eaeb601bSDimitry Andric       const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
12898c6f6c0cSDimitry Andric       Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
12908c6f6c0cSDimitry Andric                                   : Is64Bit         ? X86::R11D
12918c6f6c0cSDimitry Andric                                                     : X86::EAX;
1292eaeb601bSDimitry Andric 
1293eaeb601bSDimitry Andric       // Setup entry block
1294eaeb601bSDimitry Andric       {
1295eaeb601bSDimitry Andric 
1296eaeb601bSDimitry Andric         entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1297eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1298eaeb601bSDimitry Andric             .addReg(StackPtr)
1299eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1300eaeb601bSDimitry Andric         MachineInstr *MI =
1301eaeb601bSDimitry Andric             BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1302eaeb601bSDimitry Andric                 .addReg(FinalStackProbed)
1303eaeb601bSDimitry Andric                 .addImm(Val)
1304eaeb601bSDimitry Andric                 .setMIFlag(MachineInstr::FrameSetup);
1305eaeb601bSDimitry Andric 
1306eaeb601bSDimitry Andric         // The EFLAGS implicit def is dead.
1307eaeb601bSDimitry Andric         MI->getOperand(3).setIsDead();
1308eaeb601bSDimitry Andric 
1309eaeb601bSDimitry Andric         BuildMI(entryMBB, DL,
1310eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1311eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1312eaeb601bSDimitry Andric             .addReg(StackPtr)
1313eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1314eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1315eaeb601bSDimitry Andric             .addMBB(&MBB)
1316eaeb601bSDimitry Andric             .addImm(X86::COND_E)
1317eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1318eaeb601bSDimitry Andric         entryMBB->addSuccessor(headMBB);
1319eaeb601bSDimitry Andric         entryMBB->addSuccessor(&MBB);
1320eaeb601bSDimitry Andric       }
1321eaeb601bSDimitry Andric 
1322eaeb601bSDimitry Andric       // Loop entry block
1323eaeb601bSDimitry Andric 
1324eaeb601bSDimitry Andric       {
1325eaeb601bSDimitry Andric         const unsigned SUBOpc =
1326*06c3fb27SDimitry Andric             getSUBriOpcode(Uses64BitFramePtr);
1327eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1328eaeb601bSDimitry Andric             .addReg(StackPtr)
1329eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1330eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1331eaeb601bSDimitry Andric 
1332eaeb601bSDimitry Andric         BuildMI(headMBB, DL,
1333eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1334eaeb601bSDimitry Andric             .addReg(StackPtr)
1335bdd1243dSDimitry Andric             .addReg(FinalStackProbed)
1336eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1337eaeb601bSDimitry Andric 
1338bdd1243dSDimitry Andric         // jump to the footer if StackPtr < FinalStackProbed
1339eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1340eaeb601bSDimitry Andric             .addMBB(footMBB)
1341eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1342eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1343eaeb601bSDimitry Andric 
1344eaeb601bSDimitry Andric         headMBB->addSuccessor(bodyMBB);
1345eaeb601bSDimitry Andric         headMBB->addSuccessor(footMBB);
1346eaeb601bSDimitry Andric       }
1347eaeb601bSDimitry Andric 
1348eaeb601bSDimitry Andric       // setup loop body
1349eaeb601bSDimitry Andric       {
1350eaeb601bSDimitry Andric         addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1351eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1352eaeb601bSDimitry Andric                      StackPtr, false, 0)
1353eaeb601bSDimitry Andric             .addImm(0)
1354eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1355eaeb601bSDimitry Andric 
1356eaeb601bSDimitry Andric         const unsigned SUBOpc =
1357*06c3fb27SDimitry Andric             getSUBriOpcode(Uses64BitFramePtr);
1358eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1359eaeb601bSDimitry Andric             .addReg(StackPtr)
1360eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1361eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1362eaeb601bSDimitry Andric 
1363eaeb601bSDimitry Andric         // cmp with stack pointer bound
1364eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL,
1365eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1366eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1367eaeb601bSDimitry Andric             .addReg(StackPtr)
1368eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1369eaeb601bSDimitry Andric 
1370bdd1243dSDimitry Andric         // jump back while FinalStackProbed < StackPtr
1371eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1372eaeb601bSDimitry Andric             .addMBB(bodyMBB)
1373eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1374eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1375eaeb601bSDimitry Andric         bodyMBB->addSuccessor(bodyMBB);
1376eaeb601bSDimitry Andric         bodyMBB->addSuccessor(footMBB);
1377eaeb601bSDimitry Andric       }
1378eaeb601bSDimitry Andric 
1379eaeb601bSDimitry Andric       // setup loop footer
1380eaeb601bSDimitry Andric       {
1381eaeb601bSDimitry Andric         BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1382eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1383eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1384eaeb601bSDimitry Andric         addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1385eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1386eaeb601bSDimitry Andric                      StackPtr, false, 0)
1387eaeb601bSDimitry Andric             .addImm(0)
1388eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1389eaeb601bSDimitry Andric         footMBB->addSuccessor(&MBB);
1390eaeb601bSDimitry Andric       }
1391eaeb601bSDimitry Andric 
1392eaeb601bSDimitry Andric       recomputeLiveIns(*headMBB);
1393eaeb601bSDimitry Andric       recomputeLiveIns(*bodyMBB);
1394eaeb601bSDimitry Andric       recomputeLiveIns(*footMBB);
1395eaeb601bSDimitry Andric       recomputeLiveIns(MBB);
1396eaeb601bSDimitry Andric     }
1397eaeb601bSDimitry Andric   } else {
13980b57cec5SDimitry Andric     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
13990b57cec5SDimitry Andric                            .addReg(Reg)
14000b57cec5SDimitry Andric                            .addImm(Val)
14010b57cec5SDimitry Andric                            .setMIFlag(MachineInstr::FrameSetup);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric     // The EFLAGS implicit def is dead.
14040b57cec5SDimitry Andric     MI->getOperand(3).setIsDead();
14050b57cec5SDimitry Andric   }
1406eaeb601bSDimitry Andric }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
14090b57cec5SDimitry Andric   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
14100b57cec5SDimitry Andric   // clobbered by any interrupt handler.
14110b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
14120b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
14130b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
14140b57cec5SDimitry Andric   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
14150b57cec5SDimitry Andric   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
1418d56accc7SDimitry Andric /// Return true if we need to use the restricted Windows x64 prologue and
1419d56accc7SDimitry Andric /// epilogue code patterns that can be described with WinCFI (.seh_*
1420d56accc7SDimitry Andric /// directives).
1421fe6060f1SDimitry Andric bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const {
1422fe6060f1SDimitry Andric   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1423fe6060f1SDimitry Andric }
1424fe6060f1SDimitry Andric 
1425fe6060f1SDimitry Andric bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1426fe6060f1SDimitry Andric   return !isWin64Prologue(MF) && MF.needsFrameMoves();
1427fe6060f1SDimitry Andric }
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric /// emitPrologue - Push callee-saved registers onto the stack, which
14300b57cec5SDimitry Andric /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
14310b57cec5SDimitry Andric /// space for local variables. Also emit labels used by the exception handler to
14320b57cec5SDimitry Andric /// generate the exception handling frames.
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric /*
14350b57cec5SDimitry Andric   Here's a gist of what gets emitted:
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   ; Establish frame pointer, if needed
14380b57cec5SDimitry Andric   [if needs FP]
14390b57cec5SDimitry Andric       push  %rbp
14400b57cec5SDimitry Andric       .cfi_def_cfa_offset 16
14410b57cec5SDimitry Andric       .cfi_offset %rbp, -16
14420b57cec5SDimitry Andric       .seh_pushreg %rpb
14430b57cec5SDimitry Andric       mov  %rsp, %rbp
14440b57cec5SDimitry Andric       .cfi_def_cfa_register %rbp
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric   ; Spill general-purpose registers
14470b57cec5SDimitry Andric   [for all callee-saved GPRs]
14480b57cec5SDimitry Andric       pushq %<reg>
14490b57cec5SDimitry Andric       [if not needs FP]
14500b57cec5SDimitry Andric          .cfi_def_cfa_offset (offset from RETADDR)
14510b57cec5SDimitry Andric       .seh_pushreg %<reg>
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   ; If the required stack alignment > default stack alignment
14540b57cec5SDimitry Andric   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
14550b57cec5SDimitry Andric   ; of unknown size in the stack frame.
14560b57cec5SDimitry Andric   [if stack needs re-alignment]
14570b57cec5SDimitry Andric       and  $MASK, %rsp
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   ; Allocate space for locals
14600b57cec5SDimitry Andric   [if target is Windows and allocated space > 4096 bytes]
14610b57cec5SDimitry Andric       ; Windows needs special care for allocations larger
14620b57cec5SDimitry Andric       ; than one page.
14630b57cec5SDimitry Andric       mov $NNN, %rax
14640b57cec5SDimitry Andric       call ___chkstk_ms/___chkstk
14650b57cec5SDimitry Andric       sub  %rax, %rsp
14660b57cec5SDimitry Andric   [else]
14670b57cec5SDimitry Andric       sub  $NNN, %rsp
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   [if needs FP]
14700b57cec5SDimitry Andric       .seh_stackalloc (size of XMM spill slots)
14710b57cec5SDimitry Andric       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
14720b57cec5SDimitry Andric   [else]
14730b57cec5SDimitry Andric       .seh_stackalloc NNN
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   ; Spill XMMs
14760b57cec5SDimitry Andric   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
14770b57cec5SDimitry Andric   ; they may get spilled on any platform, if the current function
14780b57cec5SDimitry Andric   ; calls @llvm.eh.unwind.init
14790b57cec5SDimitry Andric   [if needs FP]
14800b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14810b57cec5SDimitry Andric           movaps  %<xmm reg>, -MMM(%rbp)
14820b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14830b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
14840b57cec5SDimitry Andric               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
14850b57cec5SDimitry Andric   [else]
14860b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14870b57cec5SDimitry Andric           movaps  %<xmm reg>, KKK(%rsp)
14880b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14890b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, KKK
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   .seh_endprologue
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric   [if needs base pointer]
14940b57cec5SDimitry Andric       mov  %rsp, %rbx
14950b57cec5SDimitry Andric       [if needs to restore base pointer]
14960b57cec5SDimitry Andric           mov %rsp, -MMM(%rbp)
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric   ; Emit CFI info
14990b57cec5SDimitry Andric   [if needs FP]
15000b57cec5SDimitry Andric       [for all callee-saved registers]
15010b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rbp)
15020b57cec5SDimitry Andric   [else]
15030b57cec5SDimitry Andric        .cfi_def_cfa_offset (offset from RETADDR)
15040b57cec5SDimitry Andric       [for all callee-saved registers]
15050b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rsp)
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   Notes:
15080b57cec5SDimitry Andric   - .seh directives are emitted only for Windows 64 ABI
15090b57cec5SDimitry Andric   - .cv_fpo directives are emitted on win32 when emitting CodeView
15100b57cec5SDimitry Andric   - .cfi directives are emitted for all other ABIs
15110b57cec5SDimitry Andric   - for 32-bit code, substitute %e?? registers for %r??
15120b57cec5SDimitry Andric */
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric void X86FrameLowering::emitPrologue(MachineFunction &MF,
15150b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
15160b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
15170b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
15180b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
15190b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
15200b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
15210b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
15220b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
15230b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
15240b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
15250b57cec5SDimitry Andric   bool IsFunclet = MBB.isEHFuncletEntry();
15260b57cec5SDimitry Andric   EHPersonality Personality = EHPersonality::Unknown;
15270b57cec5SDimitry Andric   if (Fn.hasPersonalityFn())
15280b57cec5SDimitry Andric     Personality = classifyEHPersonality(Fn.getPersonalityFn());
15290b57cec5SDimitry Andric   bool FnHasClrFunclet =
15300b57cec5SDimitry Andric       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
15310b57cec5SDimitry Andric   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
15320b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
1533fe6060f1SDimitry Andric   bool IsWin64Prologue = isWin64Prologue(MF);
15340b57cec5SDimitry Andric   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
15350b57cec5SDimitry Andric   // FIXME: Emit FPO data for EH funclets.
15360b57cec5SDimitry Andric   bool NeedsWinFPO =
15370b57cec5SDimitry Andric       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
15380b57cec5SDimitry Andric   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1539fe6060f1SDimitry Andric   bool NeedsDwarfCFI = needsDwarfCFI(MF);
15408bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
15418bcb0991SDimitry Andric   const Register MachineFramePtr =
15420b57cec5SDimitry Andric       STI.isTarget64BitILP32()
15438bcb0991SDimitry Andric           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
15448bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
15450b57cec5SDimitry Andric   bool HasWinCFI = false;
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   // Debug location must be unknown since the first debug location is used
15480b57cec5SDimitry Andric   // to determine the end of the prologue.
15490b57cec5SDimitry Andric   DebugLoc DL;
1550*06c3fb27SDimitry Andric   Register ArgBaseReg;
1551*06c3fb27SDimitry Andric 
1552*06c3fb27SDimitry Andric   // Emit extra prolog for argument stack slot reference.
1553*06c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
1554*06c3fb27SDimitry Andric     // MI is lea instruction that created in X86ArgumentStackSlotPass.
1555*06c3fb27SDimitry Andric     // Creat extra prolog for stack realignment.
1556*06c3fb27SDimitry Andric     ArgBaseReg = MI->getOperand(0).getReg();
1557*06c3fb27SDimitry Andric     // leal    4(%esp), %basereg
1558*06c3fb27SDimitry Andric     // .cfi_def_cfa %basereg, 0
1559*06c3fb27SDimitry Andric     // andl    $-128, %esp
1560*06c3fb27SDimitry Andric     // pushl   -4(%basereg)
1561*06c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::LEA64r : X86::LEA32r),
1562*06c3fb27SDimitry Andric             ArgBaseReg)
1563*06c3fb27SDimitry Andric         .addUse(StackPtr)
1564*06c3fb27SDimitry Andric         .addImm(1)
1565*06c3fb27SDimitry Andric         .addUse(X86::NoRegister)
1566*06c3fb27SDimitry Andric         .addImm(SlotSize)
1567*06c3fb27SDimitry Andric         .addUse(X86::NoRegister)
1568*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
1569*06c3fb27SDimitry Andric     if (NeedsDwarfCFI) {
1570*06c3fb27SDimitry Andric       // .cfi_def_cfa %basereg, 0
1571*06c3fb27SDimitry Andric       unsigned DwarfStackPtr = TRI->getDwarfRegNum(ArgBaseReg, true);
1572*06c3fb27SDimitry Andric       BuildCFI(MBB, MBBI, DL,
1573*06c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 0),
1574*06c3fb27SDimitry Andric                MachineInstr::FrameSetup);
1575*06c3fb27SDimitry Andric     }
1576*06c3fb27SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1577*06c3fb27SDimitry Andric     int64_t Offset = -(int64_t)SlotSize;
1578*06c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64rmm: X86::PUSH32rmm))
1579*06c3fb27SDimitry Andric         .addReg(ArgBaseReg)
1580*06c3fb27SDimitry Andric         .addImm(1)
1581*06c3fb27SDimitry Andric         .addReg(X86::NoRegister)
1582*06c3fb27SDimitry Andric         .addImm(Offset)
1583*06c3fb27SDimitry Andric         .addReg(X86::NoRegister)
1584*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
1585*06c3fb27SDimitry Andric   }
15860b57cec5SDimitry Andric 
1587349cc55cSDimitry Andric   // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1588349cc55cSDimitry Andric   // tail call.
1589349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1590349cc55cSDimitry Andric   if (TailCallArgReserveSize  && IsWin64Prologue)
15910b57cec5SDimitry Andric     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
15920b57cec5SDimitry Andric 
15935ffd83dbSDimitry Andric   const bool EmitStackProbeCall =
15945ffd83dbSDimitry Andric       STI.getTargetLowering()->hasStackProbeSymbol(MF);
15958bcb0991SDimitry Andric   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
15960b57cec5SDimitry Andric 
1597fe6060f1SDimitry Andric   if (HasFP && X86FI->hasSwiftAsyncContext()) {
1598349cc55cSDimitry Andric     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1599349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::DeploymentBased:
1600349cc55cSDimitry Andric       if (STI.swiftAsyncContextIsDynamicallySet()) {
1601349cc55cSDimitry Andric         // The special symbol below is absolute and has a *value* suitable to be
1602349cc55cSDimitry Andric         // combined with the frame pointer directly.
1603349cc55cSDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1604349cc55cSDimitry Andric             .addUse(MachineFramePtr)
1605349cc55cSDimitry Andric             .addUse(X86::RIP)
1606349cc55cSDimitry Andric             .addImm(1)
1607349cc55cSDimitry Andric             .addUse(X86::NoRegister)
1608349cc55cSDimitry Andric             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1609349cc55cSDimitry Andric                                X86II::MO_GOTPCREL)
1610349cc55cSDimitry Andric             .addUse(X86::NoRegister);
1611349cc55cSDimitry Andric         break;
1612349cc55cSDimitry Andric       }
1613bdd1243dSDimitry Andric       [[fallthrough]];
1614349cc55cSDimitry Andric 
1615349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Always:
1616349cc55cSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1617fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
1618fe6060f1SDimitry Andric           .addImm(60)
1619fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
1620349cc55cSDimitry Andric       break;
1621349cc55cSDimitry Andric 
1622349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Never:
1623349cc55cSDimitry Andric       break;
1624349cc55cSDimitry Andric     }
1625fe6060f1SDimitry Andric   }
1626fe6060f1SDimitry Andric 
16270b57cec5SDimitry Andric   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
16280b57cec5SDimitry Andric   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
16290b57cec5SDimitry Andric   // stack alignment.
16300b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
16310b57cec5SDimitry Andric       Fn.arg_size() == 2) {
16320b57cec5SDimitry Andric     StackSize += 8;
16330b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
1634a324c340SDimitry Andric 
1635a324c340SDimitry Andric     // Update the stack pointer by pushing a register. This is the instruction
1636a324c340SDimitry Andric     // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1637a324c340SDimitry Andric     // Hard-coding the update to a push avoids emitting a second
1638a324c340SDimitry Andric     // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1639a324c340SDimitry Andric     // probing isn't needed anyways for an 8-byte update.
1640a324c340SDimitry Andric     // Pushing a register leaves us in a similar situation to a regular
1641a324c340SDimitry Andric     // function call where we know that the address at (rsp-8) is writeable.
1642a324c340SDimitry Andric     // That way we avoid any off-by-ones with stack probing for additional
1643a324c340SDimitry Andric     // stack pointer updates later on.
1644a324c340SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1645a324c340SDimitry Andric         .addReg(X86::RAX, RegState::Undef)
1646a324c340SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
16470b57cec5SDimitry Andric   }
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
16500b57cec5SDimitry Andric   // function, and use up to 128 bytes of stack space, don't have a frame
16510b57cec5SDimitry Andric   // pointer, calls, or dynamic alloca then we do not need to adjust the
16520b57cec5SDimitry Andric   // stack pointer (we fit in the Red Zone). We also check that we don't
16530b57cec5SDimitry Andric   // push and pop from the stack.
1654fe6060f1SDimitry Andric   if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
16550b57cec5SDimitry Andric       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
16560b57cec5SDimitry Andric       !MFI.adjustsStack() &&                   // No calls.
16575ffd83dbSDimitry Andric       !EmitStackProbeCall &&                   // No stack probes.
16580b57cec5SDimitry Andric       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
16590b57cec5SDimitry Andric       !MF.shouldSplitStack()) {                // Regular stack
1660349cc55cSDimitry Andric     uint64_t MinSize =
1661349cc55cSDimitry Andric         X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta();
16620b57cec5SDimitry Andric     if (HasFP) MinSize += SlotSize;
16630b57cec5SDimitry Andric     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
16640b57cec5SDimitry Andric     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
16650b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
16660b57cec5SDimitry Andric   }
16670b57cec5SDimitry Andric 
16680b57cec5SDimitry Andric   // Insert stack pointer adjustment for later moving of return addr.  Only
16690b57cec5SDimitry Andric   // applies to tail call optimized functions where the callee argument stack
16700b57cec5SDimitry Andric   // size is bigger than the callers.
1671349cc55cSDimitry Andric   if (TailCallArgReserveSize != 0) {
1672349cc55cSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
16730b57cec5SDimitry Andric                          /*InEpilogue=*/false)
16740b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
16750b57cec5SDimitry Andric   }
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   // Mapping for machine moves:
16780b57cec5SDimitry Andric   //
16790b57cec5SDimitry Andric   //   DST: VirtualFP AND
16800b57cec5SDimitry Andric   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
16810b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_def_cfa
16820b57cec5SDimitry Andric   //
16830b57cec5SDimitry Andric   //   SRC: VirtualFP AND
16840b57cec5SDimitry Andric   //        DST: Register               => DW_CFA_def_cfa_register
16850b57cec5SDimitry Andric   //
16860b57cec5SDimitry Andric   //   ELSE
16870b57cec5SDimitry Andric   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
16880b57cec5SDimitry Andric   //        REG < 64                    => DW_CFA_offset + Reg
16890b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_offset_extended
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   uint64_t NumBytes = 0;
16920b57cec5SDimitry Andric   int stackGrowth = -SlotSize;
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   // Find the funclet establisher parameter
16958bcb0991SDimitry Andric   Register Establisher = X86::NoRegister;
16960b57cec5SDimitry Andric   if (IsClrFunclet)
16970b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
16980b57cec5SDimitry Andric   else if (IsFunclet)
16990b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
17020b57cec5SDimitry Andric     // Immediately spill establisher into the home slot.
17030b57cec5SDimitry Andric     // The runtime cares about this.
17040b57cec5SDimitry Andric     // MOV64mr %rdx, 16(%rsp)
17050b57cec5SDimitry Andric     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
17060b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
17070b57cec5SDimitry Andric         .addReg(Establisher)
17080b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
17090b57cec5SDimitry Andric     MBB.addLiveIn(Establisher);
17100b57cec5SDimitry Andric   }
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   if (HasFP) {
17130b57cec5SDimitry Andric     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric     // Calculate required stack adjustment.
17160b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
1717349cc55cSDimitry Andric     NumBytes = FrameSize -
1718349cc55cSDimitry Andric                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric     // Callee-saved registers are pushed on stack before the stack is realigned.
1721fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
17220b57cec5SDimitry Andric       NumBytes = alignTo(NumBytes, MaxAlign);
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric     // Save EBP/RBP into the appropriate stack slot.
17250b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
17260b57cec5SDimitry Andric       .addReg(MachineFramePtr, RegState::Kill)
17270b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
17280b57cec5SDimitry Andric 
1729*06c3fb27SDimitry Andric     if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
17300b57cec5SDimitry Andric       // Mark the place where EBP/RBP was saved.
17310b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
17320b57cec5SDimitry Andric       assert(StackSize);
17330b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
1734*06c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(
1735*06c3fb27SDimitry Andric                    nullptr, -2 * stackGrowth + (int)TailCallArgReserveSize),
173681ad6265SDimitry Andric                MachineInstr::FrameSetup);
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric       // Change the rule for the FramePtr to be an "offset" rule.
17390b57cec5SDimitry Andric       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
174081ad6265SDimitry Andric       BuildCFI(MBB, MBBI, DL,
174181ad6265SDimitry Andric                MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
1742*06c3fb27SDimitry Andric                                               2 * stackGrowth -
1743*06c3fb27SDimitry Andric                                                   (int)TailCallArgReserveSize),
174481ad6265SDimitry Andric                MachineInstr::FrameSetup);
17450b57cec5SDimitry Andric     }
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric     if (NeedsWinCFI) {
17480b57cec5SDimitry Andric       HasWinCFI = true;
17490b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
17500b57cec5SDimitry Andric           .addImm(FramePtr)
17510b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
17520b57cec5SDimitry Andric     }
17530b57cec5SDimitry Andric 
1754fe6060f1SDimitry Andric     if (!IsFunclet) {
1755fe6060f1SDimitry Andric       if (X86FI->hasSwiftAsyncContext()) {
1756fe6060f1SDimitry Andric         const auto &Attrs = MF.getFunction().getAttributes();
1757fe6060f1SDimitry Andric 
1758fe6060f1SDimitry Andric         // Before we update the live frame pointer we have to ensure there's a
1759fe6060f1SDimitry Andric         // valid (or null) asynchronous context in its slot just before FP in
1760fe6060f1SDimitry Andric         // the frame record, so store it now.
1761fe6060f1SDimitry Andric         if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
1762fe6060f1SDimitry Andric           // We have an initial context in r14, store it just before the frame
1763fe6060f1SDimitry Andric           // pointer.
1764fe6060f1SDimitry Andric           MBB.addLiveIn(X86::R14);
1765fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1766fe6060f1SDimitry Andric               .addReg(X86::R14)
1767fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1768fe6060f1SDimitry Andric         } else {
1769fe6060f1SDimitry Andric           // No initial context, store null so that there's no pointer that
1770fe6060f1SDimitry Andric           // could be misused.
1771*06c3fb27SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i32))
1772fe6060f1SDimitry Andric               .addImm(0)
1773fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1774fe6060f1SDimitry Andric         }
1775fe6060f1SDimitry Andric 
1776fe6060f1SDimitry Andric         if (NeedsWinCFI) {
1777fe6060f1SDimitry Andric           HasWinCFI = true;
1778fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1779fe6060f1SDimitry Andric               .addImm(X86::R14)
1780fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1781fe6060f1SDimitry Andric         }
1782fe6060f1SDimitry Andric 
1783fe6060f1SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
1784fe6060f1SDimitry Andric             .addUse(X86::RSP)
1785fe6060f1SDimitry Andric             .addImm(1)
1786fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1787fe6060f1SDimitry Andric             .addImm(8)
1788fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1789fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1790*06c3fb27SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri32), X86::RSP)
1791fe6060f1SDimitry Andric             .addUse(X86::RSP)
1792fe6060f1SDimitry Andric             .addImm(8)
1793fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1794fe6060f1SDimitry Andric       }
1795fe6060f1SDimitry Andric 
17960b57cec5SDimitry Andric       if (!IsWin64Prologue && !IsFunclet) {
17970b57cec5SDimitry Andric         // Update EBP with the new base value.
1798fe6060f1SDimitry Andric         if (!X86FI->hasSwiftAsyncContext())
17990b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL,
18000b57cec5SDimitry Andric                   TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
18010b57cec5SDimitry Andric                   FramePtr)
18020b57cec5SDimitry Andric               .addReg(StackPtr)
18030b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric         if (NeedsDwarfCFI) {
1806*06c3fb27SDimitry Andric           if (ArgBaseReg.isValid()) {
1807*06c3fb27SDimitry Andric             SmallString<64> CfaExpr;
1808*06c3fb27SDimitry Andric             CfaExpr.push_back(dwarf::DW_CFA_expression);
1809*06c3fb27SDimitry Andric             uint8_t buffer[16];
1810*06c3fb27SDimitry Andric             unsigned DwarfReg = TRI->getDwarfRegNum(MachineFramePtr, true);
1811*06c3fb27SDimitry Andric             CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
1812*06c3fb27SDimitry Andric             CfaExpr.push_back(2);
1813*06c3fb27SDimitry Andric             CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
1814*06c3fb27SDimitry Andric             CfaExpr.push_back(0);
1815*06c3fb27SDimitry Andric             // DW_CFA_expression: reg5 DW_OP_breg5 +0
1816*06c3fb27SDimitry Andric             BuildCFI(MBB, MBBI, DL,
1817*06c3fb27SDimitry Andric                      MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
1818*06c3fb27SDimitry Andric                      MachineInstr::FrameSetup);
1819*06c3fb27SDimitry Andric           } else {
18200b57cec5SDimitry Andric             // Mark effective beginning of when frame pointer becomes valid.
18210b57cec5SDimitry Andric             // Define the current CFA to use the EBP/RBP register.
18220b57cec5SDimitry Andric             unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1823fe6060f1SDimitry Andric             BuildCFI(
1824fe6060f1SDimitry Andric                 MBB, MBBI, DL,
182581ad6265SDimitry Andric                 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
182681ad6265SDimitry Andric                 MachineInstr::FrameSetup);
18270b57cec5SDimitry Andric           }
1828*06c3fb27SDimitry Andric         }
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric         if (NeedsWinFPO) {
18310b57cec5SDimitry Andric           // .cv_fpo_setframe $FramePtr
18320b57cec5SDimitry Andric           HasWinCFI = true;
18330b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
18340b57cec5SDimitry Andric               .addImm(FramePtr)
18350b57cec5SDimitry Andric               .addImm(0)
18360b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
18370b57cec5SDimitry Andric         }
18380b57cec5SDimitry Andric       }
1839fe6060f1SDimitry Andric     }
18400b57cec5SDimitry Andric   } else {
18410b57cec5SDimitry Andric     assert(!IsFunclet && "funclets without FPs not yet implemented");
1842349cc55cSDimitry Andric     NumBytes = StackSize -
1843349cc55cSDimitry Andric                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   // Update the offset adjustment, which is mainly used by codeview to translate
18470b57cec5SDimitry Andric   // from ESP to VFRAME relative local variable offsets.
18480b57cec5SDimitry Andric   if (!IsFunclet) {
1849fe6060f1SDimitry Andric     if (HasFP && TRI->hasStackRealignment(MF))
18500b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-NumBytes);
18510b57cec5SDimitry Andric     else
18520b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-StackSize);
18530b57cec5SDimitry Andric   }
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   // For EH funclets, only allocate enough space for outgoing calls. Save the
18560b57cec5SDimitry Andric   // NumBytes value that we would've used for the parent frame.
18570b57cec5SDimitry Andric   unsigned ParentFrameNumBytes = NumBytes;
18580b57cec5SDimitry Andric   if (IsFunclet)
18590b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric   // Skip the callee-saved push instructions.
18620b57cec5SDimitry Andric   bool PushedRegs = false;
18630b57cec5SDimitry Andric   int StackOffset = 2 * stackGrowth;
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   while (MBBI != MBB.end() &&
18660b57cec5SDimitry Andric          MBBI->getFlag(MachineInstr::FrameSetup) &&
18670b57cec5SDimitry Andric          (MBBI->getOpcode() == X86::PUSH32r ||
18680b57cec5SDimitry Andric           MBBI->getOpcode() == X86::PUSH64r)) {
18690b57cec5SDimitry Andric     PushedRegs = true;
18708bcb0991SDimitry Andric     Register Reg = MBBI->getOperand(0).getReg();
18710b57cec5SDimitry Andric     ++MBBI;
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
18740b57cec5SDimitry Andric       // Mark callee-saved push instruction.
18750b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
18760b57cec5SDimitry Andric       assert(StackSize);
18770b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
187881ad6265SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(nullptr, -StackOffset),
187981ad6265SDimitry Andric                MachineInstr::FrameSetup);
18800b57cec5SDimitry Andric       StackOffset += stackGrowth;
18810b57cec5SDimitry Andric     }
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric     if (NeedsWinCFI) {
18840b57cec5SDimitry Andric       HasWinCFI = true;
18850b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
18860b57cec5SDimitry Andric           .addImm(Reg)
18870b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
18880b57cec5SDimitry Andric     }
18890b57cec5SDimitry Andric   }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric   // Realign stack after we pushed callee-saved registers (so that we'll be
18920b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
18930b57cec5SDimitry Andric   // Don't do this for Win64, it needs to realign the stack after the prologue.
1894*06c3fb27SDimitry Andric   if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) &&
1895*06c3fb27SDimitry Andric       !ArgBaseReg.isValid()) {
18960b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
18970b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric     if (NeedsWinCFI) {
19000b57cec5SDimitry Andric       HasWinCFI = true;
19010b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
19020b57cec5SDimitry Andric           .addImm(MaxAlign)
19030b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19040b57cec5SDimitry Andric     }
19050b57cec5SDimitry Andric   }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric   // If there is an SUB32ri of ESP immediately before this instruction, merge
19080b57cec5SDimitry Andric   // the two. This can be the case when tail call elimination is enabled and
19090b57cec5SDimitry Andric   // the callee has more arguments then the caller.
19100b57cec5SDimitry Andric   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   // Adjust stack pointer: ESP -= numbytes.
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric   // Windows and cygwin/mingw require a prologue helper routine when allocating
19150b57cec5SDimitry Andric   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
19160b57cec5SDimitry Andric   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
19170b57cec5SDimitry Andric   // stack and adjust the stack pointer in one go.  The 64-bit version of
19180b57cec5SDimitry Andric   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
19190b57cec5SDimitry Andric   // responsible for adjusting the stack pointer.  Touching the stack at 4K
19200b57cec5SDimitry Andric   // increments is necessary to ensure that the guard pages used by the OS
19210b57cec5SDimitry Andric   // virtual memory manager are allocated in correct sequence.
19220b57cec5SDimitry Andric   uint64_t AlignedNumBytes = NumBytes;
1923fe6060f1SDimitry Andric   if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
19240b57cec5SDimitry Andric     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
19255ffd83dbSDimitry Andric   if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
19260b57cec5SDimitry Andric     assert(!X86FI->getUsesRedZone() &&
19270b57cec5SDimitry Andric            "The Red Zone is not accounted for in stack probes");
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric     // Check whether EAX is livein for this block.
19300b57cec5SDimitry Andric     bool isEAXAlive = isEAXLiveIn(MBB);
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric     if (isEAXAlive) {
19330b57cec5SDimitry Andric       if (Is64Bit) {
19340b57cec5SDimitry Andric         // Save RAX
19350b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
19360b57cec5SDimitry Andric           .addReg(X86::RAX, RegState::Kill)
19370b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19380b57cec5SDimitry Andric       } else {
19390b57cec5SDimitry Andric         // Save EAX
19400b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
19410b57cec5SDimitry Andric           .addReg(X86::EAX, RegState::Kill)
19420b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19430b57cec5SDimitry Andric       }
19440b57cec5SDimitry Andric     }
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric     if (Is64Bit) {
19470b57cec5SDimitry Andric       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
19480b57cec5SDimitry Andric       // Function prologue is responsible for adjusting the stack pointer.
1949480093f4SDimitry Andric       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
195004eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Alloc)), X86::RAX)
19510b57cec5SDimitry Andric           .addImm(Alloc)
19520b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19530b57cec5SDimitry Andric     } else {
19540b57cec5SDimitry Andric       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
19550b57cec5SDimitry Andric       // We'll also use 4 already allocated bytes for EAX.
19560b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
19570b57cec5SDimitry Andric           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
19580b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19590b57cec5SDimitry Andric     }
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric     // Call __chkstk, __chkstk_ms, or __alloca.
19620b57cec5SDimitry Andric     emitStackProbe(MF, MBB, MBBI, DL, true);
19630b57cec5SDimitry Andric 
19640b57cec5SDimitry Andric     if (isEAXAlive) {
19650b57cec5SDimitry Andric       // Restore RAX/EAX
19660b57cec5SDimitry Andric       MachineInstr *MI;
19670b57cec5SDimitry Andric       if (Is64Bit)
19680b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
19690b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 8);
19700b57cec5SDimitry Andric       else
19710b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
19720b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 4);
19730b57cec5SDimitry Andric       MI->setFlag(MachineInstr::FrameSetup);
19740b57cec5SDimitry Andric       MBB.insert(MBBI, MI);
19750b57cec5SDimitry Andric     }
19760b57cec5SDimitry Andric   } else if (NumBytes) {
19770b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
19780b57cec5SDimitry Andric   }
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   if (NeedsWinCFI && NumBytes) {
19810b57cec5SDimitry Andric     HasWinCFI = true;
19820b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
19830b57cec5SDimitry Andric         .addImm(NumBytes)
19840b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
19850b57cec5SDimitry Andric   }
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   int SEHFrameOffset = 0;
19880b57cec5SDimitry Andric   unsigned SPOrEstablisher;
19890b57cec5SDimitry Andric   if (IsFunclet) {
19900b57cec5SDimitry Andric     if (IsClrFunclet) {
19910b57cec5SDimitry Andric       // The establisher parameter passed to a CLR funclet is actually a pointer
19920b57cec5SDimitry Andric       // to the (mostly empty) frame of its nearest enclosing funclet; we have
19930b57cec5SDimitry Andric       // to find the root function establisher frame by loading the PSPSym from
19940b57cec5SDimitry Andric       // the intermediate frame.
19950b57cec5SDimitry Andric       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
19960b57cec5SDimitry Andric       MachinePointerInfo NoInfo;
19970b57cec5SDimitry Andric       MBB.addLiveIn(Establisher);
19980b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
19990b57cec5SDimitry Andric                    Establisher, false, PSPSlotOffset)
20000b57cec5SDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
20015ffd83dbSDimitry Andric               NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize)));
20020b57cec5SDimitry Andric       ;
20030b57cec5SDimitry Andric       // Save the root establisher back into the current funclet's (mostly
20040b57cec5SDimitry Andric       // empty) frame, in case a sub-funclet or the GC needs it.
20050b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
20060b57cec5SDimitry Andric                    false, PSPSlotOffset)
20070b57cec5SDimitry Andric           .addReg(Establisher)
20085ffd83dbSDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
20095ffd83dbSDimitry Andric               NoInfo,
20105ffd83dbSDimitry Andric               MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
20115ffd83dbSDimitry Andric               SlotSize, Align(SlotSize)));
20120b57cec5SDimitry Andric     }
20130b57cec5SDimitry Andric     SPOrEstablisher = Establisher;
20140b57cec5SDimitry Andric   } else {
20150b57cec5SDimitry Andric     SPOrEstablisher = StackPtr;
20160b57cec5SDimitry Andric   }
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric   if (IsWin64Prologue && HasFP) {
20190b57cec5SDimitry Andric     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
20200b57cec5SDimitry Andric     // this calculation on the incoming establisher, which holds the value of
20210b57cec5SDimitry Andric     // RSP from the parent frame at the end of the prologue.
20220b57cec5SDimitry Andric     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
20230b57cec5SDimitry Andric     if (SEHFrameOffset)
20240b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
20250b57cec5SDimitry Andric                    SPOrEstablisher, false, SEHFrameOffset);
20260b57cec5SDimitry Andric     else
20270b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
20280b57cec5SDimitry Andric           .addReg(SPOrEstablisher);
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric     // If this is not a funclet, emit the CFI describing our frame pointer.
20310b57cec5SDimitry Andric     if (NeedsWinCFI && !IsFunclet) {
20320b57cec5SDimitry Andric       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
20330b57cec5SDimitry Andric       HasWinCFI = true;
20340b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
20350b57cec5SDimitry Andric           .addImm(FramePtr)
20360b57cec5SDimitry Andric           .addImm(SEHFrameOffset)
20370b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
20380b57cec5SDimitry Andric       if (isAsynchronousEHPersonality(Personality))
20390b57cec5SDimitry Andric         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
20400b57cec5SDimitry Andric     }
20410b57cec5SDimitry Andric   } else if (IsFunclet && STI.is32Bit()) {
20420b57cec5SDimitry Andric     // Reset EBP / ESI to something good for funclets.
20430b57cec5SDimitry Andric     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
20440b57cec5SDimitry Andric     // If we're a catch funclet, we can be returned to via catchret. Save ESP
20450b57cec5SDimitry Andric     // into the registration node so that the runtime will restore it for us.
20460b57cec5SDimitry Andric     if (!MBB.isCleanupFuncletEntry()) {
20470b57cec5SDimitry Andric       assert(Personality == EHPersonality::MSVC_CXX);
20485ffd83dbSDimitry Andric       Register FrameReg;
20490b57cec5SDimitry Andric       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
2050e8d8bef9SDimitry Andric       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
20510b57cec5SDimitry Andric       // ESP is the first field, so no extra displacement is needed.
20520b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
20530b57cec5SDimitry Andric                    false, EHRegOffset)
20540b57cec5SDimitry Andric           .addReg(X86::ESP);
20550b57cec5SDimitry Andric     }
20560b57cec5SDimitry Andric   }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
20590b57cec5SDimitry Andric     const MachineInstr &FrameInstr = *MBBI;
20600b57cec5SDimitry Andric     ++MBBI;
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric     if (NeedsWinCFI) {
20630b57cec5SDimitry Andric       int FI;
20640b57cec5SDimitry Andric       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
20650b57cec5SDimitry Andric         if (X86::FR64RegClass.contains(Reg)) {
2066c14a5a88SDimitry Andric           int Offset;
20675ffd83dbSDimitry Andric           Register IgnoredFrameReg;
2068c14a5a88SDimitry Andric           if (IsWin64Prologue && IsFunclet)
2069c14a5a88SDimitry Andric             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
2070c14a5a88SDimitry Andric           else
2071e8d8bef9SDimitry Andric             Offset =
2072e8d8bef9SDimitry Andric                 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2073c14a5a88SDimitry Andric                 SEHFrameOffset;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric           HasWinCFI = true;
20760b57cec5SDimitry Andric           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
20770b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
20780b57cec5SDimitry Andric               .addImm(Reg)
20790b57cec5SDimitry Andric               .addImm(Offset)
20800b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
20810b57cec5SDimitry Andric         }
20820b57cec5SDimitry Andric       }
20830b57cec5SDimitry Andric     }
20840b57cec5SDimitry Andric   }
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   if (NeedsWinCFI && HasWinCFI)
20870b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
20880b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   if (FnHasClrFunclet && !IsFunclet) {
20910b57cec5SDimitry Andric     // Save the so-called Initial-SP (i.e. the value of the stack pointer
20920b57cec5SDimitry Andric     // immediately after the prolog)  into the PSPSlot so that funclets
20930b57cec5SDimitry Andric     // and the GC can recover it.
20940b57cec5SDimitry Andric     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
20950b57cec5SDimitry Andric     auto PSPInfo = MachinePointerInfo::getFixedStack(
20960b57cec5SDimitry Andric         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
20970b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
20980b57cec5SDimitry Andric                  PSPSlotOffset)
20990b57cec5SDimitry Andric         .addReg(StackPtr)
21000b57cec5SDimitry Andric         .addMemOperand(MF.getMachineMemOperand(
21010b57cec5SDimitry Andric             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
21025ffd83dbSDimitry Andric             SlotSize, Align(SlotSize)));
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   // Realign stack after we spilled callee-saved registers (so that we'll be
21060b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
21070b57cec5SDimitry Andric   // Win64 requires aligning the stack after the prologue.
2108fe6060f1SDimitry Andric   if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
21090b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
21100b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // We already dealt with stack realignment and funclets above.
21140b57cec5SDimitry Andric   if (IsFunclet && STI.is32Bit())
21150b57cec5SDimitry Andric     return;
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
21180b57cec5SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
21190b57cec5SDimitry Andric   // will be allocated after this, so we can still use the base pointer
21200b57cec5SDimitry Andric   // to reference locals.
21210b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
21220b57cec5SDimitry Andric     // Update the base pointer with the current stack pointer.
21230b57cec5SDimitry Andric     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
21240b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
21250b57cec5SDimitry Andric       .addReg(SPOrEstablisher)
21260b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
21270b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer()) {
21280b57cec5SDimitry Andric       // Stash value of base pointer.  Saving RSP instead of EBP shortens
21290b57cec5SDimitry Andric       // dependence chain. Used by SjLj EH.
21300b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
21310b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
21320b57cec5SDimitry Andric                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
21330b57cec5SDimitry Andric         .addReg(SPOrEstablisher)
21340b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
21350b57cec5SDimitry Andric     }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
21380b57cec5SDimitry Andric       // Stash the value of the frame pointer relative to the base pointer for
21390b57cec5SDimitry Andric       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
21400b57cec5SDimitry Andric       // it recovers the frame pointer from the base pointer rather than the
21410b57cec5SDimitry Andric       // other way around.
21420b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
21435ffd83dbSDimitry Andric       Register UsedReg;
21440b57cec5SDimitry Andric       int Offset =
2145e8d8bef9SDimitry Andric           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2146e8d8bef9SDimitry Andric               .getFixed();
21470b57cec5SDimitry Andric       assert(UsedReg == BasePtr);
21480b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
21490b57cec5SDimitry Andric           .addReg(FramePtr)
21500b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
21510b57cec5SDimitry Andric     }
21520b57cec5SDimitry Andric   }
2153*06c3fb27SDimitry Andric   if (ArgBaseReg.isValid()) {
2154*06c3fb27SDimitry Andric     // Save argument base pointer.
2155*06c3fb27SDimitry Andric     auto *MI = X86FI->getStackPtrSaveMI();
2156*06c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
2157*06c3fb27SDimitry Andric     unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
2158*06c3fb27SDimitry Andric     // movl    %basereg, offset(%ebp)
2159*06c3fb27SDimitry Andric     addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), FI)
2160*06c3fb27SDimitry Andric         .addReg(ArgBaseReg)
2161*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
2162*06c3fb27SDimitry Andric   }
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
21650b57cec5SDimitry Andric     // Mark end of stack pointer adjustment.
21660b57cec5SDimitry Andric     if (!HasFP && NumBytes) {
21670b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
21680b57cec5SDimitry Andric       assert(StackSize);
21695ffd83dbSDimitry Andric       BuildCFI(
21705ffd83dbSDimitry Andric           MBB, MBBI, DL,
217181ad6265SDimitry Andric           MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
217281ad6265SDimitry Andric           MachineInstr::FrameSetup);
21730b57cec5SDimitry Andric     }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric     // Emit DWARF info specifying the offsets of the callee-saved registers.
21765ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DL, true);
21770b57cec5SDimitry Andric   }
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric   // X86 Interrupt handling function cannot assume anything about the direction
21800b57cec5SDimitry Andric   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
21810b57cec5SDimitry Andric   // in each prologue of interrupt handler function.
21820b57cec5SDimitry Andric   //
21830b57cec5SDimitry Andric   // FIXME: Create "cld" instruction only in these cases:
21840b57cec5SDimitry Andric   // 1. The interrupt handling function uses any of the "rep" instructions.
21850b57cec5SDimitry Andric   // 2. Interrupt handling function calls another function.
21860b57cec5SDimitry Andric   //
21870b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR)
21880b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
21890b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   // At this point we know if the function has WinCFI or not.
21920b57cec5SDimitry Andric   MF.setHasWinCFI(HasWinCFI);
21930b57cec5SDimitry Andric }
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric bool X86FrameLowering::canUseLEAForSPInEpilogue(
21960b57cec5SDimitry Andric     const MachineFunction &MF) const {
21970b57cec5SDimitry Andric   // We can't use LEA instructions for adjusting the stack pointer if we don't
21980b57cec5SDimitry Andric   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
21990b57cec5SDimitry Andric   // to deallocate the stack.
22000b57cec5SDimitry Andric   // This means that we can use LEA for SP in two situations:
22010b57cec5SDimitry Andric   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
22020b57cec5SDimitry Andric   // 2. We *have* a frame pointer which means we are permitted to use LEA.
22030b57cec5SDimitry Andric   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric static bool isFuncletReturnInstr(MachineInstr &MI) {
22070b57cec5SDimitry Andric   switch (MI.getOpcode()) {
22080b57cec5SDimitry Andric   case X86::CATCHRET:
22090b57cec5SDimitry Andric   case X86::CLEANUPRET:
22100b57cec5SDimitry Andric     return true;
22110b57cec5SDimitry Andric   default:
22120b57cec5SDimitry Andric     return false;
22130b57cec5SDimitry Andric   }
22140b57cec5SDimitry Andric   llvm_unreachable("impossible");
22150b57cec5SDimitry Andric }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
22180b57cec5SDimitry Andric // stack. It holds a pointer to the bottom of the root function frame.  The
22190b57cec5SDimitry Andric // establisher frame pointer passed to a nested funclet may point to the
22200b57cec5SDimitry Andric // (mostly empty) frame of its parent funclet, but it will need to find
22210b57cec5SDimitry Andric // the frame of the root function to access locals.  To facilitate this,
22220b57cec5SDimitry Andric // every funclet copies the pointer to the bottom of the root function
22230b57cec5SDimitry Andric // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
22240b57cec5SDimitry Andric // same offset for the PSPSym in the root function frame that's used in the
22250b57cec5SDimitry Andric // funclets' frames allows each funclet to dynamically accept any ancestor
22260b57cec5SDimitry Andric // frame as its establisher argument (the runtime doesn't guarantee the
22270b57cec5SDimitry Andric // immediate parent for some reason lost to history), and also allows the GC,
22280b57cec5SDimitry Andric // which uses the PSPSym for some bookkeeping, to find it in any funclet's
22290b57cec5SDimitry Andric // frame with only a single offset reported for the entire method.
22300b57cec5SDimitry Andric unsigned
22310b57cec5SDimitry Andric X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
22320b57cec5SDimitry Andric   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
22335ffd83dbSDimitry Andric   Register SPReg;
22340b57cec5SDimitry Andric   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2235e8d8bef9SDimitry Andric                                               /*IgnoreSPUpdates*/ true)
2236e8d8bef9SDimitry Andric                    .getFixed();
22370b57cec5SDimitry Andric   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
22380b57cec5SDimitry Andric   return static_cast<unsigned>(Offset);
22390b57cec5SDimitry Andric }
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric unsigned
22420b57cec5SDimitry Andric X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2243c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
22440b57cec5SDimitry Andric   // This is the size of the pushed CSRs.
2245c14a5a88SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2246c14a5a88SDimitry Andric   // This is the size of callee saved XMMs.
2247c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2248c14a5a88SDimitry Andric   unsigned XMMSize = WinEHXMMSlotInfo.size() *
2249c14a5a88SDimitry Andric                      TRI->getSpillSize(X86::VR128RegClass);
22500b57cec5SDimitry Andric   // This is the amount of stack a funclet needs to allocate.
22510b57cec5SDimitry Andric   unsigned UsedSize;
22520b57cec5SDimitry Andric   EHPersonality Personality =
22530b57cec5SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn());
22540b57cec5SDimitry Andric   if (Personality == EHPersonality::CoreCLR) {
22550b57cec5SDimitry Andric     // CLR funclets need to hold enough space to include the PSPSym, at the
22560b57cec5SDimitry Andric     // same offset from the stack pointer (immediately after the prolog) as it
22570b57cec5SDimitry Andric     // resides at in the main function.
22580b57cec5SDimitry Andric     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
22590b57cec5SDimitry Andric   } else {
22600b57cec5SDimitry Andric     // Other funclets just need enough stack for outgoing call arguments.
22610b57cec5SDimitry Andric     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
22620b57cec5SDimitry Andric   }
22630b57cec5SDimitry Andric   // RBP is not included in the callee saved register block. After pushing RBP,
22640b57cec5SDimitry Andric   // everything is 16 byte aligned. Everything we allocate before an outgoing
22650b57cec5SDimitry Andric   // call must also be 16 byte aligned.
22665ffd83dbSDimitry Andric   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
22670b57cec5SDimitry Andric   // Subtract out the size of the callee saved registers. This is how much stack
22680b57cec5SDimitry Andric   // each funclet will allocate.
2269c14a5a88SDimitry Andric   return FrameSizeMinusRBP + XMMSize - CSSize;
22700b57cec5SDimitry Andric }
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric static bool isTailCallOpcode(unsigned Opc) {
22730b57cec5SDimitry Andric     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
22740b57cec5SDimitry Andric         Opc == X86::TCRETURNmi ||
22750b57cec5SDimitry Andric         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
22760b57cec5SDimitry Andric         Opc == X86::TCRETURNmi64;
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric void X86FrameLowering::emitEpilogue(MachineFunction &MF,
22800b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
22810b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
22820b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
22830b57cec5SDimitry Andric   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
22840b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = Terminator;
22850b57cec5SDimitry Andric   DebugLoc DL;
22860b57cec5SDimitry Andric   if (MBBI != MBB.end())
22870b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
22880b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
22890b57cec5SDimitry Andric   const bool Is64BitILP32 = STI.isTarget64BitILP32();
22908bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
2291e8d8bef9SDimitry Andric   Register MachineFramePtr =
22928bcb0991SDimitry Andric       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
22950b57cec5SDimitry Andric   bool NeedsWin64CFI =
22960b57cec5SDimitry Andric       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
22970b57cec5SDimitry Andric   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   // Get the number of bytes to allocate from the FrameInfo.
23000b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
23010b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF);
23020b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2303349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
23040b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
23050b57cec5SDimitry Andric   uint64_t NumBytes = 0;
23060b57cec5SDimitry Andric 
2307480093f4SDimitry Andric   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
23080b57cec5SDimitry Andric                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
2309480093f4SDimitry Andric                        MF.needsFrameMoves();
23100b57cec5SDimitry Andric 
2311*06c3fb27SDimitry Andric   Register ArgBaseReg;
2312*06c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
2313*06c3fb27SDimitry Andric     unsigned Opc = X86::LEA32r;
2314*06c3fb27SDimitry Andric     Register StackReg = X86::ESP;
2315*06c3fb27SDimitry Andric     ArgBaseReg = MI->getOperand(0).getReg();
2316*06c3fb27SDimitry Andric     if (STI.is64Bit()) {
2317*06c3fb27SDimitry Andric       Opc = X86::LEA64r;
2318*06c3fb27SDimitry Andric       StackReg = X86::RSP;
2319*06c3fb27SDimitry Andric     }
2320*06c3fb27SDimitry Andric     // leal    -4(%basereg), %esp
2321*06c3fb27SDimitry Andric     // .cfi_def_cfa %esp, 4
2322*06c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), StackReg)
2323*06c3fb27SDimitry Andric         .addUse(ArgBaseReg)
2324*06c3fb27SDimitry Andric         .addImm(1)
2325*06c3fb27SDimitry Andric         .addUse(X86::NoRegister)
2326*06c3fb27SDimitry Andric         .addImm(-(int64_t)SlotSize)
2327*06c3fb27SDimitry Andric         .addUse(X86::NoRegister)
2328*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
2329*06c3fb27SDimitry Andric     if (NeedsDwarfCFI) {
2330*06c3fb27SDimitry Andric       unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackReg, true);
2331*06c3fb27SDimitry Andric       BuildCFI(MBB, MBBI, DL,
2332*06c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2333*06c3fb27SDimitry Andric                MachineInstr::FrameDestroy);
2334*06c3fb27SDimitry Andric       --MBBI;
2335*06c3fb27SDimitry Andric     }
2336*06c3fb27SDimitry Andric     --MBBI;
2337*06c3fb27SDimitry Andric   }
2338*06c3fb27SDimitry Andric 
23390b57cec5SDimitry Andric   if (IsFunclet) {
23400b57cec5SDimitry Andric     assert(HasFP && "EH funclets without FP not yet implemented");
23410b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
23420b57cec5SDimitry Andric   } else if (HasFP) {
23430b57cec5SDimitry Andric     // Calculate required stack adjustment.
23440b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
2345349cc55cSDimitry Andric     NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric     // Callee-saved registers were pushed on stack before the stack was
23480b57cec5SDimitry Andric     // realigned.
2349fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
23500b57cec5SDimitry Andric       NumBytes = alignTo(FrameSize, MaxAlign);
23510b57cec5SDimitry Andric   } else {
2352349cc55cSDimitry Andric     NumBytes = StackSize - CSSize - TailCallArgReserveSize;
23530b57cec5SDimitry Andric   }
23540b57cec5SDimitry Andric   uint64_t SEHStackAllocAmt = NumBytes;
23550b57cec5SDimitry Andric 
23565ffd83dbSDimitry Andric   // AfterPop is the position to insert .cfi_restore.
23575ffd83dbSDimitry Andric   MachineBasicBlock::iterator AfterPop = MBBI;
23580b57cec5SDimitry Andric   if (HasFP) {
2359fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2360fe6060f1SDimitry Andric       // Discard the context.
2361fe6060f1SDimitry Andric       int Offset = 16 + mergeSPUpdates(MBB, MBBI, true);
2362fe6060f1SDimitry Andric       emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/true);
2363fe6060f1SDimitry Andric     }
23640b57cec5SDimitry Andric     // Pop EBP.
23650b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
23660b57cec5SDimitry Andric             MachineFramePtr)
23670b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
2368fe6060f1SDimitry Andric 
2369fe6060f1SDimitry Andric     // We need to reset FP to its untagged state on return. Bit 60 is currently
2370fe6060f1SDimitry Andric     // used to show the presence of an extended frame.
2371fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2372fe6060f1SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8),
2373fe6060f1SDimitry Andric               MachineFramePtr)
2374fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
2375fe6060f1SDimitry Andric           .addImm(60)
2376fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameDestroy);
2377fe6060f1SDimitry Andric     }
2378fe6060f1SDimitry Andric 
23790b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
2380*06c3fb27SDimitry Andric       if (!ArgBaseReg.isValid()) {
23810b57cec5SDimitry Andric         unsigned DwarfStackPtr =
23820b57cec5SDimitry Andric             TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
23835ffd83dbSDimitry Andric         BuildCFI(MBB, MBBI, DL,
238481ad6265SDimitry Andric                  MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
238581ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
2386*06c3fb27SDimitry Andric       }
23875ffd83dbSDimitry Andric       if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
23885ffd83dbSDimitry Andric         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
23895ffd83dbSDimitry Andric         BuildCFI(MBB, AfterPop, DL,
239081ad6265SDimitry Andric                  MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
239181ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
23925ffd83dbSDimitry Andric         --MBBI;
23935ffd83dbSDimitry Andric         --AfterPop;
23945ffd83dbSDimitry Andric       }
23950b57cec5SDimitry Andric       --MBBI;
23960b57cec5SDimitry Andric     }
23970b57cec5SDimitry Andric   }
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric   MachineBasicBlock::iterator FirstCSPop = MBBI;
24000b57cec5SDimitry Andric   // Skip the callee-saved pop instructions.
24010b57cec5SDimitry Andric   while (MBBI != MBB.begin()) {
24020b57cec5SDimitry Andric     MachineBasicBlock::iterator PI = std::prev(MBBI);
24030b57cec5SDimitry Andric     unsigned Opc = PI->getOpcode();
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
24060b57cec5SDimitry Andric       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2407fe6060f1SDimitry Andric           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2408fe6060f1SDimitry Andric           (Opc != X86::BTR64ri8 || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2409*06c3fb27SDimitry Andric           (Opc != X86::ADD64ri32 || !PI->getFlag(MachineInstr::FrameDestroy)))
24100b57cec5SDimitry Andric         break;
24110b57cec5SDimitry Andric       FirstCSPop = PI;
24120b57cec5SDimitry Andric     }
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric     --MBBI;
24150b57cec5SDimitry Andric   }
2416*06c3fb27SDimitry Andric   if (ArgBaseReg.isValid()) {
2417*06c3fb27SDimitry Andric     // Restore argument base pointer.
2418*06c3fb27SDimitry Andric     auto *MI = X86FI->getStackPtrSaveMI();
2419*06c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
2420*06c3fb27SDimitry Andric     unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm;
2421*06c3fb27SDimitry Andric     // movl   offset(%ebp), %basereg
2422*06c3fb27SDimitry Andric     addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVrm), ArgBaseReg), FI)
2423*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
2424*06c3fb27SDimitry Andric   }
24250b57cec5SDimitry Andric   MBBI = FirstCSPop;
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
24280b57cec5SDimitry Andric     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric   if (MBBI != MBB.end())
24310b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
24320b57cec5SDimitry Andric   // If there is an ADD32ri or SUB32ri of ESP immediately before this
24330b57cec5SDimitry Andric   // instruction, merge the two instructions.
24340b57cec5SDimitry Andric   if (NumBytes || MFI.hasVarSizedObjects())
24350b57cec5SDimitry Andric     NumBytes += mergeSPUpdates(MBB, MBBI, true);
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   // If dynamic alloca is used, then reset esp to point to the last callee-saved
24380b57cec5SDimitry Andric   // slot before popping them off! Same applies for the case, when stack was
24390b57cec5SDimitry Andric   // realigned. Don't do this if this was a funclet epilogue, since the funclets
24400b57cec5SDimitry Andric   // will not do realignment or dynamic stack allocation.
2441fe6060f1SDimitry Andric   if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
24420b57cec5SDimitry Andric       !IsFunclet) {
2443fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF))
24440b57cec5SDimitry Andric       MBBI = FirstCSPop;
24450b57cec5SDimitry Andric     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
24460b57cec5SDimitry Andric     uint64_t LEAAmount =
24470b57cec5SDimitry Andric         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
24480b57cec5SDimitry Andric 
2449fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext())
2450fe6060f1SDimitry Andric       LEAAmount -= 16;
2451fe6060f1SDimitry Andric 
24520b57cec5SDimitry Andric     // There are only two legal forms of epilogue:
24530b57cec5SDimitry Andric     // - add SEHAllocationSize, %rsp
24540b57cec5SDimitry Andric     // - lea SEHAllocationSize(%FramePtr), %rsp
24550b57cec5SDimitry Andric     //
24560b57cec5SDimitry Andric     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
24570b57cec5SDimitry Andric     // However, we may use this sequence if we have a frame pointer because the
24580b57cec5SDimitry Andric     // effects of the prologue can safely be undone.
24590b57cec5SDimitry Andric     if (LEAAmount != 0) {
24600b57cec5SDimitry Andric       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
24610b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
24620b57cec5SDimitry Andric                    FramePtr, false, LEAAmount);
24630b57cec5SDimitry Andric       --MBBI;
24640b57cec5SDimitry Andric     } else {
24650b57cec5SDimitry Andric       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
24660b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
24670b57cec5SDimitry Andric         .addReg(FramePtr);
24680b57cec5SDimitry Andric       --MBBI;
24690b57cec5SDimitry Andric     }
24700b57cec5SDimitry Andric   } else if (NumBytes) {
24710b57cec5SDimitry Andric     // Adjust stack pointer back: ESP += numbytes.
24720b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2473349cc55cSDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
24740b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
24755ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
2476349cc55cSDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(
247781ad6265SDimitry Andric                    nullptr, CSSize + TailCallArgReserveSize + SlotSize),
247881ad6265SDimitry Andric                MachineInstr::FrameDestroy);
24790b57cec5SDimitry Andric     }
24800b57cec5SDimitry Andric     --MBBI;
24810b57cec5SDimitry Andric   }
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric   // Windows unwinder will not invoke function's exception handler if IP is
24840b57cec5SDimitry Andric   // either in prologue or in epilogue.  This behavior causes a problem when a
24850b57cec5SDimitry Andric   // call immediately precedes an epilogue, because the return address points
24860b57cec5SDimitry Andric   // into the epilogue.  To cope with that, we insert an epilogue marker here,
24870b57cec5SDimitry Andric   // then replace it with a 'nop' if it ends up immediately after a CALL in the
24880b57cec5SDimitry Andric   // final emitted code.
24890b57cec5SDimitry Andric   if (NeedsWin64CFI && MF.hasWinCFI())
24900b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
24910b57cec5SDimitry Andric 
2492349cc55cSDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
24930b57cec5SDimitry Andric     MBBI = FirstCSPop;
24940b57cec5SDimitry Andric     int64_t Offset = -CSSize - SlotSize;
24950b57cec5SDimitry Andric     // Mark callee-saved pop instruction.
24960b57cec5SDimitry Andric     // Define the current CFA rule to use the provided offset.
24970b57cec5SDimitry Andric     while (MBBI != MBB.end()) {
24980b57cec5SDimitry Andric       MachineBasicBlock::iterator PI = MBBI;
24990b57cec5SDimitry Andric       unsigned Opc = PI->getOpcode();
25000b57cec5SDimitry Andric       ++MBBI;
25010b57cec5SDimitry Andric       if (Opc == X86::POP32r || Opc == X86::POP64r) {
25020b57cec5SDimitry Andric         Offset += SlotSize;
25030b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
250481ad6265SDimitry Andric                  MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset),
250581ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
25060b57cec5SDimitry Andric       }
25070b57cec5SDimitry Andric     }
25080b57cec5SDimitry Andric   }
25090b57cec5SDimitry Andric 
25105ffd83dbSDimitry Andric   // Emit DWARF info specifying the restores of the callee-saved registers.
25115ffd83dbSDimitry Andric   // For epilogue with return inside or being other block without successor,
25125ffd83dbSDimitry Andric   // no need to generate .cfi_restore for callee-saved registers.
2513349cc55cSDimitry Andric   if (NeedsDwarfCFI && !MBB.succ_empty())
25145ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
25155ffd83dbSDimitry Andric 
25160b57cec5SDimitry Andric   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
25170b57cec5SDimitry Andric     // Add the return addr area delta back since we are not tail calling.
25180b57cec5SDimitry Andric     int Offset = -1 * X86FI->getTCReturnAddrDelta();
25190b57cec5SDimitry Andric     assert(Offset >= 0 && "TCDelta should never be positive");
25200b57cec5SDimitry Andric     if (Offset) {
25210b57cec5SDimitry Andric       // Check for possible merge with preceding ADD instruction.
25220b57cec5SDimitry Andric       Offset += mergeSPUpdates(MBB, Terminator, true);
25230b57cec5SDimitry Andric       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
25240b57cec5SDimitry Andric     }
25250b57cec5SDimitry Andric   }
2526e8d8bef9SDimitry Andric 
2527e8d8bef9SDimitry Andric   // Emit tilerelease for AMX kernel.
2528349cc55cSDimitry Andric   if (X86FI->hasVirtualTileReg())
2529e8d8bef9SDimitry Andric     BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
25300b57cec5SDimitry Andric }
25310b57cec5SDimitry Andric 
2532e8d8bef9SDimitry Andric StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF,
2533e8d8bef9SDimitry Andric                                                      int FI,
25345ffd83dbSDimitry Andric                                                      Register &FrameReg) const {
25350b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   bool IsFixed = MFI.isFixedObjectIndex(FI);
25380b57cec5SDimitry Andric   // We can't calculate offset from frame pointer if the stack is realigned,
25390b57cec5SDimitry Andric   // so enforce usage of stack/base pointer.  The base pointer is used when we
25400b57cec5SDimitry Andric   // have dynamic allocas in addition to dynamic realignment.
25410b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF))
25420b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2543fe6060f1SDimitry Andric   else if (TRI->hasStackRealignment(MF))
25440b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
25450b57cec5SDimitry Andric   else
25460b57cec5SDimitry Andric     FrameReg = TRI->getFrameRegister(MF);
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric   // Offset will hold the offset from the stack pointer at function entry to the
25490b57cec5SDimitry Andric   // object.
25500b57cec5SDimitry Andric   // We need to factor in additional offsets applied during the prologue to the
25510b57cec5SDimitry Andric   // frame, base, and stack pointer depending on which is used.
25520b57cec5SDimitry Andric   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
25530b57cec5SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
25540b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
25550b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
25560b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
25570b57cec5SDimitry Andric   int64_t FPDelta = 0;
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   // In an x86 interrupt, remove the offset we added to account for the return
25600b57cec5SDimitry Andric   // address from any stack object allocated in the caller's frame. Interrupts
25610b57cec5SDimitry Andric   // do not have a standard return address. Fixed objects in the current frame,
25620b57cec5SDimitry Andric   // such as SSE register spills, should not get this treatment.
25630b57cec5SDimitry Andric   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
25640b57cec5SDimitry Andric       Offset >= 0) {
25650b57cec5SDimitry Andric     Offset += getOffsetOfLocalArea();
25660b57cec5SDimitry Andric   }
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   if (IsWin64Prologue) {
25690b57cec5SDimitry Andric     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric     // Calculate required stack adjustment.
25720b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
25730b57cec5SDimitry Andric     // If required, include space for extra hidden slot for stashing base pointer.
25740b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
25750b57cec5SDimitry Andric       FrameSize += SlotSize;
25760b57cec5SDimitry Andric     uint64_t NumBytes = FrameSize - CSSize;
25770b57cec5SDimitry Andric 
25780b57cec5SDimitry Andric     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
25790b57cec5SDimitry Andric     if (FI && FI == X86FI->getFAIndex())
2580e8d8bef9SDimitry Andric       return StackOffset::getFixed(-SEHFrameOffset);
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric     // FPDelta is the offset from the "traditional" FP location of the old base
25830b57cec5SDimitry Andric     // pointer followed by return address and the location required by the
25840b57cec5SDimitry Andric     // restricted Win64 prologue.
25850b57cec5SDimitry Andric     // Add FPDelta to all offsets below that go through the frame pointer.
25860b57cec5SDimitry Andric     FPDelta = FrameSize - SEHFrameOffset;
25870b57cec5SDimitry Andric     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
25880b57cec5SDimitry Andric            "FPDelta isn't aligned per the Win64 ABI!");
25890b57cec5SDimitry Andric   }
25900b57cec5SDimitry Andric 
2591349cc55cSDimitry Andric   if (FrameReg == TRI->getFramePtr()) {
2592349cc55cSDimitry Andric     // Skip saved EBP/RBP
25930b57cec5SDimitry Andric     Offset += SlotSize;
25940b57cec5SDimitry Andric 
2595349cc55cSDimitry Andric     // Account for restricted Windows prologue.
2596349cc55cSDimitry Andric     Offset += FPDelta;
2597349cc55cSDimitry Andric 
25980b57cec5SDimitry Andric     // Skip the RETADDR move area
25990b57cec5SDimitry Andric     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
26000b57cec5SDimitry Andric     if (TailCallReturnAddrDelta < 0)
26010b57cec5SDimitry Andric       Offset -= TailCallReturnAddrDelta;
2602349cc55cSDimitry Andric 
2603349cc55cSDimitry Andric     return StackOffset::getFixed(Offset);
26040b57cec5SDimitry Andric   }
26050b57cec5SDimitry Andric 
2606349cc55cSDimitry Andric   // FrameReg is either the stack pointer or a base pointer. But the base is
2607349cc55cSDimitry Andric   // located at the end of the statically known StackSize so the distinction
2608349cc55cSDimitry Andric   // doesn't really matter.
2609349cc55cSDimitry Andric   if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
2610349cc55cSDimitry Andric     assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2611349cc55cSDimitry Andric   return StackOffset::getFixed(Offset + StackSize);
26120b57cec5SDimitry Andric }
26130b57cec5SDimitry Andric 
26145ffd83dbSDimitry Andric int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI,
26155ffd83dbSDimitry Andric                                               Register &FrameReg) const {
2616c14a5a88SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
2617c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2618c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2619c14a5a88SDimitry Andric   const auto it = WinEHXMMSlotInfo.find(FI);
2620c14a5a88SDimitry Andric 
2621c14a5a88SDimitry Andric   if (it == WinEHXMMSlotInfo.end())
2622e8d8bef9SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg).getFixed();
2623c14a5a88SDimitry Andric 
2624c14a5a88SDimitry Andric   FrameReg = TRI->getStackRegister();
26255ffd83dbSDimitry Andric   return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
26265ffd83dbSDimitry Andric          it->second;
2627c14a5a88SDimitry Andric }
2628c14a5a88SDimitry Andric 
2629e8d8bef9SDimitry Andric StackOffset
2630e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI,
2631e8d8bef9SDimitry Andric                                            Register &FrameReg,
26320b57cec5SDimitry Andric                                            int Adjustment) const {
26330b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
26340b57cec5SDimitry Andric   FrameReg = TRI->getStackRegister();
2635e8d8bef9SDimitry Andric   return StackOffset::getFixed(MFI.getObjectOffset(FI) -
2636e8d8bef9SDimitry Andric                                getOffsetOfLocalArea() + Adjustment);
26370b57cec5SDimitry Andric }
26380b57cec5SDimitry Andric 
2639e8d8bef9SDimitry Andric StackOffset
2640e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2641e8d8bef9SDimitry Andric                                                  int FI, Register &FrameReg,
26420b57cec5SDimitry Andric                                                  bool IgnoreSPUpdates) const {
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
26450b57cec5SDimitry Andric   // Does not include any dynamic realign.
26460b57cec5SDimitry Andric   const uint64_t StackSize = MFI.getStackSize();
26470b57cec5SDimitry Andric   // LLVM arranges the stack as follows:
26480b57cec5SDimitry Andric   //   ...
26490b57cec5SDimitry Andric   //   ARG2
26500b57cec5SDimitry Andric   //   ARG1
26510b57cec5SDimitry Andric   //   RETADDR
26520b57cec5SDimitry Andric   //   PUSH RBP   <-- RBP points here
26530b57cec5SDimitry Andric   //   PUSH CSRs
26540b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (non-win64)
26550b57cec5SDimitry Andric   //   ...
26560b57cec5SDimitry Andric   //   STACK OBJECTS
26570b57cec5SDimitry Andric   //   ...        <-- RSP after prologue points here
26580b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (win64)
26590b57cec5SDimitry Andric   //
26600b57cec5SDimitry Andric   // if (hasVarSizedObjects()):
26610b57cec5SDimitry Andric   //   ...        <-- "base pointer" (ESI/RBX) points here
26620b57cec5SDimitry Andric   //   DYNAMIC ALLOCAS
26630b57cec5SDimitry Andric   //   ...        <-- RSP points here
26640b57cec5SDimitry Andric   //
26650b57cec5SDimitry Andric   // Case 1: In the simple case of no stack realignment and no dynamic
26660b57cec5SDimitry Andric   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
26670b57cec5SDimitry Andric   // with fixed offsets from RSP.
26680b57cec5SDimitry Andric   //
26690b57cec5SDimitry Andric   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
26700b57cec5SDimitry Andric   // stack objects are addressed with RBP and regular stack objects with RSP.
26710b57cec5SDimitry Andric   //
26720b57cec5SDimitry Andric   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
26730b57cec5SDimitry Andric   // to address stack arguments for outgoing calls and nothing else. The "base
26740b57cec5SDimitry Andric   // pointer" points to local variables, and RBP points to fixed objects.
26750b57cec5SDimitry Andric   //
26760b57cec5SDimitry Andric   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
26770b57cec5SDimitry Andric   // answer we give is relative to the SP after the prologue, and not the
26780b57cec5SDimitry Andric   // SP in the middle of the function.
26790b57cec5SDimitry Andric 
2680fe6060f1SDimitry Andric   if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
26810b57cec5SDimitry Andric       !STI.isTargetWin64())
26820b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric   // If !hasReservedCallFrame the function might have SP adjustement in the
26850b57cec5SDimitry Andric   // body.  So, even though the offset is statically known, it depends on where
26860b57cec5SDimitry Andric   // we are in the function.
26870b57cec5SDimitry Andric   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
26880b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric   // We don't handle tail calls, and shouldn't be seeing them either.
26910b57cec5SDimitry Andric   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
26920b57cec5SDimitry Andric          "we don't handle this case!");
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric   // This is how the math works out:
26950b57cec5SDimitry Andric   //
26960b57cec5SDimitry Andric   //  %rsp grows (i.e. gets lower) left to right. Each box below is
26970b57cec5SDimitry Andric   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
26980b57cec5SDimitry Andric   //  get to.
26990b57cec5SDimitry Andric   //
27000b57cec5SDimitry Andric   //    ----------------------------------
27010b57cec5SDimitry Andric   //    | BP | Obj0 | Obj1 | ... | ObjN |
27020b57cec5SDimitry Andric   //    ----------------------------------
27030b57cec5SDimitry Andric   //    ^    ^      ^                   ^
27040b57cec5SDimitry Andric   //    A    B      C                   E
27050b57cec5SDimitry Andric   //
27060b57cec5SDimitry Andric   // A is the incoming stack pointer.
27070b57cec5SDimitry Andric   // (B - A) is the local area offset (-8 for x86-64) [1]
27080b57cec5SDimitry Andric   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
27090b57cec5SDimitry Andric   //
27100b57cec5SDimitry Andric   // |(E - B)| is the StackSize (absolute value, positive).  For a
27110b57cec5SDimitry Andric   // stack that grown down, this works out to be (B - E). [3]
27120b57cec5SDimitry Andric   //
27130b57cec5SDimitry Andric   // E is also the value of %rsp after stack has been set up, and we
27140b57cec5SDimitry Andric   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
27150b57cec5SDimitry Andric   // (C - E) == (C - A) - (B - A) + (B - E)
27160b57cec5SDimitry Andric   //            { Using [1], [2] and [3] above }
27170b57cec5SDimitry Andric   //         == getObjectOffset - LocalAreaOffset + StackSize
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
27200b57cec5SDimitry Andric }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric bool X86FrameLowering::assignCalleeSavedSpillSlots(
27230b57cec5SDimitry Andric     MachineFunction &MF, const TargetRegisterInfo *TRI,
27240b57cec5SDimitry Andric     std::vector<CalleeSavedInfo> &CSI) const {
27250b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
27260b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   unsigned CalleeSavedFrameSize = 0;
2729c14a5a88SDimitry Andric   unsigned XMMCalleeSavedFrameSize = 0;
2730c14a5a88SDimitry Andric   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
27310b57cec5SDimitry Andric   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0) {
27360b57cec5SDimitry Andric     // create RETURNADDR area
27370b57cec5SDimitry Andric     //   arg
27380b57cec5SDimitry Andric     //   arg
27390b57cec5SDimitry Andric     //   RETADDR
27400b57cec5SDimitry Andric     //   { ...
27410b57cec5SDimitry Andric     //     RETADDR area
27420b57cec5SDimitry Andric     //     ...
27430b57cec5SDimitry Andric     //   }
27440b57cec5SDimitry Andric     //   [EBP]
27450b57cec5SDimitry Andric     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
27460b57cec5SDimitry Andric                            TailCallReturnAddrDelta - SlotSize, true);
27470b57cec5SDimitry Andric   }
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
27500b57cec5SDimitry Andric   if (this->TRI->hasBasePointer(MF)) {
27510b57cec5SDimitry Andric     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
27520b57cec5SDimitry Andric     if (MF.hasEHFunclets()) {
27535ffd83dbSDimitry Andric       int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize));
27540b57cec5SDimitry Andric       X86FI->setHasSEHFramePtrSave(true);
27550b57cec5SDimitry Andric       X86FI->setSEHFramePtrSaveIndex(FI);
27560b57cec5SDimitry Andric     }
27570b57cec5SDimitry Andric   }
27580b57cec5SDimitry Andric 
27590b57cec5SDimitry Andric   if (hasFP(MF)) {
27600b57cec5SDimitry Andric     // emitPrologue always spills frame register the first thing.
27610b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
27620b57cec5SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
27630b57cec5SDimitry Andric 
2764fe6060f1SDimitry Andric     // The async context lives directly before the frame pointer, and we
2765fe6060f1SDimitry Andric     // allocate a second slot to preserve stack alignment.
2766fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2767fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2768fe6060f1SDimitry Andric       MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2769fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2770fe6060f1SDimitry Andric     }
2771fe6060f1SDimitry Andric 
27720b57cec5SDimitry Andric     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
27730b57cec5SDimitry Andric     // the frame register, we can delete it from CSI list and not have to worry
27740b57cec5SDimitry Andric     // about avoiding it later.
27758bcb0991SDimitry Andric     Register FPReg = TRI->getFrameRegister(MF);
27760b57cec5SDimitry Andric     for (unsigned i = 0; i < CSI.size(); ++i) {
27770b57cec5SDimitry Andric       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
27780b57cec5SDimitry Andric         CSI.erase(CSI.begin() + i);
27790b57cec5SDimitry Andric         break;
27800b57cec5SDimitry Andric       }
27810b57cec5SDimitry Andric     }
27820b57cec5SDimitry Andric   }
27830b57cec5SDimitry Andric 
27840b57cec5SDimitry Andric   // Assign slots for GPRs. It increases frame size.
27850eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
278604eeddc0SDimitry Andric     Register Reg = I.getReg();
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
27890b57cec5SDimitry Andric       continue;
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
27920b57cec5SDimitry Andric     CalleeSavedFrameSize += SlotSize;
27930b57cec5SDimitry Andric 
27940b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
27950eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
27960b57cec5SDimitry Andric   }
27970b57cec5SDimitry Andric 
2798*06c3fb27SDimitry Andric   // Adjust the offset of spill slot as we know the accurate callee saved frame
2799*06c3fb27SDimitry Andric   // size.
2800*06c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
2801*06c3fb27SDimitry Andric     SpillSlotOffset -= SlotSize;
2802*06c3fb27SDimitry Andric     CalleeSavedFrameSize += SlotSize;
2803*06c3fb27SDimitry Andric 
2804*06c3fb27SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2805*06c3fb27SDimitry Andric     // TODO: saving the slot index is better?
2806*06c3fb27SDimitry Andric     X86FI->setRestoreBasePointer(CalleeSavedFrameSize);
2807*06c3fb27SDimitry Andric   }
28080b57cec5SDimitry Andric   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
28090b57cec5SDimitry Andric   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric   // Assign slots for XMMs.
28120eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
281304eeddc0SDimitry Andric     Register Reg = I.getReg();
28140b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
28150b57cec5SDimitry Andric       continue;
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
28180b57cec5SDimitry Andric     MVT VT = MVT::Other;
28190b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
28200b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
28230b57cec5SDimitry Andric     unsigned Size = TRI->getSpillSize(*RC);
28245ffd83dbSDimitry Andric     Align Alignment = TRI->getSpillAlign(*RC);
28250b57cec5SDimitry Andric     // ensure alignment
2826c14a5a88SDimitry Andric     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
28275ffd83dbSDimitry Andric     SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
2828c14a5a88SDimitry Andric 
28290b57cec5SDimitry Andric     // spill into slot
28300b57cec5SDimitry Andric     SpillSlotOffset -= Size;
28310b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
28320eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
28335ffd83dbSDimitry Andric     MFI.ensureMaxAlignment(Alignment);
2834c14a5a88SDimitry Andric 
2835c14a5a88SDimitry Andric     // Save the start offset and size of XMM in stack frame for funclets.
2836c14a5a88SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
2837c14a5a88SDimitry Andric       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2838c14a5a88SDimitry Andric       XMMCalleeSavedFrameSize += Size;
2839c14a5a88SDimitry Andric     }
28400b57cec5SDimitry Andric   }
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   return true;
28430b57cec5SDimitry Andric }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric bool X86FrameLowering::spillCalleeSavedRegisters(
28460b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
28475ffd83dbSDimitry Andric     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
28480b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
28490b57cec5SDimitry Andric 
28500b57cec5SDimitry Andric   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
28510b57cec5SDimitry Andric   // for us, and there are no XMM CSRs on Win32.
28520b57cec5SDimitry Andric   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
28530b57cec5SDimitry Andric     return true;
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric   // Push GPRs. It increases frame size.
28560b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
28570b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
28580eae32dcSDimitry Andric   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
285904eeddc0SDimitry Andric     Register Reg = I.getReg();
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
28620b57cec5SDimitry Andric       continue;
28630b57cec5SDimitry Andric 
28640b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
28650b57cec5SDimitry Andric     bool isLiveIn = MRI.isLiveIn(Reg);
28660b57cec5SDimitry Andric     if (!isLiveIn)
28670b57cec5SDimitry Andric       MBB.addLiveIn(Reg);
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric     // Decide whether we can add a kill flag to the use.
28700b57cec5SDimitry Andric     bool CanKill = !isLiveIn;
28710b57cec5SDimitry Andric     // Check if any subregister is live-in
28720b57cec5SDimitry Andric     if (CanKill) {
28730b57cec5SDimitry Andric       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
28740b57cec5SDimitry Andric         if (MRI.isLiveIn(*AReg)) {
28750b57cec5SDimitry Andric           CanKill = false;
28760b57cec5SDimitry Andric           break;
28770b57cec5SDimitry Andric         }
28780b57cec5SDimitry Andric       }
28790b57cec5SDimitry Andric     }
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric     // Do not set a kill flag on values that are also marked as live-in. This
28820b57cec5SDimitry Andric     // happens with the @llvm-returnaddress intrinsic and with arguments
28830b57cec5SDimitry Andric     // passed in callee saved registers.
28840b57cec5SDimitry Andric     // Omitting the kill flags is conservatively correct even if the live-in
28850b57cec5SDimitry Andric     // is not used after all.
28860b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
28870b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
28880b57cec5SDimitry Andric   }
28890b57cec5SDimitry Andric 
2890*06c3fb27SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2891*06c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
2892*06c3fb27SDimitry Andric     unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
2893*06c3fb27SDimitry Andric     Register BaseReg = this->TRI->getBaseRegister();
2894*06c3fb27SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc))
2895*06c3fb27SDimitry Andric         .addReg(BaseReg, getKillRegState(true))
2896*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
2897*06c3fb27SDimitry Andric   }
2898*06c3fb27SDimitry Andric 
28990b57cec5SDimitry Andric   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
29000b57cec5SDimitry Andric   // It can be done by spilling XMMs to stack frame.
29010eae32dcSDimitry Andric   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
290204eeddc0SDimitry Andric     Register Reg = I.getReg();
29030b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
29040b57cec5SDimitry Andric       continue;
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
29070b57cec5SDimitry Andric     MVT VT = MVT::Other;
29080b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
29090b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric     // Add the callee-saved register as live-in. It's killed at the spill.
29120b57cec5SDimitry Andric     MBB.addLiveIn(Reg);
29130b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
29140b57cec5SDimitry Andric 
2915bdd1243dSDimitry Andric     TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, TRI,
2916bdd1243dSDimitry Andric                             Register());
29170b57cec5SDimitry Andric     --MI;
29180b57cec5SDimitry Andric     MI->setFlag(MachineInstr::FrameSetup);
29190b57cec5SDimitry Andric     ++MI;
29200b57cec5SDimitry Andric   }
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric   return true;
29230b57cec5SDimitry Andric }
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
29260b57cec5SDimitry Andric                                                MachineBasicBlock::iterator MBBI,
29270b57cec5SDimitry Andric                                                MachineInstr *CatchRet) const {
29280b57cec5SDimitry Andric   // SEH shouldn't use catchret.
29290b57cec5SDimitry Andric   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
29300b57cec5SDimitry Andric              MBB.getParent()->getFunction().getPersonalityFn())) &&
29310b57cec5SDimitry Andric          "SEH should not use CATCHRET");
2932fe6060f1SDimitry Andric   const DebugLoc &DL = CatchRet->getDebugLoc();
29330b57cec5SDimitry Andric   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric   // Fill EAX/RAX with the address of the target block.
29360b57cec5SDimitry Andric   if (STI.is64Bit()) {
29370b57cec5SDimitry Andric     // LEA64r CatchRetTarget(%rip), %rax
29380b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
29390b57cec5SDimitry Andric         .addReg(X86::RIP)
29400b57cec5SDimitry Andric         .addImm(0)
29410b57cec5SDimitry Andric         .addReg(0)
29420b57cec5SDimitry Andric         .addMBB(CatchRetTarget)
29430b57cec5SDimitry Andric         .addReg(0);
29440b57cec5SDimitry Andric   } else {
29450b57cec5SDimitry Andric     // MOV32ri $CatchRetTarget, %eax
29460b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
29470b57cec5SDimitry Andric         .addMBB(CatchRetTarget);
29480b57cec5SDimitry Andric   }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   // Record that we've taken the address of CatchRetTarget and no longer just
29510b57cec5SDimitry Andric   // reference it in a terminator.
2952bdd1243dSDimitry Andric   CatchRetTarget->setMachineBlockAddressTaken();
29530b57cec5SDimitry Andric }
29540b57cec5SDimitry Andric 
29555ffd83dbSDimitry Andric bool X86FrameLowering::restoreCalleeSavedRegisters(
29565ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
29575ffd83dbSDimitry Andric     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
29580b57cec5SDimitry Andric   if (CSI.empty())
29590b57cec5SDimitry Andric     return false;
29600b57cec5SDimitry Andric 
29610b57cec5SDimitry Andric   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
29620b57cec5SDimitry Andric     // Don't restore CSRs in 32-bit EH funclets. Matches
29630b57cec5SDimitry Andric     // spillCalleeSavedRegisters.
29640b57cec5SDimitry Andric     if (STI.is32Bit())
29650b57cec5SDimitry Andric       return true;
29660b57cec5SDimitry Andric     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
29670b57cec5SDimitry Andric     // funclets. emitEpilogue transforms these to normal jumps.
29680b57cec5SDimitry Andric     if (MI->getOpcode() == X86::CATCHRET) {
29690b57cec5SDimitry Andric       const Function &F = MBB.getParent()->getFunction();
29700b57cec5SDimitry Andric       bool IsSEH = isAsynchronousEHPersonality(
29710b57cec5SDimitry Andric           classifyEHPersonality(F.getPersonalityFn()));
29720b57cec5SDimitry Andric       if (IsSEH)
29730b57cec5SDimitry Andric         return true;
29740b57cec5SDimitry Andric     }
29750b57cec5SDimitry Andric   }
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   // Reload XMMs from stack frame.
29804824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
298104eeddc0SDimitry Andric     Register Reg = I.getReg();
29820b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) ||
29830b57cec5SDimitry Andric         X86::GR32RegClass.contains(Reg))
29840b57cec5SDimitry Andric       continue;
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
29870b57cec5SDimitry Andric     MVT VT = MVT::Other;
29880b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
29890b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2992bdd1243dSDimitry Andric     TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, TRI,
2993bdd1243dSDimitry Andric                              Register());
29940b57cec5SDimitry Andric   }
29950b57cec5SDimitry Andric 
2996*06c3fb27SDimitry Andric   // Clear the stack slot for spill base pointer register.
2997*06c3fb27SDimitry Andric   MachineFunction &MF = *MBB.getParent();
2998*06c3fb27SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2999*06c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
3000*06c3fb27SDimitry Andric     unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
3001*06c3fb27SDimitry Andric     Register BaseReg = this->TRI->getBaseRegister();
3002*06c3fb27SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc), BaseReg)
3003*06c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
3004*06c3fb27SDimitry Andric   }
3005*06c3fb27SDimitry Andric 
30060b57cec5SDimitry Andric   // POP GPRs.
30070b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
30084824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
300904eeddc0SDimitry Andric     Register Reg = I.getReg();
30100b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) &&
30110b57cec5SDimitry Andric         !X86::GR32RegClass.contains(Reg))
30120b57cec5SDimitry Andric       continue;
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
30150b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
30160b57cec5SDimitry Andric   }
30170b57cec5SDimitry Andric   return true;
30180b57cec5SDimitry Andric }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
30210b57cec5SDimitry Andric                                             BitVector &SavedRegs,
30220b57cec5SDimitry Andric                                             RegScavenger *RS) const {
30230b57cec5SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
30260b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)){
30278bcb0991SDimitry Andric     Register BasePtr = TRI->getBaseRegister();
30280b57cec5SDimitry Andric     if (STI.isTarget64BitILP32())
30290b57cec5SDimitry Andric       BasePtr = getX86SubSuperRegister(BasePtr, 64);
30300b57cec5SDimitry Andric     SavedRegs.set(BasePtr);
30310b57cec5SDimitry Andric   }
30320b57cec5SDimitry Andric }
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric static bool
30350b57cec5SDimitry Andric HasNestArgument(const MachineFunction *MF) {
30360b57cec5SDimitry Andric   const Function &F = MF->getFunction();
30370b57cec5SDimitry Andric   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
30380b57cec5SDimitry Andric        I != E; I++) {
30398bcb0991SDimitry Andric     if (I->hasNestAttr() && !I->use_empty())
30400b57cec5SDimitry Andric       return true;
30410b57cec5SDimitry Andric   }
30420b57cec5SDimitry Andric   return false;
30430b57cec5SDimitry Andric }
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric /// GetScratchRegister - Get a temp register for performing work in the
30460b57cec5SDimitry Andric /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
30470b57cec5SDimitry Andric /// and the properties of the function either one or two registers will be
30480b57cec5SDimitry Andric /// needed. Set primary to true for the first register, false for the second.
30490b57cec5SDimitry Andric static unsigned
30500b57cec5SDimitry Andric GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
30510b57cec5SDimitry Andric   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
30520b57cec5SDimitry Andric 
30530b57cec5SDimitry Andric   // Erlang stuff.
30540b57cec5SDimitry Andric   if (CallingConvention == CallingConv::HiPE) {
30550b57cec5SDimitry Andric     if (Is64Bit)
30560b57cec5SDimitry Andric       return Primary ? X86::R14 : X86::R13;
30570b57cec5SDimitry Andric     else
30580b57cec5SDimitry Andric       return Primary ? X86::EBX : X86::EDI;
30590b57cec5SDimitry Andric   }
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric   if (Is64Bit) {
30620b57cec5SDimitry Andric     if (IsLP64)
30630b57cec5SDimitry Andric       return Primary ? X86::R11 : X86::R12;
30640b57cec5SDimitry Andric     else
30650b57cec5SDimitry Andric       return Primary ? X86::R11D : X86::R12D;
30660b57cec5SDimitry Andric   }
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   bool IsNested = HasNestArgument(&MF);
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric   if (CallingConvention == CallingConv::X86_FastCall ||
30718bcb0991SDimitry Andric       CallingConvention == CallingConv::Fast ||
30728bcb0991SDimitry Andric       CallingConvention == CallingConv::Tail) {
30730b57cec5SDimitry Andric     if (IsNested)
30740b57cec5SDimitry Andric       report_fatal_error("Segmented stacks does not support fastcall with "
30750b57cec5SDimitry Andric                          "nested function.");
30760b57cec5SDimitry Andric     return Primary ? X86::EAX : X86::ECX;
30770b57cec5SDimitry Andric   }
30780b57cec5SDimitry Andric   if (IsNested)
30790b57cec5SDimitry Andric     return Primary ? X86::EDX : X86::EAX;
30800b57cec5SDimitry Andric   return Primary ? X86::ECX : X86::EAX;
30810b57cec5SDimitry Andric }
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual stack
30840b57cec5SDimitry Andric // limit.
30850b57cec5SDimitry Andric static const uint64_t kSplitStackAvailable = 256;
30860b57cec5SDimitry Andric 
30870b57cec5SDimitry Andric void X86FrameLowering::adjustForSegmentedStacks(
30880b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
30890b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
30900b57cec5SDimitry Andric   uint64_t StackSize;
30910b57cec5SDimitry Andric   unsigned TlsReg, TlsOffset;
30920b57cec5SDimitry Andric   DebugLoc DL;
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
30950b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
30960b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
30990b57cec5SDimitry Andric   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
31000b57cec5SDimitry Andric          "Scratch register is live-in");
31010b57cec5SDimitry Andric 
31020b57cec5SDimitry Andric   if (MF.getFunction().isVarArg())
31030b57cec5SDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
31040b57cec5SDimitry Andric   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
31050b57cec5SDimitry Andric       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
31060b57cec5SDimitry Andric       !STI.isTargetDragonFly())
31070b57cec5SDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric   // Eventually StackSize will be calculated by a link-time pass; which will
31100b57cec5SDimitry Andric   // also decide whether checking code needs to be injected into this particular
31110b57cec5SDimitry Andric   // prologue.
31120b57cec5SDimitry Andric   StackSize = MFI.getStackSize();
31130b57cec5SDimitry Andric 
311481ad6265SDimitry Andric   if (!MFI.needsSplitStackProlog())
31150b57cec5SDimitry Andric     return;
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
31180b57cec5SDimitry Andric   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
31190b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
31200b57cec5SDimitry Andric   bool IsNested = false;
31210b57cec5SDimitry Andric 
31220b57cec5SDimitry Andric   // We need to know if the function has a nest argument only in 64 bit mode.
31230b57cec5SDimitry Andric   if (Is64Bit)
31240b57cec5SDimitry Andric     IsNested = HasNestArgument(&MF);
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
31270b57cec5SDimitry Andric   // allocMBB needs to be last (terminating) instruction.
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
31300b57cec5SDimitry Andric     allocMBB->addLiveIn(LI);
31310b57cec5SDimitry Andric     checkMBB->addLiveIn(LI);
31320b57cec5SDimitry Andric   }
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric   if (IsNested)
31350b57cec5SDimitry Andric     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric   MF.push_front(allocMBB);
31380b57cec5SDimitry Andric   MF.push_front(checkMBB);
31390b57cec5SDimitry Andric 
31400b57cec5SDimitry Andric   // When the frame size is less than 256 we just compare the stack
31410b57cec5SDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
31420b57cec5SDimitry Andric   bool CompareStackPointer = StackSize < kSplitStackAvailable;
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric   // Read the limit off the current stacklet off the stack_guard location.
31450b57cec5SDimitry Andric   if (Is64Bit) {
31460b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
31470b57cec5SDimitry Andric       TlsReg = X86::FS;
31480b57cec5SDimitry Andric       TlsOffset = IsLP64 ? 0x70 : 0x40;
31490b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
31500b57cec5SDimitry Andric       TlsReg = X86::GS;
31510b57cec5SDimitry Andric       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
31520b57cec5SDimitry Andric     } else if (STI.isTargetWin64()) {
31530b57cec5SDimitry Andric       TlsReg = X86::GS;
31540b57cec5SDimitry Andric       TlsOffset = 0x28; // pvArbitrary, reserved for application use
31550b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
31560b57cec5SDimitry Andric       TlsReg = X86::FS;
31570b57cec5SDimitry Andric       TlsOffset = 0x18;
31580b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
31590b57cec5SDimitry Andric       TlsReg = X86::FS;
31600b57cec5SDimitry Andric       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
31610b57cec5SDimitry Andric     } else {
31620b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
31630b57cec5SDimitry Andric     }
31640b57cec5SDimitry Andric 
31650b57cec5SDimitry Andric     if (CompareStackPointer)
31660b57cec5SDimitry Andric       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
31670b57cec5SDimitry Andric     else
31680b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
31690b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
31720b57cec5SDimitry Andric       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
31730b57cec5SDimitry Andric   } else {
31740b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
31750b57cec5SDimitry Andric       TlsReg = X86::GS;
31760b57cec5SDimitry Andric       TlsOffset = 0x30;
31770b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
31780b57cec5SDimitry Andric       TlsReg = X86::GS;
31790b57cec5SDimitry Andric       TlsOffset = 0x48 + 90*4;
31800b57cec5SDimitry Andric     } else if (STI.isTargetWin32()) {
31810b57cec5SDimitry Andric       TlsReg = X86::FS;
31820b57cec5SDimitry Andric       TlsOffset = 0x14; // pvArbitrary, reserved for application use
31830b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
31840b57cec5SDimitry Andric       TlsReg = X86::FS;
31850b57cec5SDimitry Andric       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
31860b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
31870b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
31880b57cec5SDimitry Andric     } else {
31890b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
31900b57cec5SDimitry Andric     }
31910b57cec5SDimitry Andric 
31920b57cec5SDimitry Andric     if (CompareStackPointer)
31930b57cec5SDimitry Andric       ScratchReg = X86::ESP;
31940b57cec5SDimitry Andric     else
31950b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
31960b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
31990b57cec5SDimitry Andric         STI.isTargetDragonFly()) {
32000b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
32010b57cec5SDimitry Andric         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
32020b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
32050b57cec5SDimitry Andric       unsigned ScratchReg2;
32060b57cec5SDimitry Andric       bool SaveScratch2;
32070b57cec5SDimitry Andric       if (CompareStackPointer) {
32080b57cec5SDimitry Andric         // The primary scratch register is available for holding the TLS offset.
32090b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
32100b57cec5SDimitry Andric         SaveScratch2 = false;
32110b57cec5SDimitry Andric       } else {
32120b57cec5SDimitry Andric         // Need to use a second register to hold the TLS offset
32130b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
32140b57cec5SDimitry Andric 
32150b57cec5SDimitry Andric         // Unfortunately, with fastcc the second scratch register may hold an
32160b57cec5SDimitry Andric         // argument.
32170b57cec5SDimitry Andric         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
32180b57cec5SDimitry Andric       }
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric       // If Scratch2 is live-in then it needs to be saved.
32210b57cec5SDimitry Andric       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
32220b57cec5SDimitry Andric              "Scratch register is live-in and not saved");
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric       if (SaveScratch2)
32250b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
32260b57cec5SDimitry Andric           .addReg(ScratchReg2, RegState::Kill);
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
32290b57cec5SDimitry Andric         .addImm(TlsOffset);
32300b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
32310b57cec5SDimitry Andric         .addReg(ScratchReg)
32320b57cec5SDimitry Andric         .addReg(ScratchReg2).addImm(1).addReg(0)
32330b57cec5SDimitry Andric         .addImm(0)
32340b57cec5SDimitry Andric         .addReg(TlsReg);
32350b57cec5SDimitry Andric 
32360b57cec5SDimitry Andric       if (SaveScratch2)
32370b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
32380b57cec5SDimitry Andric     }
32390b57cec5SDimitry Andric   }
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
32420b57cec5SDimitry Andric   // It jumps to normal execution of the function body.
32430b57cec5SDimitry Andric   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric   // On 32 bit we first push the arguments size and then the frame size. On 64
32460b57cec5SDimitry Andric   // bit, we pass the stack frame size in r10 and the argument size in r11.
32470b57cec5SDimitry Andric   if (Is64Bit) {
32480b57cec5SDimitry Andric     // Functions with nested arguments use R10, so it needs to be saved across
32490b57cec5SDimitry Andric     // the call to _morestack
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
32520b57cec5SDimitry Andric     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
32530b57cec5SDimitry Andric     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
32540b57cec5SDimitry Andric     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric     if (IsNested)
32570b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
32580b57cec5SDimitry Andric 
325904eeddc0SDimitry Andric     BuildMI(allocMBB, DL, TII.get(getMOVriOpcode(IsLP64, StackSize)), Reg10)
32600b57cec5SDimitry Andric         .addImm(StackSize);
326104eeddc0SDimitry Andric     BuildMI(allocMBB, DL,
326204eeddc0SDimitry Andric             TII.get(getMOVriOpcode(IsLP64, X86FI->getArgumentStackSize())),
326304eeddc0SDimitry Andric             Reg11)
32640b57cec5SDimitry Andric         .addImm(X86FI->getArgumentStackSize());
32650b57cec5SDimitry Andric   } else {
3266*06c3fb27SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSH32i))
32670b57cec5SDimitry Andric       .addImm(X86FI->getArgumentStackSize());
3268*06c3fb27SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSH32i))
32690b57cec5SDimitry Andric       .addImm(StackSize);
32700b57cec5SDimitry Andric   }
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   // __morestack is in libgcc
32730b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
32740b57cec5SDimitry Andric     // Under the large code model, we cannot assume that __morestack lives
32750b57cec5SDimitry Andric     // within 2^31 bytes of the call site, so we cannot use pc-relative
32760b57cec5SDimitry Andric     // addressing. We cannot perform the call via a temporary register,
32770b57cec5SDimitry Andric     // as the rax register may be used to store the static chain, and all
32780b57cec5SDimitry Andric     // other suitable registers may be either callee-save or used for
32790b57cec5SDimitry Andric     // parameter passing. We cannot use the stack at this point either
32800b57cec5SDimitry Andric     // because __morestack manipulates the stack directly.
32810b57cec5SDimitry Andric     //
32820b57cec5SDimitry Andric     // To avoid these issues, perform an indirect call via a read-only memory
32830b57cec5SDimitry Andric     // location containing the address.
32840b57cec5SDimitry Andric     //
32850b57cec5SDimitry Andric     // This solution is not perfect, as it assumes that the .rodata section
32860b57cec5SDimitry Andric     // is laid out within 2^31 bytes of each function body, but this seems
32870b57cec5SDimitry Andric     // to be sufficient for JIT.
32880b57cec5SDimitry Andric     // FIXME: Add retpoline support and remove the error here..
32890946e70aSDimitry Andric     if (STI.useIndirectThunkCalls())
32900b57cec5SDimitry Andric       report_fatal_error("Emitting morestack calls on 64-bit with the large "
32910946e70aSDimitry Andric                          "code model and thunks not yet implemented.");
32920b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
32930b57cec5SDimitry Andric         .addReg(X86::RIP)
32940b57cec5SDimitry Andric         .addImm(0)
32950b57cec5SDimitry Andric         .addReg(0)
32960b57cec5SDimitry Andric         .addExternalSymbol("__morestack_addr")
32970b57cec5SDimitry Andric         .addReg(0);
32980b57cec5SDimitry Andric   } else {
32990b57cec5SDimitry Andric     if (Is64Bit)
33000b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
33010b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
33020b57cec5SDimitry Andric     else
33030b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
33040b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
33050b57cec5SDimitry Andric   }
33060b57cec5SDimitry Andric 
33070b57cec5SDimitry Andric   if (IsNested)
33080b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
33090b57cec5SDimitry Andric   else
33100b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
33110b57cec5SDimitry Andric 
33120b57cec5SDimitry Andric   allocMBB->addSuccessor(&PrologueMBB);
33130b57cec5SDimitry Andric 
33140b57cec5SDimitry Andric   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
33150b57cec5SDimitry Andric   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
33180b57cec5SDimitry Andric   MF.verify();
33190b57cec5SDimitry Andric #endif
33200b57cec5SDimitry Andric }
33210b57cec5SDimitry Andric 
33220b57cec5SDimitry Andric /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
33230b57cec5SDimitry Andric /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
33240b57cec5SDimitry Andric /// to fields it needs, through a named metadata node "hipe.literals" containing
33250b57cec5SDimitry Andric /// name-value pairs.
33260b57cec5SDimitry Andric static unsigned getHiPELiteral(
33270b57cec5SDimitry Andric     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
33280b57cec5SDimitry Andric   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
33290b57cec5SDimitry Andric     MDNode *Node = HiPELiteralsMD->getOperand(i);
33300b57cec5SDimitry Andric     if (Node->getNumOperands() != 2) continue;
33310b57cec5SDimitry Andric     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
33320b57cec5SDimitry Andric     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
33330b57cec5SDimitry Andric     if (!NodeName || !NodeVal) continue;
33340b57cec5SDimitry Andric     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
33350b57cec5SDimitry Andric     if (ValConst && NodeName->getString() == LiteralName) {
33360b57cec5SDimitry Andric       return ValConst->getZExtValue();
33370b57cec5SDimitry Andric     }
33380b57cec5SDimitry Andric   }
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric   report_fatal_error("HiPE literal " + LiteralName
33410b57cec5SDimitry Andric                      + " required but not provided");
33420b57cec5SDimitry Andric }
33430b57cec5SDimitry Andric 
33448bcb0991SDimitry Andric // Return true if there are no non-ehpad successors to MBB and there are no
33458bcb0991SDimitry Andric // non-meta instructions between MBBI and MBB.end().
33468bcb0991SDimitry Andric static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
33478bcb0991SDimitry Andric                                   MachineBasicBlock::const_iterator MBBI) {
3348e8d8bef9SDimitry Andric   return llvm::all_of(
3349e8d8bef9SDimitry Andric              MBB.successors(),
33508bcb0991SDimitry Andric              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
33518bcb0991SDimitry Andric          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
33528bcb0991SDimitry Andric            return MI.isMetaInstruction();
33538bcb0991SDimitry Andric          });
33548bcb0991SDimitry Andric }
33558bcb0991SDimitry Andric 
33560b57cec5SDimitry Andric /// Erlang programs may need a special prologue to handle the stack size they
33570b57cec5SDimitry Andric /// might need at runtime. That is because Erlang/OTP does not implement a C
33580b57cec5SDimitry Andric /// stack but uses a custom implementation of hybrid stack/heap architecture.
33590b57cec5SDimitry Andric /// (for more information see Eric Stenman's Ph.D. thesis:
33600b57cec5SDimitry Andric /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
33610b57cec5SDimitry Andric ///
33620b57cec5SDimitry Andric /// CheckStack:
33630b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
33640b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
33650b57cec5SDimitry Andric /// OldStart:
33660b57cec5SDimitry Andric ///       ...
33670b57cec5SDimitry Andric /// IncStack:
33680b57cec5SDimitry Andric ///       call inc_stack   # doubles the stack space
33690b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
33700b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
33710b57cec5SDimitry Andric void X86FrameLowering::adjustForHiPEPrologue(
33720b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
33730b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
33740b57cec5SDimitry Andric   DebugLoc DL;
33750b57cec5SDimitry Andric 
33760b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
33770b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
33780b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
33790b57cec5SDimitry Andric 
33800b57cec5SDimitry Andric   // HiPE-specific values
33810b57cec5SDimitry Andric   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
33820b57cec5SDimitry Andric     ->getNamedMetadata("hipe.literals");
33830b57cec5SDimitry Andric   if (!HiPELiteralsMD)
33840b57cec5SDimitry Andric     report_fatal_error(
33850b57cec5SDimitry Andric         "Can't generate HiPE prologue without runtime parameters");
33860b57cec5SDimitry Andric   const unsigned HipeLeafWords
33870b57cec5SDimitry Andric     = getHiPELiteral(HiPELiteralsMD,
33880b57cec5SDimitry Andric                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
33890b57cec5SDimitry Andric   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
33900b57cec5SDimitry Andric   const unsigned Guaranteed = HipeLeafWords * SlotSize;
33910b57cec5SDimitry Andric   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
33920b57cec5SDimitry Andric                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
33930b57cec5SDimitry Andric   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
33940b57cec5SDimitry Andric 
33950b57cec5SDimitry Andric   assert(STI.isTargetLinux() &&
33960b57cec5SDimitry Andric          "HiPE prologue is only supported on Linux operating systems.");
33970b57cec5SDimitry Andric 
33980b57cec5SDimitry Andric   // Compute the largest caller's frame that is needed to fit the callees'
33990b57cec5SDimitry Andric   // frames. This 'MaxStack' is computed from:
34000b57cec5SDimitry Andric   //
34010b57cec5SDimitry Andric   // a) the fixed frame size, which is the space needed for all spilled temps,
34020b57cec5SDimitry Andric   // b) outgoing on-stack parameter areas, and
34030b57cec5SDimitry Andric   // c) the minimum stack space this function needs to make available for the
34040b57cec5SDimitry Andric   //    functions it calls (a tunable ABI property).
34050b57cec5SDimitry Andric   if (MFI.hasCalls()) {
34060b57cec5SDimitry Andric     unsigned MoreStackForCalls = 0;
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric     for (auto &MBB : MF) {
34090b57cec5SDimitry Andric       for (auto &MI : MBB) {
34100b57cec5SDimitry Andric         if (!MI.isCall())
34110b57cec5SDimitry Andric           continue;
34120b57cec5SDimitry Andric 
34130b57cec5SDimitry Andric         // Get callee operand.
34140b57cec5SDimitry Andric         const MachineOperand &MO = MI.getOperand(0);
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric         // Only take account of global function calls (no closures etc.).
34170b57cec5SDimitry Andric         if (!MO.isGlobal())
34180b57cec5SDimitry Andric           continue;
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric         const Function *F = dyn_cast<Function>(MO.getGlobal());
34210b57cec5SDimitry Andric         if (!F)
34220b57cec5SDimitry Andric           continue;
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric         // Do not update 'MaxStack' for primitive and built-in functions
34250b57cec5SDimitry Andric         // (encoded with names either starting with "erlang."/"bif_" or not
34260b57cec5SDimitry Andric         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
34270b57cec5SDimitry Andric         // "_", such as the BIF "suspend_0") as they are executed on another
34280b57cec5SDimitry Andric         // stack.
3429349cc55cSDimitry Andric         if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
34300b57cec5SDimitry Andric             F->getName().find_first_of("._") == StringRef::npos)
34310b57cec5SDimitry Andric           continue;
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric         unsigned CalleeStkArity =
34340b57cec5SDimitry Andric           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
34350b57cec5SDimitry Andric         if (HipeLeafWords - 1 > CalleeStkArity)
34360b57cec5SDimitry Andric           MoreStackForCalls = std::max(MoreStackForCalls,
34370b57cec5SDimitry Andric                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
34380b57cec5SDimitry Andric       }
34390b57cec5SDimitry Andric     }
34400b57cec5SDimitry Andric     MaxStack += MoreStackForCalls;
34410b57cec5SDimitry Andric   }
34420b57cec5SDimitry Andric 
34430b57cec5SDimitry Andric   // If the stack frame needed is larger than the guaranteed then runtime checks
34440b57cec5SDimitry Andric   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
34450b57cec5SDimitry Andric   if (MaxStack > Guaranteed) {
34460b57cec5SDimitry Andric     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
34470b57cec5SDimitry Andric     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric     for (const auto &LI : PrologueMBB.liveins()) {
34500b57cec5SDimitry Andric       stackCheckMBB->addLiveIn(LI);
34510b57cec5SDimitry Andric       incStackMBB->addLiveIn(LI);
34520b57cec5SDimitry Andric     }
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric     MF.push_front(incStackMBB);
34550b57cec5SDimitry Andric     MF.push_front(stackCheckMBB);
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
34580b57cec5SDimitry Andric     unsigned LEAop, CMPop, CALLop;
34590b57cec5SDimitry Andric     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
34600b57cec5SDimitry Andric     if (Is64Bit) {
34610b57cec5SDimitry Andric       SPReg = X86::RSP;
34620b57cec5SDimitry Andric       PReg  = X86::RBP;
34630b57cec5SDimitry Andric       LEAop = X86::LEA64r;
34640b57cec5SDimitry Andric       CMPop = X86::CMP64rm;
34650b57cec5SDimitry Andric       CALLop = X86::CALL64pcrel32;
34660b57cec5SDimitry Andric     } else {
34670b57cec5SDimitry Andric       SPReg = X86::ESP;
34680b57cec5SDimitry Andric       PReg  = X86::EBP;
34690b57cec5SDimitry Andric       LEAop = X86::LEA32r;
34700b57cec5SDimitry Andric       CMPop = X86::CMP32rm;
34710b57cec5SDimitry Andric       CALLop = X86::CALLpcrel32;
34720b57cec5SDimitry Andric     }
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
34750b57cec5SDimitry Andric     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
34760b57cec5SDimitry Andric            "HiPE prologue scratch register is live-in");
34770b57cec5SDimitry Andric 
34780b57cec5SDimitry Andric     // Create new MBB for StackCheck:
34790b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
34800b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
34810b57cec5SDimitry Andric     // SPLimitOffset is in a fixed heap location (pointed by BP).
34820b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
34830b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
34840b57cec5SDimitry Andric     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric     // Create new MBB for IncStack:
34870b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(CALLop)).
34880b57cec5SDimitry Andric       addExternalSymbol("inc_stack_0");
34890b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
34900b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
34910b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
34920b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
34930b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
34960b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
34970b57cec5SDimitry Andric     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
34980b57cec5SDimitry Andric     incStackMBB->addSuccessor(incStackMBB, {1, 100});
34990b57cec5SDimitry Andric   }
35000b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
35010b57cec5SDimitry Andric   MF.verify();
35020b57cec5SDimitry Andric #endif
35030b57cec5SDimitry Andric }
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
35060b57cec5SDimitry Andric                                            MachineBasicBlock::iterator MBBI,
35070b57cec5SDimitry Andric                                            const DebugLoc &DL,
35080b57cec5SDimitry Andric                                            int Offset) const {
35090b57cec5SDimitry Andric   if (Offset <= 0)
35100b57cec5SDimitry Andric     return false;
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric   if (Offset % SlotSize)
35130b57cec5SDimitry Andric     return false;
35140b57cec5SDimitry Andric 
35150b57cec5SDimitry Andric   int NumPops = Offset / SlotSize;
35160b57cec5SDimitry Andric   // This is only worth it if we have at most 2 pops.
35170b57cec5SDimitry Andric   if (NumPops != 1 && NumPops != 2)
35180b57cec5SDimitry Andric     return false;
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric   // Handle only the trivial case where the adjustment directly follows
35210b57cec5SDimitry Andric   // a call. This is the most common one, anyway.
35220b57cec5SDimitry Andric   if (MBBI == MBB.begin())
35230b57cec5SDimitry Andric     return false;
35240b57cec5SDimitry Andric   MachineBasicBlock::iterator Prev = std::prev(MBBI);
35250b57cec5SDimitry Andric   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
35260b57cec5SDimitry Andric     return false;
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric   unsigned Regs[2];
35290b57cec5SDimitry Andric   unsigned FoundRegs = 0;
35300b57cec5SDimitry Andric 
3531e8d8bef9SDimitry Andric   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3532e8d8bef9SDimitry Andric   const MachineOperand &RegMask = Prev->getOperand(1);
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric   auto &RegClass =
35350b57cec5SDimitry Andric       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
35360b57cec5SDimitry Andric   // Try to find up to NumPops free registers.
35370b57cec5SDimitry Andric   for (auto Candidate : RegClass) {
35380b57cec5SDimitry Andric     // Poor man's liveness:
35390b57cec5SDimitry Andric     // Since we're immediately after a call, any register that is clobbered
35400b57cec5SDimitry Andric     // by the call and not defined by it can be considered dead.
35410b57cec5SDimitry Andric     if (!RegMask.clobbersPhysReg(Candidate))
35420b57cec5SDimitry Andric       continue;
35430b57cec5SDimitry Andric 
35440b57cec5SDimitry Andric     // Don't clobber reserved registers
35450b57cec5SDimitry Andric     if (MRI.isReserved(Candidate))
35460b57cec5SDimitry Andric       continue;
35470b57cec5SDimitry Andric 
35480b57cec5SDimitry Andric     bool IsDef = false;
35490b57cec5SDimitry Andric     for (const MachineOperand &MO : Prev->implicit_operands()) {
35500b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() &&
35510b57cec5SDimitry Andric           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
35520b57cec5SDimitry Andric         IsDef = true;
35530b57cec5SDimitry Andric         break;
35540b57cec5SDimitry Andric       }
35550b57cec5SDimitry Andric     }
35560b57cec5SDimitry Andric 
35570b57cec5SDimitry Andric     if (IsDef)
35580b57cec5SDimitry Andric       continue;
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric     Regs[FoundRegs++] = Candidate;
35610b57cec5SDimitry Andric     if (FoundRegs == (unsigned)NumPops)
35620b57cec5SDimitry Andric       break;
35630b57cec5SDimitry Andric   }
35640b57cec5SDimitry Andric 
35650b57cec5SDimitry Andric   if (FoundRegs == 0)
35660b57cec5SDimitry Andric     return false;
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric   // If we found only one free register, but need two, reuse the same one twice.
35690b57cec5SDimitry Andric   while (FoundRegs < (unsigned)NumPops)
35700b57cec5SDimitry Andric     Regs[FoundRegs++] = Regs[0];
35710b57cec5SDimitry Andric 
35720b57cec5SDimitry Andric   for (int i = 0; i < NumPops; ++i)
35730b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL,
35740b57cec5SDimitry Andric             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
35750b57cec5SDimitry Andric 
35760b57cec5SDimitry Andric   return true;
35770b57cec5SDimitry Andric }
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::
35800b57cec5SDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
35810b57cec5SDimitry Andric                               MachineBasicBlock::iterator I) const {
35820b57cec5SDimitry Andric   bool reserveCallFrame = hasReservedCallFrame(MF);
35830b57cec5SDimitry Andric   unsigned Opcode = I->getOpcode();
35840b57cec5SDimitry Andric   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
3585fe6060f1SDimitry Andric   DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
35868bcb0991SDimitry Andric   uint64_t Amount = TII.getFrameSize(*I);
35870b57cec5SDimitry Andric   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
35880b57cec5SDimitry Andric   I = MBB.erase(I);
35890b57cec5SDimitry Andric   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
35900b57cec5SDimitry Andric 
35915ffd83dbSDimitry Andric   // Try to avoid emitting dead SP adjustments if the block end is unreachable,
35925ffd83dbSDimitry Andric   // typically because the function is marked noreturn (abort, throw,
35935ffd83dbSDimitry Andric   // assert_fail, etc).
35945ffd83dbSDimitry Andric   if (isDestroy && blockEndIsUnreachable(MBB, I))
35955ffd83dbSDimitry Andric     return I;
35965ffd83dbSDimitry Andric 
35970b57cec5SDimitry Andric   if (!reserveCallFrame) {
35980b57cec5SDimitry Andric     // If the stack pointer can be changed after prologue, turn the
35990b57cec5SDimitry Andric     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
36000b57cec5SDimitry Andric     // adjcallstackdown instruction into 'add ESP, <amt>'
36010b57cec5SDimitry Andric 
36020b57cec5SDimitry Andric     // We need to keep the stack aligned properly.  To do this, we round the
36030b57cec5SDimitry Andric     // amount of space needed for the outgoing arguments up to the next
36040b57cec5SDimitry Andric     // alignment boundary.
36055ffd83dbSDimitry Andric     Amount = alignTo(Amount, getStackAlign());
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric     const Function &F = MF.getFunction();
36080b57cec5SDimitry Andric     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
3609480093f4SDimitry Andric     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric     // If we have any exception handlers in this function, and we adjust
36120b57cec5SDimitry Andric     // the SP before calls, we may need to indicate this to the unwinder
36130b57cec5SDimitry Andric     // using GNU_ARGS_SIZE. Note that this may be necessary even when
36140b57cec5SDimitry Andric     // Amount == 0, because the preceding function may have set a non-0
36150b57cec5SDimitry Andric     // GNU_ARGS_SIZE.
36160b57cec5SDimitry Andric     // TODO: We don't need to reset this between subsequent functions,
36170b57cec5SDimitry Andric     // if it didn't change.
36180b57cec5SDimitry Andric     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
36190b57cec5SDimitry Andric 
36200b57cec5SDimitry Andric     if (HasDwarfEHHandlers && !isDestroy &&
36210b57cec5SDimitry Andric         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
36220b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
36230b57cec5SDimitry Andric                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric     if (Amount == 0)
36260b57cec5SDimitry Andric       return I;
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric     // Factor out the amount that gets handled inside the sequence
36290b57cec5SDimitry Andric     // (Pushes of argument for frame setup, callee pops for frame destroy)
36300b57cec5SDimitry Andric     Amount -= InternalAmt;
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric     // TODO: This is needed only if we require precise CFA.
36330b57cec5SDimitry Andric     // If this is a callee-pop calling convention, emit a CFA adjust for
36340b57cec5SDimitry Andric     // the amount the callee popped.
36350b57cec5SDimitry Andric     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
36360b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
36370b57cec5SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
36380b57cec5SDimitry Andric 
36390b57cec5SDimitry Andric     // Add Amount to SP to destroy a frame, or subtract to setup.
36400b57cec5SDimitry Andric     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
36410b57cec5SDimitry Andric 
36420b57cec5SDimitry Andric     if (StackAdjustment) {
36430b57cec5SDimitry Andric       // Merge with any previous or following adjustment instruction. Note: the
36440b57cec5SDimitry Andric       // instructions merged with here do not have CFI, so their stack
36450b57cec5SDimitry Andric       // adjustments do not feed into CfaAdjustment.
36460b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
36470b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
36480b57cec5SDimitry Andric 
36490b57cec5SDimitry Andric       if (StackAdjustment) {
36500b57cec5SDimitry Andric         if (!(F.hasMinSize() &&
36510b57cec5SDimitry Andric               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
36520b57cec5SDimitry Andric           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
36530b57cec5SDimitry Andric                                /*InEpilogue=*/false);
36540b57cec5SDimitry Andric       }
36550b57cec5SDimitry Andric     }
36560b57cec5SDimitry Andric 
36570b57cec5SDimitry Andric     if (DwarfCFI && !hasFP(MF)) {
36580b57cec5SDimitry Andric       // If we don't have FP, but need to generate unwind information,
36590b57cec5SDimitry Andric       // we need to set the correct CFA offset after the stack adjustment.
36600b57cec5SDimitry Andric       // How much we adjust the CFA offset depends on whether we're emitting
36610b57cec5SDimitry Andric       // CFI only for EH purposes or for debugging. EH only requires the CFA
36620b57cec5SDimitry Andric       // offset to be correct at each call site, while for debugging we want
36630b57cec5SDimitry Andric       // it to be more precise.
36640b57cec5SDimitry Andric 
36650b57cec5SDimitry Andric       int64_t CfaAdjustment = -StackAdjustment;
36660b57cec5SDimitry Andric       // TODO: When not using precise CFA, we also need to adjust for the
36670b57cec5SDimitry Andric       // InternalAmt here.
36680b57cec5SDimitry Andric       if (CfaAdjustment) {
36690b57cec5SDimitry Andric         BuildCFI(MBB, InsertPos, DL,
36700b57cec5SDimitry Andric                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
36710b57cec5SDimitry Andric                                                          CfaAdjustment));
36720b57cec5SDimitry Andric       }
36730b57cec5SDimitry Andric     }
36740b57cec5SDimitry Andric 
36750b57cec5SDimitry Andric     return I;
36760b57cec5SDimitry Andric   }
36770b57cec5SDimitry Andric 
36785ffd83dbSDimitry Andric   if (InternalAmt) {
36790b57cec5SDimitry Andric     MachineBasicBlock::iterator CI = I;
36800b57cec5SDimitry Andric     MachineBasicBlock::iterator B = MBB.begin();
36810b57cec5SDimitry Andric     while (CI != B && !std::prev(CI)->isCall())
36820b57cec5SDimitry Andric       --CI;
36830b57cec5SDimitry Andric     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
36840b57cec5SDimitry Andric   }
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric   return I;
36870b57cec5SDimitry Andric }
36880b57cec5SDimitry Andric 
36890b57cec5SDimitry Andric bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
36900b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
36910b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3692fe6060f1SDimitry Andric   if (!MBB.isLiveIn(X86::EFLAGS))
3693fe6060f1SDimitry Andric     return true;
3694fe6060f1SDimitry Andric 
3695bdd1243dSDimitry Andric   // If stack probes have to loop inline or call, that will clobber EFLAGS.
3696bdd1243dSDimitry Andric   // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
3697bdd1243dSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
3698bdd1243dSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
3699bdd1243dSDimitry Andric   if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
3700bdd1243dSDimitry Andric     return false;
3701bdd1243dSDimitry Andric 
3702fe6060f1SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3703fe6060f1SDimitry Andric   return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
37040b57cec5SDimitry Andric }
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
37070b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
37080b57cec5SDimitry Andric 
37090b57cec5SDimitry Andric   // Win64 has strict requirements in terms of epilogue and we are
37100b57cec5SDimitry Andric   // not taking a chance at messing with them.
37110b57cec5SDimitry Andric   // I.e., unless this block is already an exit block, we can't use
37120b57cec5SDimitry Andric   // it as an epilogue.
37130b57cec5SDimitry Andric   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
37140b57cec5SDimitry Andric     return false;
37150b57cec5SDimitry Andric 
3716fe6060f1SDimitry Andric   // Swift async context epilogue has a BTR instruction that clobbers parts of
3717fe6060f1SDimitry Andric   // EFLAGS.
3718fe6060f1SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3719fe6060f1SDimitry Andric   if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext())
3720fe6060f1SDimitry Andric     return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
3721fe6060f1SDimitry Andric 
37220b57cec5SDimitry Andric   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
37230b57cec5SDimitry Andric     return true;
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric   // If we cannot use LEA to adjust SP, we may need to use ADD, which
37260b57cec5SDimitry Andric   // clobbers the EFLAGS. Check that we do not need to preserve it,
37270b57cec5SDimitry Andric   // otherwise, conservatively assume this is not
37280b57cec5SDimitry Andric   // safe to insert the epilogue here.
37290b57cec5SDimitry Andric   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
37300b57cec5SDimitry Andric }
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
37330b57cec5SDimitry Andric   // If we may need to emit frameless compact unwind information, give
37340b57cec5SDimitry Andric   // up as this is currently broken: PR25614.
3735e8d8bef9SDimitry Andric   bool CompactUnwind =
3736e8d8bef9SDimitry Andric       MF.getMMI().getContext().getObjectFileInfo()->getCompactUnwindSection() !=
3737e8d8bef9SDimitry Andric       nullptr;
3738e8d8bef9SDimitry Andric   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
3739e8d8bef9SDimitry Andric           !CompactUnwind) &&
3740e8d8bef9SDimitry Andric          // The lowering of segmented stack and HiPE only support entry
3741e8d8bef9SDimitry Andric          // blocks as prologue blocks: PR26107. This limitation may be
3742e8d8bef9SDimitry Andric          // lifted if we fix:
37430b57cec5SDimitry Andric          // - adjustForSegmentedStacks
37440b57cec5SDimitry Andric          // - adjustForHiPEPrologue
37450b57cec5SDimitry Andric          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
37460b57cec5SDimitry Andric          !MF.shouldSplitStack();
37470b57cec5SDimitry Andric }
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
37500b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
37510b57cec5SDimitry Andric     const DebugLoc &DL, bool RestoreSP) const {
37520b57cec5SDimitry Andric   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
37530b57cec5SDimitry Andric   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
37540b57cec5SDimitry Andric   assert(STI.is32Bit() && !Uses64BitFramePtr &&
37550b57cec5SDimitry Andric          "restoring EBP/ESI on non-32-bit target");
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
37588bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
37598bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
37600b57cec5SDimitry Andric   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
37610b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
37620b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric   // FIXME: Don't set FrameSetup flag in catchret case.
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
37670b57cec5SDimitry Andric   int EHRegSize = MFI.getObjectSize(FI);
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric   if (RestoreSP) {
37700b57cec5SDimitry Andric     // MOV32rm -EHRegSize(%ebp), %esp
37710b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
37720b57cec5SDimitry Andric                  X86::EBP, true, -EHRegSize)
37730b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
37740b57cec5SDimitry Andric   }
37750b57cec5SDimitry Andric 
37765ffd83dbSDimitry Andric   Register UsedReg;
3777e8d8bef9SDimitry Andric   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
37780b57cec5SDimitry Andric   int EndOffset = -EHRegOffset - EHRegSize;
37790b57cec5SDimitry Andric   FuncInfo.EHRegNodeEndOffset = EndOffset;
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric   if (UsedReg == FramePtr) {
37820b57cec5SDimitry Andric     // ADD $offset, %ebp
3783*06c3fb27SDimitry Andric     unsigned ADDri = getADDriOpcode(false);
37840b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
37850b57cec5SDimitry Andric         .addReg(FramePtr)
37860b57cec5SDimitry Andric         .addImm(EndOffset)
37870b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup)
37880b57cec5SDimitry Andric         ->getOperand(3)
37890b57cec5SDimitry Andric         .setIsDead();
37900b57cec5SDimitry Andric     assert(EndOffset >= 0 &&
37910b57cec5SDimitry Andric            "end of registration object above normal EBP position!");
37920b57cec5SDimitry Andric   } else if (UsedReg == BasePtr) {
37930b57cec5SDimitry Andric     // LEA offset(%ebp), %esi
37940b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
37950b57cec5SDimitry Andric                  FramePtr, false, EndOffset)
37960b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
37970b57cec5SDimitry Andric     // MOV32rm SavedEBPOffset(%esi), %ebp
37980b57cec5SDimitry Andric     assert(X86FI->getHasSEHFramePtrSave());
37990b57cec5SDimitry Andric     int Offset =
3800e8d8bef9SDimitry Andric         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
3801e8d8bef9SDimitry Andric             .getFixed();
38020b57cec5SDimitry Andric     assert(UsedReg == BasePtr);
38030b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
38040b57cec5SDimitry Andric                  UsedReg, true, Offset)
38050b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
38060b57cec5SDimitry Andric   } else {
38070b57cec5SDimitry Andric     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
38080b57cec5SDimitry Andric   }
38090b57cec5SDimitry Andric   return MBBI;
38100b57cec5SDimitry Andric }
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
38130b57cec5SDimitry Andric   return TRI->getSlotSize();
38140b57cec5SDimitry Andric }
38150b57cec5SDimitry Andric 
38165ffd83dbSDimitry Andric Register
38175ffd83dbSDimitry Andric X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const {
3818*06c3fb27SDimitry Andric   return StackPtr;
3819*06c3fb27SDimitry Andric }
3820*06c3fb27SDimitry Andric 
3821*06c3fb27SDimitry Andric TargetFrameLowering::DwarfFrameBase
3822*06c3fb27SDimitry Andric X86FrameLowering::getDwarfFrameBase(const MachineFunction &MF) const {
3823*06c3fb27SDimitry Andric   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
3824*06c3fb27SDimitry Andric   Register FrameRegister = RI->getFrameRegister(MF);
3825*06c3fb27SDimitry Andric   if (getInitialCFARegister(MF) == FrameRegister &&
3826*06c3fb27SDimitry Andric       MF.getInfo<X86MachineFunctionInfo>()->hasCFIAdjustCfa()) {
3827*06c3fb27SDimitry Andric     DwarfFrameBase FrameBase;
3828*06c3fb27SDimitry Andric     FrameBase.Kind = DwarfFrameBase::CFA;
3829*06c3fb27SDimitry Andric     FrameBase.Location.Offset =
3830*06c3fb27SDimitry Andric         -MF.getFrameInfo().getStackSize() - getInitialCFAOffset(MF);
3831*06c3fb27SDimitry Andric     return FrameBase;
3832*06c3fb27SDimitry Andric   }
3833*06c3fb27SDimitry Andric 
3834*06c3fb27SDimitry Andric   return DwarfFrameBase{DwarfFrameBase::Register, {FrameRegister}};
38350b57cec5SDimitry Andric }
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric namespace {
38380b57cec5SDimitry Andric // Struct used by orderFrameObjects to help sort the stack objects.
38390b57cec5SDimitry Andric struct X86FrameSortingObject {
38400b57cec5SDimitry Andric   bool IsValid = false;         // true if we care about this Object.
38410b57cec5SDimitry Andric   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
38420b57cec5SDimitry Andric   unsigned ObjectSize = 0;      // Size of Object in bytes.
38435ffd83dbSDimitry Andric   Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
38440b57cec5SDimitry Andric   unsigned ObjectNumUses = 0;   // Object static number of uses.
38450b57cec5SDimitry Andric };
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric // The comparison function we use for std::sort to order our local
38480b57cec5SDimitry Andric // stack symbols. The current algorithm is to use an estimated
38490b57cec5SDimitry Andric // "density". This takes into consideration the size and number of
38500b57cec5SDimitry Andric // uses each object has in order to roughly minimize code size.
38510b57cec5SDimitry Andric // So, for example, an object of size 16B that is referenced 5 times
38520b57cec5SDimitry Andric // will get higher priority than 4 4B objects referenced 1 time each.
38530b57cec5SDimitry Andric // It's not perfect and we may be able to squeeze a few more bytes out of
38540b57cec5SDimitry Andric // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
38550b57cec5SDimitry Andric // fringe end can have special consideration, given their size is less
38560b57cec5SDimitry Andric // important, etc.), but the algorithmic complexity grows too much to be
38570b57cec5SDimitry Andric // worth the extra gains we get. This gets us pretty close.
38580b57cec5SDimitry Andric // The final order leaves us with objects with highest priority going
38590b57cec5SDimitry Andric // at the end of our list.
38600b57cec5SDimitry Andric struct X86FrameSortingComparator {
38610b57cec5SDimitry Andric   inline bool operator()(const X86FrameSortingObject &A,
3862e8d8bef9SDimitry Andric                          const X86FrameSortingObject &B) const {
38630b57cec5SDimitry Andric     uint64_t DensityAScaled, DensityBScaled;
38640b57cec5SDimitry Andric 
38650b57cec5SDimitry Andric     // For consistency in our comparison, all invalid objects are placed
38660b57cec5SDimitry Andric     // at the end. This also allows us to stop walking when we hit the
38670b57cec5SDimitry Andric     // first invalid item after it's all sorted.
38680b57cec5SDimitry Andric     if (!A.IsValid)
38690b57cec5SDimitry Andric       return false;
38700b57cec5SDimitry Andric     if (!B.IsValid)
38710b57cec5SDimitry Andric       return true;
38720b57cec5SDimitry Andric 
38730b57cec5SDimitry Andric     // The density is calculated by doing :
38740b57cec5SDimitry Andric     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
38750b57cec5SDimitry Andric     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
38760b57cec5SDimitry Andric     // Since this approach may cause inconsistencies in
38770b57cec5SDimitry Andric     // the floating point <, >, == comparisons, depending on the floating
38780b57cec5SDimitry Andric     // point model with which the compiler was built, we're going
38790b57cec5SDimitry Andric     // to scale both sides by multiplying with
38800b57cec5SDimitry Andric     // A.ObjectSize * B.ObjectSize. This ends up factoring away
38810b57cec5SDimitry Andric     // the division and, with it, the need for any floating point
38820b57cec5SDimitry Andric     // arithmetic.
38830b57cec5SDimitry Andric     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
38840b57cec5SDimitry Andric       static_cast<uint64_t>(B.ObjectSize);
38850b57cec5SDimitry Andric     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
38860b57cec5SDimitry Andric       static_cast<uint64_t>(A.ObjectSize);
38870b57cec5SDimitry Andric 
38880b57cec5SDimitry Andric     // If the two densities are equal, prioritize highest alignment
38890b57cec5SDimitry Andric     // objects. This allows for similar alignment objects
38900b57cec5SDimitry Andric     // to be packed together (given the same density).
38910b57cec5SDimitry Andric     // There's room for improvement here, also, since we can pack
38920b57cec5SDimitry Andric     // similar alignment (different density) objects next to each
38930b57cec5SDimitry Andric     // other to save padding. This will also require further
38940b57cec5SDimitry Andric     // complexity/iterations, and the overall gain isn't worth it,
38950b57cec5SDimitry Andric     // in general. Something to keep in mind, though.
38960b57cec5SDimitry Andric     if (DensityAScaled == DensityBScaled)
38970b57cec5SDimitry Andric       return A.ObjectAlignment < B.ObjectAlignment;
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric     return DensityAScaled < DensityBScaled;
39000b57cec5SDimitry Andric   }
39010b57cec5SDimitry Andric };
39020b57cec5SDimitry Andric } // namespace
39030b57cec5SDimitry Andric 
39040b57cec5SDimitry Andric // Order the symbols in the local stack.
39050b57cec5SDimitry Andric // We want to place the local stack objects in some sort of sensible order.
39060b57cec5SDimitry Andric // The heuristic we use is to try and pack them according to static number
39070b57cec5SDimitry Andric // of uses and size of object in order to minimize code size.
39080b57cec5SDimitry Andric void X86FrameLowering::orderFrameObjects(
39090b57cec5SDimitry Andric     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
39100b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
39110b57cec5SDimitry Andric 
39120b57cec5SDimitry Andric   // Don't waste time if there's nothing to do.
39130b57cec5SDimitry Andric   if (ObjectsToAllocate.empty())
39140b57cec5SDimitry Andric     return;
39150b57cec5SDimitry Andric 
39160b57cec5SDimitry Andric   // Create an array of all MFI objects. We won't need all of these
39170b57cec5SDimitry Andric   // objects, but we're going to create a full array of them to make
39180b57cec5SDimitry Andric   // it easier to index into when we're counting "uses" down below.
39190b57cec5SDimitry Andric   // We want to be able to easily/cheaply access an object by simply
39200b57cec5SDimitry Andric   // indexing into it, instead of having to search for it every time.
39210b57cec5SDimitry Andric   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
39220b57cec5SDimitry Andric 
39230b57cec5SDimitry Andric   // Walk the objects we care about and mark them as such in our working
39240b57cec5SDimitry Andric   // struct.
39250b57cec5SDimitry Andric   for (auto &Obj : ObjectsToAllocate) {
39260b57cec5SDimitry Andric     SortingObjects[Obj].IsValid = true;
39270b57cec5SDimitry Andric     SortingObjects[Obj].ObjectIndex = Obj;
39285ffd83dbSDimitry Andric     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
39290b57cec5SDimitry Andric     // Set the size.
39300b57cec5SDimitry Andric     int ObjectSize = MFI.getObjectSize(Obj);
39310b57cec5SDimitry Andric     if (ObjectSize == 0)
39320b57cec5SDimitry Andric       // Variable size. Just use 4.
39330b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = 4;
39340b57cec5SDimitry Andric     else
39350b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = ObjectSize;
39360b57cec5SDimitry Andric   }
39370b57cec5SDimitry Andric 
39380b57cec5SDimitry Andric   // Count the number of uses for each object.
39390b57cec5SDimitry Andric   for (auto &MBB : MF) {
39400b57cec5SDimitry Andric     for (auto &MI : MBB) {
39410b57cec5SDimitry Andric       if (MI.isDebugInstr())
39420b57cec5SDimitry Andric         continue;
39430b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
39440b57cec5SDimitry Andric         // Check to see if it's a local stack symbol.
39450b57cec5SDimitry Andric         if (!MO.isFI())
39460b57cec5SDimitry Andric           continue;
39470b57cec5SDimitry Andric         int Index = MO.getIndex();
39480b57cec5SDimitry Andric         // Check to see if it falls within our range, and is tagged
39490b57cec5SDimitry Andric         // to require ordering.
39500b57cec5SDimitry Andric         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
39510b57cec5SDimitry Andric             SortingObjects[Index].IsValid)
39520b57cec5SDimitry Andric           SortingObjects[Index].ObjectNumUses++;
39530b57cec5SDimitry Andric       }
39540b57cec5SDimitry Andric     }
39550b57cec5SDimitry Andric   }
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
39580b57cec5SDimitry Andric   // info).
39590b57cec5SDimitry Andric   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   // Now modify the original list to represent the final order that
39620b57cec5SDimitry Andric   // we want. The order will depend on whether we're going to access them
39630b57cec5SDimitry Andric   // from the stack pointer or the frame pointer. For SP, the list should
39640b57cec5SDimitry Andric   // end up with the END containing objects that we want with smaller offsets.
39650b57cec5SDimitry Andric   // For FP, it should be flipped.
39660b57cec5SDimitry Andric   int i = 0;
39670b57cec5SDimitry Andric   for (auto &Obj : SortingObjects) {
39680b57cec5SDimitry Andric     // All invalid items are sorted at the end, so it's safe to stop.
39690b57cec5SDimitry Andric     if (!Obj.IsValid)
39700b57cec5SDimitry Andric       break;
39710b57cec5SDimitry Andric     ObjectsToAllocate[i++] = Obj.ObjectIndex;
39720b57cec5SDimitry Andric   }
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   // Flip it if we're accessing off of the FP.
3975fe6060f1SDimitry Andric   if (!TRI->hasStackRealignment(MF) && hasFP(MF))
39760b57cec5SDimitry Andric     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
39770b57cec5SDimitry Andric }
39780b57cec5SDimitry Andric 
39790b57cec5SDimitry Andric 
39800b57cec5SDimitry Andric unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
39810b57cec5SDimitry Andric   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
39820b57cec5SDimitry Andric   unsigned Offset = 16;
39830b57cec5SDimitry Andric   // RBP is immediately pushed.
39840b57cec5SDimitry Andric   Offset += SlotSize;
39850b57cec5SDimitry Andric   // All callee-saved registers are then pushed.
39860b57cec5SDimitry Andric   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
39870b57cec5SDimitry Andric   // Every funclet allocates enough stack space for the largest outgoing call.
39880b57cec5SDimitry Andric   Offset += getWinEHFuncletFrameSize(MF);
39890b57cec5SDimitry Andric   return Offset;
39900b57cec5SDimitry Andric }
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric void X86FrameLowering::processFunctionBeforeFrameFinalized(
39930b57cec5SDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
39940b57cec5SDimitry Andric   // Mark the function as not having WinCFI. We will set it back to true in
39950b57cec5SDimitry Andric   // emitPrologue if it gets called and emits CFI.
39960b57cec5SDimitry Andric   MF.setHasWinCFI(false);
39970b57cec5SDimitry Andric 
3998e8d8bef9SDimitry Andric   // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
3999e8d8bef9SDimitry Andric   // aligned. The format doesn't support misaligned stack adjustments.
4000e8d8bef9SDimitry Andric   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
4001e8d8bef9SDimitry Andric     MF.getFrameInfo().ensureMaxAlignment(Align(SlotSize));
4002e8d8bef9SDimitry Andric 
40030b57cec5SDimitry Andric   // If this function isn't doing Win64-style C++ EH, we don't need to do
40040b57cec5SDimitry Andric   // anything.
4005e8d8bef9SDimitry Andric   if (STI.is64Bit() && MF.hasEHFunclets() &&
4006e8d8bef9SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()) ==
4007e8d8bef9SDimitry Andric           EHPersonality::MSVC_CXX) {
4008e8d8bef9SDimitry Andric     adjustFrameForMsvcCxxEh(MF);
4009e8d8bef9SDimitry Andric   }
4010e8d8bef9SDimitry Andric }
40110b57cec5SDimitry Andric 
4012e8d8bef9SDimitry Andric void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
40130b57cec5SDimitry Andric   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
40140b57cec5SDimitry Andric   // relative to RSP after the prologue.  Find the offset of the last fixed
40150b57cec5SDimitry Andric   // object, so that we can allocate a slot immediately following it. If there
40160b57cec5SDimitry Andric   // were no fixed objects, use offset -SlotSize, which is immediately after the
40170b57cec5SDimitry Andric   // return address. Fixed objects have negative frame indices.
40180b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
40190b57cec5SDimitry Andric   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
40200b57cec5SDimitry Andric   int64_t MinFixedObjOffset = -SlotSize;
40210b57cec5SDimitry Andric   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
40220b57cec5SDimitry Andric     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
40230b57cec5SDimitry Andric 
40240b57cec5SDimitry Andric   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
40250b57cec5SDimitry Andric     for (WinEHHandlerType &H : TBME.HandlerArray) {
40260b57cec5SDimitry Andric       int FrameIndex = H.CatchObj.FrameIndex;
40270b57cec5SDimitry Andric       if (FrameIndex != INT_MAX) {
40280b57cec5SDimitry Andric         // Ensure alignment.
40295ffd83dbSDimitry Andric         unsigned Align = MFI.getObjectAlign(FrameIndex).value();
40300b57cec5SDimitry Andric         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
40310b57cec5SDimitry Andric         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
40320b57cec5SDimitry Andric         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
40330b57cec5SDimitry Andric       }
40340b57cec5SDimitry Andric     }
40350b57cec5SDimitry Andric   }
40360b57cec5SDimitry Andric 
40370b57cec5SDimitry Andric   // Ensure alignment.
40380b57cec5SDimitry Andric   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
40390b57cec5SDimitry Andric   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
40400b57cec5SDimitry Andric   int UnwindHelpFI =
40410b57cec5SDimitry Andric       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
40420b57cec5SDimitry Andric   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
40430b57cec5SDimitry Andric 
40440b57cec5SDimitry Andric   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
40450b57cec5SDimitry Andric   // other frame setup instructions.
40460b57cec5SDimitry Andric   MachineBasicBlock &MBB = MF.front();
40470b57cec5SDimitry Andric   auto MBBI = MBB.begin();
40480b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
40490b57cec5SDimitry Andric     ++MBBI;
40500b57cec5SDimitry Andric 
40510b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MBBI);
40520b57cec5SDimitry Andric   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
40530b57cec5SDimitry Andric                     UnwindHelpFI)
40540b57cec5SDimitry Andric       .addImm(-2);
40550b57cec5SDimitry Andric }
40565ffd83dbSDimitry Andric 
40575ffd83dbSDimitry Andric void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
40585ffd83dbSDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
4059*06c3fb27SDimitry Andric   auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4060*06c3fb27SDimitry Andric 
40615ffd83dbSDimitry Andric   if (STI.is32Bit() && MF.hasEHFunclets())
40625ffd83dbSDimitry Andric     restoreWinEHStackPointersInParent(MF);
4063*06c3fb27SDimitry Andric   // We have emitted prolog and epilog. Don't need stack pointer saving
4064*06c3fb27SDimitry Andric   // instruction any more.
4065*06c3fb27SDimitry Andric   if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) {
4066*06c3fb27SDimitry Andric     MI->eraseFromParent();
4067*06c3fb27SDimitry Andric     X86FI->setStackPtrSaveMI(nullptr);
4068*06c3fb27SDimitry Andric   }
40695ffd83dbSDimitry Andric }
40705ffd83dbSDimitry Andric 
40715ffd83dbSDimitry Andric void X86FrameLowering::restoreWinEHStackPointersInParent(
40725ffd83dbSDimitry Andric     MachineFunction &MF) const {
40735ffd83dbSDimitry Andric   // 32-bit functions have to restore stack pointers when control is transferred
40745ffd83dbSDimitry Andric   // back to the parent function. These blocks are identified as eh pads that
40755ffd83dbSDimitry Andric   // are not funclet entries.
40765ffd83dbSDimitry Andric   bool IsSEH = isAsynchronousEHPersonality(
40775ffd83dbSDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
40785ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : MF) {
40795ffd83dbSDimitry Andric     bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
40805ffd83dbSDimitry Andric     if (NeedsRestore)
40815ffd83dbSDimitry Andric       restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(),
40825ffd83dbSDimitry Andric                                   /*RestoreSP=*/IsSEH);
40835ffd83dbSDimitry Andric   }
40845ffd83dbSDimitry Andric }
4085