xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
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"
140b57cec5SDimitry Andric #include "X86InstrBuilder.h"
150b57cec5SDimitry Andric #include "X86InstrInfo.h"
160b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h"
170b57cec5SDimitry Andric #include "X86Subtarget.h"
180b57cec5SDimitry Andric #include "X86TargetMachine.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
270b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
280b57cec5SDimitry Andric #include "llvm/IR/Function.h"
290b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
300b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
310b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
320b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
330b57cec5SDimitry Andric #include <cstdlib>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
38*8bcb0991SDimitry Andric                                    MaybeAlign StackAlignOverride)
39*8bcb0991SDimitry Andric     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
400b57cec5SDimitry Andric                           STI.is64Bit() ? -8 : -4),
410b57cec5SDimitry Andric       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
420b57cec5SDimitry Andric   // Cache a bunch of frame-related predicates for this subtarget.
430b57cec5SDimitry Andric   SlotSize = TRI->getSlotSize();
440b57cec5SDimitry Andric   Is64Bit = STI.is64Bit();
450b57cec5SDimitry Andric   IsLP64 = STI.isTarget64BitLP64();
460b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
470b57cec5SDimitry Andric   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
480b57cec5SDimitry Andric   StackPtr = TRI->getStackRegister();
490b57cec5SDimitry Andric }
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
520b57cec5SDimitry Andric   return !MF.getFrameInfo().hasVarSizedObjects() &&
530b57cec5SDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
540b57cec5SDimitry Andric }
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
570b57cec5SDimitry Andric /// call frame pseudos can be simplified.  Having a FP, as in the default
580b57cec5SDimitry Andric /// implementation, is not sufficient here since we can't always use it.
590b57cec5SDimitry Andric /// Use a more nuanced condition.
600b57cec5SDimitry Andric bool
610b57cec5SDimitry Andric X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
620b57cec5SDimitry Andric   return hasReservedCallFrame(MF) ||
630b57cec5SDimitry Andric          (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
640b57cec5SDimitry Andric          TRI->hasBasePointer(MF);
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric // needsFrameIndexResolution - Do we need to perform FI resolution for
680b57cec5SDimitry Andric // this function. Normally, this is required only when the function
690b57cec5SDimitry Andric // has any stack objects. However, FI resolution actually has another job,
700b57cec5SDimitry Andric // not apparent from the title - it resolves callframesetup/destroy
710b57cec5SDimitry Andric // that were not simplified earlier.
720b57cec5SDimitry Andric // So, this is required for x86 functions that have push sequences even
730b57cec5SDimitry Andric // when there are no stack objects.
740b57cec5SDimitry Andric bool
750b57cec5SDimitry Andric X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
760b57cec5SDimitry Andric   return MF.getFrameInfo().hasStackObjects() ||
770b57cec5SDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
810b57cec5SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
820b57cec5SDimitry Andric /// or if frame pointer elimination is disabled.
830b57cec5SDimitry Andric bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
840b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
850b57cec5SDimitry Andric   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
860b57cec5SDimitry Andric           TRI->needsStackRealignment(MF) ||
870b57cec5SDimitry Andric           MFI.hasVarSizedObjects() ||
880b57cec5SDimitry Andric           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
890b57cec5SDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
900b57cec5SDimitry Andric           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
910b57cec5SDimitry Andric           MFI.hasStackMap() || MFI.hasPatchPoint() ||
920b57cec5SDimitry Andric           MFI.hasCopyImplyingStackAdjustment());
930b57cec5SDimitry Andric }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
960b57cec5SDimitry Andric   if (IsLP64) {
970b57cec5SDimitry Andric     if (isInt<8>(Imm))
980b57cec5SDimitry Andric       return X86::SUB64ri8;
990b57cec5SDimitry Andric     return X86::SUB64ri32;
1000b57cec5SDimitry Andric   } else {
1010b57cec5SDimitry Andric     if (isInt<8>(Imm))
1020b57cec5SDimitry Andric       return X86::SUB32ri8;
1030b57cec5SDimitry Andric     return X86::SUB32ri;
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
1080b57cec5SDimitry Andric   if (IsLP64) {
1090b57cec5SDimitry Andric     if (isInt<8>(Imm))
1100b57cec5SDimitry Andric       return X86::ADD64ri8;
1110b57cec5SDimitry Andric     return X86::ADD64ri32;
1120b57cec5SDimitry Andric   } else {
1130b57cec5SDimitry Andric     if (isInt<8>(Imm))
1140b57cec5SDimitry Andric       return X86::ADD32ri8;
1150b57cec5SDimitry Andric     return X86::ADD32ri;
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric static unsigned getSUBrrOpcode(unsigned isLP64) {
1200b57cec5SDimitry Andric   return isLP64 ? X86::SUB64rr : X86::SUB32rr;
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric static unsigned getADDrrOpcode(unsigned isLP64) {
1240b57cec5SDimitry Andric   return isLP64 ? X86::ADD64rr : X86::ADD32rr;
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
1280b57cec5SDimitry Andric   if (IsLP64) {
1290b57cec5SDimitry Andric     if (isInt<8>(Imm))
1300b57cec5SDimitry Andric       return X86::AND64ri8;
1310b57cec5SDimitry Andric     return X86::AND64ri32;
1320b57cec5SDimitry Andric   }
1330b57cec5SDimitry Andric   if (isInt<8>(Imm))
1340b57cec5SDimitry Andric     return X86::AND32ri8;
1350b57cec5SDimitry Andric   return X86::AND32ri;
1360b57cec5SDimitry Andric }
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric static unsigned getLEArOpcode(unsigned IsLP64) {
1390b57cec5SDimitry Andric   return IsLP64 ? X86::LEA64r : X86::LEA32r;
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
1430b57cec5SDimitry Andric /// when it reaches the "return" instruction. We can then pop a stack object
1440b57cec5SDimitry Andric /// to this register without worry about clobbering it.
1450b57cec5SDimitry Andric static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
1460b57cec5SDimitry Andric                                        MachineBasicBlock::iterator &MBBI,
1470b57cec5SDimitry Andric                                        const X86RegisterInfo *TRI,
1480b57cec5SDimitry Andric                                        bool Is64Bit) {
1490b57cec5SDimitry Andric   const MachineFunction *MF = MBB.getParent();
1500b57cec5SDimitry Andric   if (MF->callsEHReturn())
1510b57cec5SDimitry Andric     return 0;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   if (MBBI == MBB.end())
1560b57cec5SDimitry Andric     return 0;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   switch (MBBI->getOpcode()) {
1590b57cec5SDimitry Andric   default: return 0;
1600b57cec5SDimitry Andric   case TargetOpcode::PATCHABLE_RET:
1610b57cec5SDimitry Andric   case X86::RET:
1620b57cec5SDimitry Andric   case X86::RETL:
1630b57cec5SDimitry Andric   case X86::RETQ:
1640b57cec5SDimitry Andric   case X86::RETIL:
1650b57cec5SDimitry Andric   case X86::RETIQ:
1660b57cec5SDimitry Andric   case X86::TCRETURNdi:
1670b57cec5SDimitry Andric   case X86::TCRETURNri:
1680b57cec5SDimitry Andric   case X86::TCRETURNmi:
1690b57cec5SDimitry Andric   case X86::TCRETURNdi64:
1700b57cec5SDimitry Andric   case X86::TCRETURNri64:
1710b57cec5SDimitry Andric   case X86::TCRETURNmi64:
1720b57cec5SDimitry Andric   case X86::EH_RETURN:
1730b57cec5SDimitry Andric   case X86::EH_RETURN64: {
1740b57cec5SDimitry Andric     SmallSet<uint16_t, 8> Uses;
1750b57cec5SDimitry Andric     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
1760b57cec5SDimitry Andric       MachineOperand &MO = MBBI->getOperand(i);
1770b57cec5SDimitry Andric       if (!MO.isReg() || MO.isDef())
1780b57cec5SDimitry Andric         continue;
179*8bcb0991SDimitry Andric       Register Reg = MO.getReg();
1800b57cec5SDimitry Andric       if (!Reg)
1810b57cec5SDimitry Andric         continue;
1820b57cec5SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1830b57cec5SDimitry Andric         Uses.insert(*AI);
1840b57cec5SDimitry Andric     }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric     for (auto CS : AvailableRegs)
1870b57cec5SDimitry Andric       if (!Uses.count(CS) && CS != X86::RIP && CS != X86::RSP &&
1880b57cec5SDimitry Andric           CS != X86::ESP)
1890b57cec5SDimitry Andric         return CS;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   return 0;
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric static bool isEAXLiveIn(MachineBasicBlock &MBB) {
1970b57cec5SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
1980b57cec5SDimitry Andric     unsigned Reg = RegMask.PhysReg;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
2010b57cec5SDimitry Andric         Reg == X86::AH || Reg == X86::AL)
2020b57cec5SDimitry Andric       return true;
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   return false;
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric /// Check if the flags need to be preserved before the terminators.
2090b57cec5SDimitry Andric /// This would be the case, if the eflags is live-in of the region
2100b57cec5SDimitry Andric /// composed by the terminators or live-out of that region, without
2110b57cec5SDimitry Andric /// being defined by a terminator.
2120b57cec5SDimitry Andric static bool
2130b57cec5SDimitry Andric flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
2140b57cec5SDimitry Andric   for (const MachineInstr &MI : MBB.terminators()) {
2150b57cec5SDimitry Andric     bool BreakNext = false;
2160b57cec5SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
2170b57cec5SDimitry Andric       if (!MO.isReg())
2180b57cec5SDimitry Andric         continue;
219*8bcb0991SDimitry Andric       Register Reg = MO.getReg();
2200b57cec5SDimitry Andric       if (Reg != X86::EFLAGS)
2210b57cec5SDimitry Andric         continue;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric       // This terminator needs an eflags that is not defined
2240b57cec5SDimitry Andric       // by a previous another terminator:
2250b57cec5SDimitry Andric       // EFLAGS is live-in of the region composed by the terminators.
2260b57cec5SDimitry Andric       if (!MO.isDef())
2270b57cec5SDimitry Andric         return true;
2280b57cec5SDimitry Andric       // This terminator defines the eflags, i.e., we don't need to preserve it.
2290b57cec5SDimitry Andric       // However, we still need to check this specific terminator does not
2300b57cec5SDimitry Andric       // read a live-in value.
2310b57cec5SDimitry Andric       BreakNext = true;
2320b57cec5SDimitry Andric     }
2330b57cec5SDimitry Andric     // We found a definition of the eflags, no need to preserve them.
2340b57cec5SDimitry Andric     if (BreakNext)
2350b57cec5SDimitry Andric       return false;
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // None of the terminators use or define the eflags.
2390b57cec5SDimitry Andric   // Check if they are live-out, that would imply we need to preserve them.
2400b57cec5SDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors())
2410b57cec5SDimitry Andric     if (Succ->isLiveIn(X86::EFLAGS))
2420b57cec5SDimitry Andric       return true;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   return false;
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric /// emitSPUpdate - Emit a series of instructions to increment / decrement the
2480b57cec5SDimitry Andric /// stack pointer by a constant value.
2490b57cec5SDimitry Andric void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
2500b57cec5SDimitry Andric                                     MachineBasicBlock::iterator &MBBI,
2510b57cec5SDimitry Andric                                     const DebugLoc &DL,
2520b57cec5SDimitry Andric                                     int64_t NumBytes, bool InEpilogue) const {
2530b57cec5SDimitry Andric   bool isSub = NumBytes < 0;
2540b57cec5SDimitry Andric   uint64_t Offset = isSub ? -NumBytes : NumBytes;
2550b57cec5SDimitry Andric   MachineInstr::MIFlag Flag =
2560b57cec5SDimitry Andric       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   uint64_t Chunk = (1LL << 31) - 1;
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   if (Offset > Chunk) {
2610b57cec5SDimitry Andric     // Rather than emit a long series of instructions for large offsets,
2620b57cec5SDimitry Andric     // load the offset into a register and do one sub/add
2630b57cec5SDimitry Andric     unsigned Reg = 0;
2640b57cec5SDimitry Andric     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric     if (isSub && !isEAXLiveIn(MBB))
2670b57cec5SDimitry Andric       Reg = Rax;
2680b57cec5SDimitry Andric     else
2690b57cec5SDimitry Andric       Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric     unsigned MovRIOpc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
2720b57cec5SDimitry Andric     unsigned AddSubRROpc =
2730b57cec5SDimitry Andric         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
2740b57cec5SDimitry Andric     if (Reg) {
2750b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Reg)
2760b57cec5SDimitry Andric           .addImm(Offset)
2770b57cec5SDimitry Andric           .setMIFlag(Flag);
2780b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
2790b57cec5SDimitry Andric                              .addReg(StackPtr)
2800b57cec5SDimitry Andric                              .addReg(Reg);
2810b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2820b57cec5SDimitry Andric       return;
2830b57cec5SDimitry Andric     } else if (Offset > 8 * Chunk) {
2840b57cec5SDimitry Andric       // If we would need more than 8 add or sub instructions (a >16GB stack
2850b57cec5SDimitry Andric       // frame), it's worth spilling RAX to materialize this immediate.
2860b57cec5SDimitry Andric       //   pushq %rax
2870b57cec5SDimitry Andric       //   movabsq +-$Offset+-SlotSize, %rax
2880b57cec5SDimitry Andric       //   addq %rsp, %rax
2890b57cec5SDimitry Andric       //   xchg %rax, (%rsp)
2900b57cec5SDimitry Andric       //   movq (%rsp), %rsp
2910b57cec5SDimitry Andric       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
2920b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2930b57cec5SDimitry Andric           .addReg(Rax, RegState::Kill)
2940b57cec5SDimitry Andric           .setMIFlag(Flag);
2950b57cec5SDimitry Andric       // Subtract is not commutative, so negate the offset and always use add.
2960b57cec5SDimitry Andric       // Subtract 8 less and add 8 more to account for the PUSH we just did.
2970b57cec5SDimitry Andric       if (isSub)
2980b57cec5SDimitry Andric         Offset = -(Offset - SlotSize);
2990b57cec5SDimitry Andric       else
3000b57cec5SDimitry Andric         Offset = Offset + SlotSize;
3010b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Rax)
3020b57cec5SDimitry Andric           .addImm(Offset)
3030b57cec5SDimitry Andric           .setMIFlag(Flag);
3040b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
3050b57cec5SDimitry Andric                              .addReg(Rax)
3060b57cec5SDimitry Andric                              .addReg(StackPtr);
3070b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3080b57cec5SDimitry Andric       // Exchange the new SP in RAX with the top of the stack.
3090b57cec5SDimitry Andric       addRegOffset(
3100b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
3110b57cec5SDimitry Andric           StackPtr, false, 0);
3120b57cec5SDimitry Andric       // Load new SP from the top of the stack into RSP.
3130b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
3140b57cec5SDimitry Andric                    StackPtr, false, 0);
3150b57cec5SDimitry Andric       return;
3160b57cec5SDimitry Andric     }
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   while (Offset) {
3200b57cec5SDimitry Andric     uint64_t ThisVal = std::min(Offset, Chunk);
3210b57cec5SDimitry Andric     if (ThisVal == SlotSize) {
3220b57cec5SDimitry Andric       // Use push / pop for slot sized adjustments as a size optimization. We
3230b57cec5SDimitry Andric       // need to find a dead register when using pop.
3240b57cec5SDimitry Andric       unsigned Reg = isSub
3250b57cec5SDimitry Andric         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
3260b57cec5SDimitry Andric         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
3270b57cec5SDimitry Andric       if (Reg) {
3280b57cec5SDimitry Andric         unsigned Opc = isSub
3290b57cec5SDimitry Andric           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
3300b57cec5SDimitry Andric           : (Is64Bit ? X86::POP64r  : X86::POP32r);
3310b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(Opc))
3320b57cec5SDimitry Andric             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
3330b57cec5SDimitry Andric             .setMIFlag(Flag);
3340b57cec5SDimitry Andric         Offset -= ThisVal;
3350b57cec5SDimitry Andric         continue;
3360b57cec5SDimitry Andric       }
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
3400b57cec5SDimitry Andric         .setMIFlag(Flag);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     Offset -= ThisVal;
3430b57cec5SDimitry Andric   }
3440b57cec5SDimitry Andric }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
3470b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3480b57cec5SDimitry Andric     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
3490b57cec5SDimitry Andric   assert(Offset != 0 && "zero offset stack adjustment requested");
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
3520b57cec5SDimitry Andric   // is tricky.
3530b57cec5SDimitry Andric   bool UseLEA;
3540b57cec5SDimitry Andric   if (!InEpilogue) {
3550b57cec5SDimitry Andric     // Check if inserting the prologue at the beginning
3560b57cec5SDimitry Andric     // of MBB would require to use LEA operations.
3570b57cec5SDimitry Andric     // We need to use LEA operations if EFLAGS is live in, because
3580b57cec5SDimitry Andric     // it means an instruction will read it before it gets defined.
3590b57cec5SDimitry Andric     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
3600b57cec5SDimitry Andric   } else {
3610b57cec5SDimitry Andric     // If we can use LEA for SP but we shouldn't, check that none
3620b57cec5SDimitry Andric     // of the terminators uses the eflags. Otherwise we will insert
3630b57cec5SDimitry Andric     // a ADD that will redefine the eflags and break the condition.
3640b57cec5SDimitry Andric     // Alternatively, we could move the ADD, but this may not be possible
3650b57cec5SDimitry Andric     // and is an optimization anyway.
3660b57cec5SDimitry Andric     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
3670b57cec5SDimitry Andric     if (UseLEA && !STI.useLeaForSP())
3680b57cec5SDimitry Andric       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
3690b57cec5SDimitry Andric     // If that assert breaks, that means we do not do the right thing
3700b57cec5SDimitry Andric     // in canUseAsEpilogue.
3710b57cec5SDimitry Andric     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
3720b57cec5SDimitry Andric            "We shouldn't have allowed this insertion point");
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   MachineInstrBuilder MI;
3760b57cec5SDimitry Andric   if (UseLEA) {
3770b57cec5SDimitry Andric     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
3780b57cec5SDimitry Andric                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
3790b57cec5SDimitry Andric                               StackPtr),
3800b57cec5SDimitry Andric                       StackPtr, false, Offset);
3810b57cec5SDimitry Andric   } else {
3820b57cec5SDimitry Andric     bool IsSub = Offset < 0;
3830b57cec5SDimitry Andric     uint64_t AbsOffset = IsSub ? -Offset : Offset;
3840b57cec5SDimitry Andric     unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
3850b57cec5SDimitry Andric                          : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
3860b57cec5SDimitry Andric     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
3870b57cec5SDimitry Andric              .addReg(StackPtr)
3880b57cec5SDimitry Andric              .addImm(AbsOffset);
3890b57cec5SDimitry Andric     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric   return MI;
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
3950b57cec5SDimitry Andric                                      MachineBasicBlock::iterator &MBBI,
3960b57cec5SDimitry Andric                                      bool doMergeWithPrevious) const {
3970b57cec5SDimitry Andric   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
3980b57cec5SDimitry Andric       (!doMergeWithPrevious && MBBI == MBB.end()))
3990b57cec5SDimitry Andric     return 0;
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   PI = skipDebugInstructionsBackward(PI, MBB.begin());
4040b57cec5SDimitry Andric   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
4050b57cec5SDimitry Andric   // instruction, and that there are no DBG_VALUE or other instructions between
4060b57cec5SDimitry Andric   // ADD/SUB/LEA and its corresponding CFI instruction.
4070b57cec5SDimitry Andric   /* TODO: Add support for the case where there are multiple CFI instructions
4080b57cec5SDimitry Andric     below the ADD/SUB/LEA, e.g.:
4090b57cec5SDimitry Andric     ...
4100b57cec5SDimitry Andric     add
4110b57cec5SDimitry Andric     cfi_def_cfa_offset
4120b57cec5SDimitry Andric     cfi_offset
4130b57cec5SDimitry Andric     ...
4140b57cec5SDimitry Andric   */
4150b57cec5SDimitry Andric   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
4160b57cec5SDimitry Andric     PI = std::prev(PI);
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   unsigned Opc = PI->getOpcode();
4190b57cec5SDimitry Andric   int Offset = 0;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
4220b57cec5SDimitry Andric        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
4230b57cec5SDimitry Andric       PI->getOperand(0).getReg() == StackPtr){
4240b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4250b57cec5SDimitry Andric     Offset = PI->getOperand(2).getImm();
4260b57cec5SDimitry Andric   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
4270b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr &&
4280b57cec5SDimitry Andric              PI->getOperand(1).getReg() == StackPtr &&
4290b57cec5SDimitry Andric              PI->getOperand(2).getImm() == 1 &&
4300b57cec5SDimitry Andric              PI->getOperand(3).getReg() == X86::NoRegister &&
4310b57cec5SDimitry Andric              PI->getOperand(5).getReg() == X86::NoRegister) {
4320b57cec5SDimitry Andric     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
4330b57cec5SDimitry Andric     Offset = PI->getOperand(4).getImm();
4340b57cec5SDimitry Andric   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
4350b57cec5SDimitry Andric               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
4360b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr) {
4370b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4380b57cec5SDimitry Andric     Offset = -PI->getOperand(2).getImm();
4390b57cec5SDimitry Andric   } else
4400b57cec5SDimitry Andric     return 0;
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric   PI = MBB.erase(PI);
4430b57cec5SDimitry Andric   if (PI != MBB.end() && PI->isCFIInstruction()) PI = MBB.erase(PI);
4440b57cec5SDimitry Andric   if (!doMergeWithPrevious)
4450b57cec5SDimitry Andric     MBBI = skipDebugInstructionsForward(PI, MBB.end());
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   return Offset;
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
4510b57cec5SDimitry Andric                                 MachineBasicBlock::iterator MBBI,
4520b57cec5SDimitry Andric                                 const DebugLoc &DL,
4530b57cec5SDimitry Andric                                 const MCCFIInstruction &CFIInst) const {
4540b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4550b57cec5SDimitry Andric   unsigned CFIIndex = MF.addFrameInst(CFIInst);
4560b57cec5SDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
4570b57cec5SDimitry Andric       .addCFIIndex(CFIIndex);
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMoves(
4610b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
4620b57cec5SDimitry Andric     const DebugLoc &DL) const {
4630b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4640b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
4650b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
4660b57cec5SDimitry Andric   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   // Add callee saved registers to move list.
4690b57cec5SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
4700b57cec5SDimitry Andric   if (CSI.empty()) return;
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // Calculate offsets.
4730b57cec5SDimitry Andric   for (std::vector<CalleeSavedInfo>::const_iterator
4740b57cec5SDimitry Andric          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
4750b57cec5SDimitry Andric     int64_t Offset = MFI.getObjectOffset(I->getFrameIdx());
4760b57cec5SDimitry Andric     unsigned Reg = I->getReg();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
4790b57cec5SDimitry Andric     BuildCFI(MBB, MBBI, DL,
4800b57cec5SDimitry Andric              MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
4810b57cec5SDimitry Andric   }
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric void X86FrameLowering::emitStackProbe(MachineFunction &MF,
4850b57cec5SDimitry Andric                                       MachineBasicBlock &MBB,
4860b57cec5SDimitry Andric                                       MachineBasicBlock::iterator MBBI,
4870b57cec5SDimitry Andric                                       const DebugLoc &DL, bool InProlog) const {
4880b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
4890b57cec5SDimitry Andric   if (STI.isTargetWindowsCoreCLR()) {
4900b57cec5SDimitry Andric     if (InProlog) {
4910b57cec5SDimitry Andric       emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
4920b57cec5SDimitry Andric     } else {
4930b57cec5SDimitry Andric       emitStackProbeInline(MF, MBB, MBBI, DL, false);
4940b57cec5SDimitry Andric     }
4950b57cec5SDimitry Andric   } else {
4960b57cec5SDimitry Andric     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
4970b57cec5SDimitry Andric   }
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
5010b57cec5SDimitry Andric                                         MachineBasicBlock &PrologMBB) const {
5020b57cec5SDimitry Andric   const StringRef ChkStkStubSymbol = "__chkstk_stub";
5030b57cec5SDimitry Andric   MachineInstr *ChkStkStub = nullptr;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   for (MachineInstr &MI : PrologMBB) {
5060b57cec5SDimitry Andric     if (MI.isCall() && MI.getOperand(0).isSymbol() &&
5070b57cec5SDimitry Andric         ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
5080b57cec5SDimitry Andric       ChkStkStub = &MI;
5090b57cec5SDimitry Andric       break;
5100b57cec5SDimitry Andric     }
5110b57cec5SDimitry Andric   }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   if (ChkStkStub != nullptr) {
5140b57cec5SDimitry Andric     assert(!ChkStkStub->isBundled() &&
5150b57cec5SDimitry Andric            "Not expecting bundled instructions here");
5160b57cec5SDimitry Andric     MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
5170b57cec5SDimitry Andric     assert(std::prev(MBBI) == ChkStkStub &&
5180b57cec5SDimitry Andric            "MBBI expected after __chkstk_stub.");
5190b57cec5SDimitry Andric     DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
5200b57cec5SDimitry Andric     emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
5210b57cec5SDimitry Andric     ChkStkStub->eraseFromParent();
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
5260b57cec5SDimitry Andric                                             MachineBasicBlock &MBB,
5270b57cec5SDimitry Andric                                             MachineBasicBlock::iterator MBBI,
5280b57cec5SDimitry Andric                                             const DebugLoc &DL,
5290b57cec5SDimitry Andric                                             bool InProlog) const {
5300b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
5310b57cec5SDimitry Andric   assert(STI.is64Bit() && "different expansion needed for 32 bit");
5320b57cec5SDimitry Andric   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
5330b57cec5SDimitry Andric   const TargetInstrInfo &TII = *STI.getInstrInfo();
5340b57cec5SDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   // RAX contains the number of bytes of desired stack adjustment.
5370b57cec5SDimitry Andric   // The handling here assumes this value has already been updated so as to
5380b57cec5SDimitry Andric   // maintain stack alignment.
5390b57cec5SDimitry Andric   //
5400b57cec5SDimitry Andric   // We need to exit with RSP modified by this amount and execute suitable
5410b57cec5SDimitry Andric   // page touches to notify the OS that we're growing the stack responsibly.
5420b57cec5SDimitry Andric   // All stack probing must be done without modifying RSP.
5430b57cec5SDimitry Andric   //
5440b57cec5SDimitry Andric   // MBB:
5450b57cec5SDimitry Andric   //    SizeReg = RAX;
5460b57cec5SDimitry Andric   //    ZeroReg = 0
5470b57cec5SDimitry Andric   //    CopyReg = RSP
5480b57cec5SDimitry Andric   //    Flags, TestReg = CopyReg - SizeReg
5490b57cec5SDimitry Andric   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
5500b57cec5SDimitry Andric   //    LimitReg = gs magic thread env access
5510b57cec5SDimitry Andric   //    if FinalReg >= LimitReg goto ContinueMBB
5520b57cec5SDimitry Andric   // RoundBB:
5530b57cec5SDimitry Andric   //    RoundReg = page address of FinalReg
5540b57cec5SDimitry Andric   // LoopMBB:
5550b57cec5SDimitry Andric   //    LoopReg = PHI(LimitReg,ProbeReg)
5560b57cec5SDimitry Andric   //    ProbeReg = LoopReg - PageSize
5570b57cec5SDimitry Andric   //    [ProbeReg] = 0
5580b57cec5SDimitry Andric   //    if (ProbeReg > RoundReg) goto LoopMBB
5590b57cec5SDimitry Andric   // ContinueMBB:
5600b57cec5SDimitry Andric   //    RSP = RSP - RAX
5610b57cec5SDimitry Andric   //    [rest of original MBB]
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   // Set up the new basic blocks
5640b57cec5SDimitry Andric   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
5650b57cec5SDimitry Andric   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
5660b57cec5SDimitry Andric   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
5690b57cec5SDimitry Andric   MF.insert(MBBIter, RoundMBB);
5700b57cec5SDimitry Andric   MF.insert(MBBIter, LoopMBB);
5710b57cec5SDimitry Andric   MF.insert(MBBIter, ContinueMBB);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   // Split MBB and move the tail portion down to ContinueMBB.
5740b57cec5SDimitry Andric   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
5750b57cec5SDimitry Andric   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
5760b57cec5SDimitry Andric   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   // Some useful constants
5790b57cec5SDimitry Andric   const int64_t ThreadEnvironmentStackLimit = 0x10;
5800b57cec5SDimitry Andric   const int64_t PageSize = 0x1000;
5810b57cec5SDimitry Andric   const int64_t PageMask = ~(PageSize - 1);
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric   // Registers we need. For the normal case we use virtual
5840b57cec5SDimitry Andric   // registers. For the prolog expansion we use RAX, RCX and RDX.
5850b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
5860b57cec5SDimitry Andric   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
5870b57cec5SDimitry Andric   const Register SizeReg = InProlog ? X86::RAX
5880b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
5890b57cec5SDimitry Andric                  ZeroReg = InProlog ? X86::RCX
5900b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
5910b57cec5SDimitry Andric                  CopyReg = InProlog ? X86::RDX
5920b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
5930b57cec5SDimitry Andric                  TestReg = InProlog ? X86::RDX
5940b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
5950b57cec5SDimitry Andric                  FinalReg = InProlog ? X86::RDX
5960b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
5970b57cec5SDimitry Andric                  RoundedReg = InProlog ? X86::RDX
5980b57cec5SDimitry Andric                                        : MRI.createVirtualRegister(RegClass),
5990b57cec5SDimitry Andric                  LimitReg = InProlog ? X86::RCX
6000b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass),
6010b57cec5SDimitry Andric                  JoinReg = InProlog ? X86::RCX
6020b57cec5SDimitry Andric                                     : MRI.createVirtualRegister(RegClass),
6030b57cec5SDimitry Andric                  ProbeReg = InProlog ? X86::RCX
6040b57cec5SDimitry Andric                                      : MRI.createVirtualRegister(RegClass);
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   // SP-relative offsets where we can save RCX and RDX.
6070b57cec5SDimitry Andric   int64_t RCXShadowSlot = 0;
6080b57cec5SDimitry Andric   int64_t RDXShadowSlot = 0;
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   // If inlining in the prolog, save RCX and RDX.
6110b57cec5SDimitry Andric   if (InProlog) {
6120b57cec5SDimitry Andric     // Compute the offsets. We need to account for things already
6130b57cec5SDimitry Andric     // pushed onto the stack at this point: return address, frame
6140b57cec5SDimitry Andric     // pointer (if used), and callee saves.
6150b57cec5SDimitry Andric     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
6160b57cec5SDimitry Andric     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
6170b57cec5SDimitry Andric     const bool HasFP = hasFP(MF);
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric     // Check if we need to spill RCX and/or RDX.
6200b57cec5SDimitry Andric     // Here we assume that no earlier prologue instruction changes RCX and/or
6210b57cec5SDimitry Andric     // RDX, so checking the block live-ins is enough.
6220b57cec5SDimitry Andric     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
6230b57cec5SDimitry Andric     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
6240b57cec5SDimitry Andric     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
6250b57cec5SDimitry Andric     // Assign the initial slot to both registers, then change RDX's slot if both
6260b57cec5SDimitry Andric     // need to be spilled.
6270b57cec5SDimitry Andric     if (IsRCXLiveIn)
6280b57cec5SDimitry Andric       RCXShadowSlot = InitSlot;
6290b57cec5SDimitry Andric     if (IsRDXLiveIn)
6300b57cec5SDimitry Andric       RDXShadowSlot = InitSlot;
6310b57cec5SDimitry Andric     if (IsRDXLiveIn && IsRCXLiveIn)
6320b57cec5SDimitry Andric       RDXShadowSlot += 8;
6330b57cec5SDimitry Andric     // Emit the saves if needed.
6340b57cec5SDimitry Andric     if (IsRCXLiveIn)
6350b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
6360b57cec5SDimitry Andric                    RCXShadowSlot)
6370b57cec5SDimitry Andric           .addReg(X86::RCX);
6380b57cec5SDimitry Andric     if (IsRDXLiveIn)
6390b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
6400b57cec5SDimitry Andric                    RDXShadowSlot)
6410b57cec5SDimitry Andric           .addReg(X86::RDX);
6420b57cec5SDimitry Andric   } else {
6430b57cec5SDimitry Andric     // Not in the prolog. Copy RAX to a virtual reg.
6440b57cec5SDimitry Andric     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
6450b57cec5SDimitry Andric   }
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   // Add code to MBB to check for overflow and set the new target stack pointer
6480b57cec5SDimitry Andric   // to zero if so.
6490b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
6500b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef)
6510b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef);
6520b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
6530b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
6540b57cec5SDimitry Andric       .addReg(CopyReg)
6550b57cec5SDimitry Andric       .addReg(SizeReg);
6560b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
6570b57cec5SDimitry Andric       .addReg(TestReg)
6580b57cec5SDimitry Andric       .addReg(ZeroReg)
6590b57cec5SDimitry Andric       .addImm(X86::COND_B);
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // FinalReg now holds final stack pointer value, or zero if
6620b57cec5SDimitry Andric   // allocation would overflow. Compare against the current stack
6630b57cec5SDimitry Andric   // limit from the thread environment block. Note this limit is the
6640b57cec5SDimitry Andric   // lowest touched page on the stack, not the point at which the OS
6650b57cec5SDimitry Andric   // will cause an overflow exception, so this is just an optimization
6660b57cec5SDimitry Andric   // to avoid unnecessarily touching pages that are below the current
6670b57cec5SDimitry Andric   // SP but already committed to the stack by the OS.
6680b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
6690b57cec5SDimitry Andric       .addReg(0)
6700b57cec5SDimitry Andric       .addImm(1)
6710b57cec5SDimitry Andric       .addReg(0)
6720b57cec5SDimitry Andric       .addImm(ThreadEnvironmentStackLimit)
6730b57cec5SDimitry Andric       .addReg(X86::GS);
6740b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
6750b57cec5SDimitry Andric   // Jump if the desired stack pointer is at or above the stack limit.
6760b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric   // Add code to roundMBB to round the final stack pointer to a page boundary.
6790b57cec5SDimitry Andric   RoundMBB->addLiveIn(FinalReg);
6800b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
6810b57cec5SDimitry Andric       .addReg(FinalReg)
6820b57cec5SDimitry Andric       .addImm(PageMask);
6830b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   // LimitReg now holds the current stack limit, RoundedReg page-rounded
6860b57cec5SDimitry Andric   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
6870b57cec5SDimitry Andric   // and probe until we reach RoundedReg.
6880b57cec5SDimitry Andric   if (!InProlog) {
6890b57cec5SDimitry Andric     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
6900b57cec5SDimitry Andric         .addReg(LimitReg)
6910b57cec5SDimitry Andric         .addMBB(RoundMBB)
6920b57cec5SDimitry Andric         .addReg(ProbeReg)
6930b57cec5SDimitry Andric         .addMBB(LoopMBB);
6940b57cec5SDimitry Andric   }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   LoopMBB->addLiveIn(JoinReg);
6970b57cec5SDimitry Andric   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
6980b57cec5SDimitry Andric                false, -PageSize);
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   // Probe by storing a byte onto the stack.
7010b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
7020b57cec5SDimitry Andric       .addReg(ProbeReg)
7030b57cec5SDimitry Andric       .addImm(1)
7040b57cec5SDimitry Andric       .addReg(0)
7050b57cec5SDimitry Andric       .addImm(0)
7060b57cec5SDimitry Andric       .addReg(0)
7070b57cec5SDimitry Andric       .addImm(0);
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   LoopMBB->addLiveIn(RoundedReg);
7100b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
7110b57cec5SDimitry Andric       .addReg(RoundedReg)
7120b57cec5SDimitry Andric       .addReg(ProbeReg);
7130b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   // If in prolog, restore RDX and RCX.
7180b57cec5SDimitry Andric   if (InProlog) {
7190b57cec5SDimitry Andric     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
7200b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
7210b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RCX),
7220b57cec5SDimitry Andric                    X86::RSP, false, RCXShadowSlot);
7230b57cec5SDimitry Andric     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
7240b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
7250b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RDX),
7260b57cec5SDimitry Andric                    X86::RSP, false, RDXShadowSlot);
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   // Now that the probing is done, add code to continueMBB to update
7300b57cec5SDimitry Andric   // the stack pointer for real.
7310b57cec5SDimitry Andric   ContinueMBB->addLiveIn(SizeReg);
7320b57cec5SDimitry Andric   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
7330b57cec5SDimitry Andric       .addReg(X86::RSP)
7340b57cec5SDimitry Andric       .addReg(SizeReg);
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // Add the control flow edges we need.
7370b57cec5SDimitry Andric   MBB.addSuccessor(ContinueMBB);
7380b57cec5SDimitry Andric   MBB.addSuccessor(RoundMBB);
7390b57cec5SDimitry Andric   RoundMBB->addSuccessor(LoopMBB);
7400b57cec5SDimitry Andric   LoopMBB->addSuccessor(ContinueMBB);
7410b57cec5SDimitry Andric   LoopMBB->addSuccessor(LoopMBB);
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   // Mark all the instructions added to the prolog as frame setup.
7440b57cec5SDimitry Andric   if (InProlog) {
7450b57cec5SDimitry Andric     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
7460b57cec5SDimitry Andric       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
7470b57cec5SDimitry Andric     }
7480b57cec5SDimitry Andric     for (MachineInstr &MI : *RoundMBB) {
7490b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
7500b57cec5SDimitry Andric     }
7510b57cec5SDimitry Andric     for (MachineInstr &MI : *LoopMBB) {
7520b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric     for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
7550b57cec5SDimitry Andric          CMBBI != ContinueMBBI; ++CMBBI) {
7560b57cec5SDimitry Andric       CMBBI->setFlag(MachineInstr::FrameSetup);
7570b57cec5SDimitry Andric     }
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
7620b57cec5SDimitry Andric                                           MachineBasicBlock &MBB,
7630b57cec5SDimitry Andric                                           MachineBasicBlock::iterator MBBI,
7640b57cec5SDimitry Andric                                           const DebugLoc &DL,
7650b57cec5SDimitry Andric                                           bool InProlog) const {
7660b57cec5SDimitry Andric   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   // FIXME: Add retpoline support and remove this.
7690b57cec5SDimitry Andric   if (Is64Bit && IsLargeCodeModel && STI.useRetpolineIndirectCalls())
7700b57cec5SDimitry Andric     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
7710b57cec5SDimitry Andric                        "code model and retpoline not yet implemented.");
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   unsigned CallOp;
7740b57cec5SDimitry Andric   if (Is64Bit)
7750b57cec5SDimitry Andric     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
7760b57cec5SDimitry Andric   else
7770b57cec5SDimitry Andric     CallOp = X86::CALLpcrel32;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   MachineInstrBuilder CI;
7820b57cec5SDimitry Andric   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   // All current stack probes take AX and SP as input, clobber flags, and
7850b57cec5SDimitry Andric   // preserve all registers. x86_64 probes leave RSP unmodified.
7860b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
7870b57cec5SDimitry Andric     // For the large code model, we have to call through a register. Use R11,
7880b57cec5SDimitry Andric     // as it is scratch in all supported calling conventions.
7890b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
7900b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
7910b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
7920b57cec5SDimitry Andric   } else {
7930b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
7940b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
7950b57cec5SDimitry Andric   }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
7980b57cec5SDimitry Andric   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
7990b57cec5SDimitry Andric   CI.addReg(AX, RegState::Implicit)
8000b57cec5SDimitry Andric       .addReg(SP, RegState::Implicit)
8010b57cec5SDimitry Andric       .addReg(AX, RegState::Define | RegState::Implicit)
8020b57cec5SDimitry Andric       .addReg(SP, RegState::Define | RegState::Implicit)
8030b57cec5SDimitry Andric       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   if (STI.isTargetWin64() || !STI.isOSWindows()) {
8060b57cec5SDimitry Andric     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
8070b57cec5SDimitry Andric     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
8080b57cec5SDimitry Andric     // themselves. They also does not clobber %rax so we can reuse it when
8090b57cec5SDimitry Andric     // adjusting %rsp.
8100b57cec5SDimitry Andric     // All other platforms do not specify a particular ABI for the stack probe
8110b57cec5SDimitry Andric     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
8120b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
8130b57cec5SDimitry Andric         .addReg(SP)
8140b57cec5SDimitry Andric         .addReg(AX);
8150b57cec5SDimitry Andric   }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   if (InProlog) {
8180b57cec5SDimitry Andric     // Apply the frame setup flag to all inserted instrs.
8190b57cec5SDimitry Andric     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
8200b57cec5SDimitry Andric       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
8210b57cec5SDimitry Andric   }
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInlineStub(
8250b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
8260b57cec5SDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   assert(InProlog && "ChkStkStub called outside prolog!");
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
8310b57cec5SDimitry Andric       .addExternalSymbol("__chkstk_stub");
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric static unsigned calculateSetFPREG(uint64_t SPAdjust) {
8350b57cec5SDimitry Andric   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
8360b57cec5SDimitry Andric   // and might require smaller successive adjustments.
8370b57cec5SDimitry Andric   const uint64_t Win64MaxSEHOffset = 128;
8380b57cec5SDimitry Andric   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
8390b57cec5SDimitry Andric   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
8400b57cec5SDimitry Andric   return SEHFrameOffset & -16;
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric // If we're forcing a stack realignment we can't rely on just the frame
8440b57cec5SDimitry Andric // info, we need to know the ABI stack alignment as well in case we
8450b57cec5SDimitry Andric // have a call out.  Otherwise just make sure we have some alignment - we'll
8460b57cec5SDimitry Andric // go with the minimum SlotSize.
8470b57cec5SDimitry Andric uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
8480b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
8490b57cec5SDimitry Andric   uint64_t MaxAlign = MFI.getMaxAlignment(); // Desired stack alignment.
8500b57cec5SDimitry Andric   unsigned StackAlign = getStackAlignment();
8510b57cec5SDimitry Andric   if (MF.getFunction().hasFnAttribute("stackrealign")) {
8520b57cec5SDimitry Andric     if (MFI.hasCalls())
8530b57cec5SDimitry Andric       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
8540b57cec5SDimitry Andric     else if (MaxAlign < SlotSize)
8550b57cec5SDimitry Andric       MaxAlign = SlotSize;
8560b57cec5SDimitry Andric   }
8570b57cec5SDimitry Andric   return MaxAlign;
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
8610b57cec5SDimitry Andric                                           MachineBasicBlock::iterator MBBI,
8620b57cec5SDimitry Andric                                           const DebugLoc &DL, unsigned Reg,
8630b57cec5SDimitry Andric                                           uint64_t MaxAlign) const {
8640b57cec5SDimitry Andric   uint64_t Val = -MaxAlign;
8650b57cec5SDimitry Andric   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
8660b57cec5SDimitry Andric   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
8670b57cec5SDimitry Andric                          .addReg(Reg)
8680b57cec5SDimitry Andric                          .addImm(Val)
8690b57cec5SDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup);
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric   // The EFLAGS implicit def is dead.
8720b57cec5SDimitry Andric   MI->getOperand(3).setIsDead();
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
8760b57cec5SDimitry Andric   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
8770b57cec5SDimitry Andric   // clobbered by any interrupt handler.
8780b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
8790b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
8800b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
8810b57cec5SDimitry Andric   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
8820b57cec5SDimitry Andric   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric /// emitPrologue - Push callee-saved registers onto the stack, which
8870b57cec5SDimitry Andric /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
8880b57cec5SDimitry Andric /// space for local variables. Also emit labels used by the exception handler to
8890b57cec5SDimitry Andric /// generate the exception handling frames.
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric /*
8920b57cec5SDimitry Andric   Here's a gist of what gets emitted:
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   ; Establish frame pointer, if needed
8950b57cec5SDimitry Andric   [if needs FP]
8960b57cec5SDimitry Andric       push  %rbp
8970b57cec5SDimitry Andric       .cfi_def_cfa_offset 16
8980b57cec5SDimitry Andric       .cfi_offset %rbp, -16
8990b57cec5SDimitry Andric       .seh_pushreg %rpb
9000b57cec5SDimitry Andric       mov  %rsp, %rbp
9010b57cec5SDimitry Andric       .cfi_def_cfa_register %rbp
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   ; Spill general-purpose registers
9040b57cec5SDimitry Andric   [for all callee-saved GPRs]
9050b57cec5SDimitry Andric       pushq %<reg>
9060b57cec5SDimitry Andric       [if not needs FP]
9070b57cec5SDimitry Andric          .cfi_def_cfa_offset (offset from RETADDR)
9080b57cec5SDimitry Andric       .seh_pushreg %<reg>
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   ; If the required stack alignment > default stack alignment
9110b57cec5SDimitry Andric   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
9120b57cec5SDimitry Andric   ; of unknown size in the stack frame.
9130b57cec5SDimitry Andric   [if stack needs re-alignment]
9140b57cec5SDimitry Andric       and  $MASK, %rsp
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   ; Allocate space for locals
9170b57cec5SDimitry Andric   [if target is Windows and allocated space > 4096 bytes]
9180b57cec5SDimitry Andric       ; Windows needs special care for allocations larger
9190b57cec5SDimitry Andric       ; than one page.
9200b57cec5SDimitry Andric       mov $NNN, %rax
9210b57cec5SDimitry Andric       call ___chkstk_ms/___chkstk
9220b57cec5SDimitry Andric       sub  %rax, %rsp
9230b57cec5SDimitry Andric   [else]
9240b57cec5SDimitry Andric       sub  $NNN, %rsp
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   [if needs FP]
9270b57cec5SDimitry Andric       .seh_stackalloc (size of XMM spill slots)
9280b57cec5SDimitry Andric       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
9290b57cec5SDimitry Andric   [else]
9300b57cec5SDimitry Andric       .seh_stackalloc NNN
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   ; Spill XMMs
9330b57cec5SDimitry Andric   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
9340b57cec5SDimitry Andric   ; they may get spilled on any platform, if the current function
9350b57cec5SDimitry Andric   ; calls @llvm.eh.unwind.init
9360b57cec5SDimitry Andric   [if needs FP]
9370b57cec5SDimitry Andric       [for all callee-saved XMM registers]
9380b57cec5SDimitry Andric           movaps  %<xmm reg>, -MMM(%rbp)
9390b57cec5SDimitry Andric       [for all callee-saved XMM registers]
9400b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
9410b57cec5SDimitry Andric               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
9420b57cec5SDimitry Andric   [else]
9430b57cec5SDimitry Andric       [for all callee-saved XMM registers]
9440b57cec5SDimitry Andric           movaps  %<xmm reg>, KKK(%rsp)
9450b57cec5SDimitry Andric       [for all callee-saved XMM registers]
9460b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, KKK
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   .seh_endprologue
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   [if needs base pointer]
9510b57cec5SDimitry Andric       mov  %rsp, %rbx
9520b57cec5SDimitry Andric       [if needs to restore base pointer]
9530b57cec5SDimitry Andric           mov %rsp, -MMM(%rbp)
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   ; Emit CFI info
9560b57cec5SDimitry Andric   [if needs FP]
9570b57cec5SDimitry Andric       [for all callee-saved registers]
9580b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rbp)
9590b57cec5SDimitry Andric   [else]
9600b57cec5SDimitry Andric        .cfi_def_cfa_offset (offset from RETADDR)
9610b57cec5SDimitry Andric       [for all callee-saved registers]
9620b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rsp)
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   Notes:
9650b57cec5SDimitry Andric   - .seh directives are emitted only for Windows 64 ABI
9660b57cec5SDimitry Andric   - .cv_fpo directives are emitted on win32 when emitting CodeView
9670b57cec5SDimitry Andric   - .cfi directives are emitted for all other ABIs
9680b57cec5SDimitry Andric   - for 32-bit code, substitute %e?? registers for %r??
9690b57cec5SDimitry Andric */
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric void X86FrameLowering::emitPrologue(MachineFunction &MF,
9720b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
9730b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
9740b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
9750b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
9760b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
9770b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
9780b57cec5SDimitry Andric   MachineModuleInfo &MMI = MF.getMMI();
9790b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9800b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
9810b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
9820b57cec5SDimitry Andric   bool IsFunclet = MBB.isEHFuncletEntry();
9830b57cec5SDimitry Andric   EHPersonality Personality = EHPersonality::Unknown;
9840b57cec5SDimitry Andric   if (Fn.hasPersonalityFn())
9850b57cec5SDimitry Andric     Personality = classifyEHPersonality(Fn.getPersonalityFn());
9860b57cec5SDimitry Andric   bool FnHasClrFunclet =
9870b57cec5SDimitry Andric       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
9880b57cec5SDimitry Andric   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
9890b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
9900b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
9910b57cec5SDimitry Andric   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
9920b57cec5SDimitry Andric   // FIXME: Emit FPO data for EH funclets.
9930b57cec5SDimitry Andric   bool NeedsWinFPO =
9940b57cec5SDimitry Andric       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
9950b57cec5SDimitry Andric   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
9960b57cec5SDimitry Andric   bool NeedsDwarfCFI =
9970b57cec5SDimitry Andric       !IsWin64Prologue && (MMI.hasDebugInfo() || Fn.needsUnwindTableEntry());
998*8bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
999*8bcb0991SDimitry Andric   const Register MachineFramePtr =
10000b57cec5SDimitry Andric       STI.isTarget64BitILP32()
1001*8bcb0991SDimitry Andric           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
1002*8bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
10030b57cec5SDimitry Andric   bool HasWinCFI = false;
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   // Debug location must be unknown since the first debug location is used
10060b57cec5SDimitry Andric   // to determine the end of the prologue.
10070b57cec5SDimitry Andric   DebugLoc DL;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   // Add RETADDR move area to callee saved frame size.
10100b57cec5SDimitry Andric   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
10110b57cec5SDimitry Andric   if (TailCallReturnAddrDelta && IsWin64Prologue)
10120b57cec5SDimitry Andric     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0)
10150b57cec5SDimitry Andric     X86FI->setCalleeSavedFrameSize(
10160b57cec5SDimitry Andric       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   bool UseStackProbe = !STI.getTargetLowering()->getStackProbeSymbolName(MF).empty();
1019*8bcb0991SDimitry Andric   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
10220b57cec5SDimitry Andric   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
10230b57cec5SDimitry Andric   // stack alignment.
10240b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
10250b57cec5SDimitry Andric       Fn.arg_size() == 2) {
10260b57cec5SDimitry Andric     StackSize += 8;
10270b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
10280b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -8, /*InEpilogue=*/false);
10290b57cec5SDimitry Andric   }
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
10320b57cec5SDimitry Andric   // function, and use up to 128 bytes of stack space, don't have a frame
10330b57cec5SDimitry Andric   // pointer, calls, or dynamic alloca then we do not need to adjust the
10340b57cec5SDimitry Andric   // stack pointer (we fit in the Red Zone). We also check that we don't
10350b57cec5SDimitry Andric   // push and pop from the stack.
10360b57cec5SDimitry Andric   if (has128ByteRedZone(MF) &&
10370b57cec5SDimitry Andric       !TRI->needsStackRealignment(MF) &&
10380b57cec5SDimitry Andric       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
10390b57cec5SDimitry Andric       !MFI.adjustsStack() &&                   // No calls.
10400b57cec5SDimitry Andric       !UseStackProbe &&                        // No stack probes.
10410b57cec5SDimitry Andric       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
10420b57cec5SDimitry Andric       !MF.shouldSplitStack()) {                // Regular stack
10430b57cec5SDimitry Andric     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
10440b57cec5SDimitry Andric     if (HasFP) MinSize += SlotSize;
10450b57cec5SDimitry Andric     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
10460b57cec5SDimitry Andric     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
10470b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   // Insert stack pointer adjustment for later moving of return addr.  Only
10510b57cec5SDimitry Andric   // applies to tail call optimized functions where the callee argument stack
10520b57cec5SDimitry Andric   // size is bigger than the callers.
10530b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0) {
10540b57cec5SDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
10550b57cec5SDimitry Andric                          /*InEpilogue=*/false)
10560b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
10570b57cec5SDimitry Andric   }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   // Mapping for machine moves:
10600b57cec5SDimitry Andric   //
10610b57cec5SDimitry Andric   //   DST: VirtualFP AND
10620b57cec5SDimitry Andric   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
10630b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_def_cfa
10640b57cec5SDimitry Andric   //
10650b57cec5SDimitry Andric   //   SRC: VirtualFP AND
10660b57cec5SDimitry Andric   //        DST: Register               => DW_CFA_def_cfa_register
10670b57cec5SDimitry Andric   //
10680b57cec5SDimitry Andric   //   ELSE
10690b57cec5SDimitry Andric   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
10700b57cec5SDimitry Andric   //        REG < 64                    => DW_CFA_offset + Reg
10710b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_offset_extended
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric   uint64_t NumBytes = 0;
10740b57cec5SDimitry Andric   int stackGrowth = -SlotSize;
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   // Find the funclet establisher parameter
1077*8bcb0991SDimitry Andric   Register Establisher = X86::NoRegister;
10780b57cec5SDimitry Andric   if (IsClrFunclet)
10790b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
10800b57cec5SDimitry Andric   else if (IsFunclet)
10810b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
10840b57cec5SDimitry Andric     // Immediately spill establisher into the home slot.
10850b57cec5SDimitry Andric     // The runtime cares about this.
10860b57cec5SDimitry Andric     // MOV64mr %rdx, 16(%rsp)
10870b57cec5SDimitry Andric     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
10880b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
10890b57cec5SDimitry Andric         .addReg(Establisher)
10900b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
10910b57cec5SDimitry Andric     MBB.addLiveIn(Establisher);
10920b57cec5SDimitry Andric   }
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric   if (HasFP) {
10950b57cec5SDimitry Andric     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     // Calculate required stack adjustment.
10980b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
10990b57cec5SDimitry Andric     // If required, include space for extra hidden slot for stashing base pointer.
11000b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
11010b57cec5SDimitry Andric       FrameSize += SlotSize;
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric     // Callee-saved registers are pushed on stack before the stack is realigned.
11060b57cec5SDimitry Andric     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
11070b57cec5SDimitry Andric       NumBytes = alignTo(NumBytes, MaxAlign);
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric     // Save EBP/RBP into the appropriate stack slot.
11100b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
11110b57cec5SDimitry Andric       .addReg(MachineFramePtr, RegState::Kill)
11120b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
11150b57cec5SDimitry Andric       // Mark the place where EBP/RBP was saved.
11160b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
11170b57cec5SDimitry Andric       assert(StackSize);
11180b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
11190b57cec5SDimitry Andric                MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric       // Change the rule for the FramePtr to be an "offset" rule.
11220b57cec5SDimitry Andric       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
11230b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
11240b57cec5SDimitry Andric                                   nullptr, DwarfFramePtr, 2 * stackGrowth));
11250b57cec5SDimitry Andric     }
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric     if (NeedsWinCFI) {
11280b57cec5SDimitry Andric       HasWinCFI = true;
11290b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
11300b57cec5SDimitry Andric           .addImm(FramePtr)
11310b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
11320b57cec5SDimitry Andric     }
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric     if (!IsWin64Prologue && !IsFunclet) {
11350b57cec5SDimitry Andric       // Update EBP with the new base value.
11360b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL,
11370b57cec5SDimitry Andric               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
11380b57cec5SDimitry Andric               FramePtr)
11390b57cec5SDimitry Andric           .addReg(StackPtr)
11400b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric       if (NeedsDwarfCFI) {
11430b57cec5SDimitry Andric         // Mark effective beginning of when frame pointer becomes valid.
11440b57cec5SDimitry Andric         // Define the current CFA to use the EBP/RBP register.
11450b57cec5SDimitry Andric         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
11460b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
11470b57cec5SDimitry Andric                                     nullptr, DwarfFramePtr));
11480b57cec5SDimitry Andric       }
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric       if (NeedsWinFPO) {
11510b57cec5SDimitry Andric         // .cv_fpo_setframe $FramePtr
11520b57cec5SDimitry Andric         HasWinCFI = true;
11530b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
11540b57cec5SDimitry Andric             .addImm(FramePtr)
11550b57cec5SDimitry Andric             .addImm(0)
11560b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
11570b57cec5SDimitry Andric       }
11580b57cec5SDimitry Andric     }
11590b57cec5SDimitry Andric   } else {
11600b57cec5SDimitry Andric     assert(!IsFunclet && "funclets without FPs not yet implemented");
11610b57cec5SDimitry Andric     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
11620b57cec5SDimitry Andric   }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // Update the offset adjustment, which is mainly used by codeview to translate
11650b57cec5SDimitry Andric   // from ESP to VFRAME relative local variable offsets.
11660b57cec5SDimitry Andric   if (!IsFunclet) {
11670b57cec5SDimitry Andric     if (HasFP && TRI->needsStackRealignment(MF))
11680b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-NumBytes);
11690b57cec5SDimitry Andric     else
11700b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-StackSize);
11710b57cec5SDimitry Andric   }
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   // For EH funclets, only allocate enough space for outgoing calls. Save the
11740b57cec5SDimitry Andric   // NumBytes value that we would've used for the parent frame.
11750b57cec5SDimitry Andric   unsigned ParentFrameNumBytes = NumBytes;
11760b57cec5SDimitry Andric   if (IsFunclet)
11770b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   // Skip the callee-saved push instructions.
11800b57cec5SDimitry Andric   bool PushedRegs = false;
11810b57cec5SDimitry Andric   int StackOffset = 2 * stackGrowth;
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric   while (MBBI != MBB.end() &&
11840b57cec5SDimitry Andric          MBBI->getFlag(MachineInstr::FrameSetup) &&
11850b57cec5SDimitry Andric          (MBBI->getOpcode() == X86::PUSH32r ||
11860b57cec5SDimitry Andric           MBBI->getOpcode() == X86::PUSH64r)) {
11870b57cec5SDimitry Andric     PushedRegs = true;
1188*8bcb0991SDimitry Andric     Register Reg = MBBI->getOperand(0).getReg();
11890b57cec5SDimitry Andric     ++MBBI;
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
11920b57cec5SDimitry Andric       // Mark callee-saved push instruction.
11930b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
11940b57cec5SDimitry Andric       assert(StackSize);
11950b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
11960b57cec5SDimitry Andric                MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
11970b57cec5SDimitry Andric       StackOffset += stackGrowth;
11980b57cec5SDimitry Andric     }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric     if (NeedsWinCFI) {
12010b57cec5SDimitry Andric       HasWinCFI = true;
12020b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
12030b57cec5SDimitry Andric           .addImm(Reg)
12040b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
12050b57cec5SDimitry Andric     }
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   // Realign stack after we pushed callee-saved registers (so that we'll be
12090b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
12100b57cec5SDimitry Andric   // Don't do this for Win64, it needs to realign the stack after the prologue.
12110b57cec5SDimitry Andric   if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
12120b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
12130b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric     if (NeedsWinCFI) {
12160b57cec5SDimitry Andric       HasWinCFI = true;
12170b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
12180b57cec5SDimitry Andric           .addImm(MaxAlign)
12190b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
12200b57cec5SDimitry Andric     }
12210b57cec5SDimitry Andric   }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // If there is an SUB32ri of ESP immediately before this instruction, merge
12240b57cec5SDimitry Andric   // the two. This can be the case when tail call elimination is enabled and
12250b57cec5SDimitry Andric   // the callee has more arguments then the caller.
12260b57cec5SDimitry Andric   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric   // Adjust stack pointer: ESP -= numbytes.
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Windows and cygwin/mingw require a prologue helper routine when allocating
12310b57cec5SDimitry Andric   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
12320b57cec5SDimitry Andric   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
12330b57cec5SDimitry Andric   // stack and adjust the stack pointer in one go.  The 64-bit version of
12340b57cec5SDimitry Andric   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
12350b57cec5SDimitry Andric   // responsible for adjusting the stack pointer.  Touching the stack at 4K
12360b57cec5SDimitry Andric   // increments is necessary to ensure that the guard pages used by the OS
12370b57cec5SDimitry Andric   // virtual memory manager are allocated in correct sequence.
12380b57cec5SDimitry Andric   uint64_t AlignedNumBytes = NumBytes;
12390b57cec5SDimitry Andric   if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
12400b57cec5SDimitry Andric     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
12410b57cec5SDimitry Andric   if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
12420b57cec5SDimitry Andric     assert(!X86FI->getUsesRedZone() &&
12430b57cec5SDimitry Andric            "The Red Zone is not accounted for in stack probes");
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric     // Check whether EAX is livein for this block.
12460b57cec5SDimitry Andric     bool isEAXAlive = isEAXLiveIn(MBB);
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric     if (isEAXAlive) {
12490b57cec5SDimitry Andric       if (Is64Bit) {
12500b57cec5SDimitry Andric         // Save RAX
12510b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
12520b57cec5SDimitry Andric           .addReg(X86::RAX, RegState::Kill)
12530b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
12540b57cec5SDimitry Andric       } else {
12550b57cec5SDimitry Andric         // Save EAX
12560b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
12570b57cec5SDimitry Andric           .addReg(X86::EAX, RegState::Kill)
12580b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
12590b57cec5SDimitry Andric       }
12600b57cec5SDimitry Andric     }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric     if (Is64Bit) {
12630b57cec5SDimitry Andric       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
12640b57cec5SDimitry Andric       // Function prologue is responsible for adjusting the stack pointer.
12650b57cec5SDimitry Andric       int Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
12660b57cec5SDimitry Andric       if (isUInt<32>(Alloc)) {
12670b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
12680b57cec5SDimitry Andric             .addImm(Alloc)
12690b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
12700b57cec5SDimitry Andric       } else if (isInt<32>(Alloc)) {
12710b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
12720b57cec5SDimitry Andric             .addImm(Alloc)
12730b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
12740b57cec5SDimitry Andric       } else {
12750b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
12760b57cec5SDimitry Andric             .addImm(Alloc)
12770b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
12780b57cec5SDimitry Andric       }
12790b57cec5SDimitry Andric     } else {
12800b57cec5SDimitry Andric       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
12810b57cec5SDimitry Andric       // We'll also use 4 already allocated bytes for EAX.
12820b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
12830b57cec5SDimitry Andric           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
12840b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
12850b57cec5SDimitry Andric     }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric     // Call __chkstk, __chkstk_ms, or __alloca.
12880b57cec5SDimitry Andric     emitStackProbe(MF, MBB, MBBI, DL, true);
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric     if (isEAXAlive) {
12910b57cec5SDimitry Andric       // Restore RAX/EAX
12920b57cec5SDimitry Andric       MachineInstr *MI;
12930b57cec5SDimitry Andric       if (Is64Bit)
12940b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
12950b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 8);
12960b57cec5SDimitry Andric       else
12970b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
12980b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 4);
12990b57cec5SDimitry Andric       MI->setFlag(MachineInstr::FrameSetup);
13000b57cec5SDimitry Andric       MBB.insert(MBBI, MI);
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric   } else if (NumBytes) {
13030b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   if (NeedsWinCFI && NumBytes) {
13070b57cec5SDimitry Andric     HasWinCFI = true;
13080b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
13090b57cec5SDimitry Andric         .addImm(NumBytes)
13100b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
13110b57cec5SDimitry Andric   }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   int SEHFrameOffset = 0;
13140b57cec5SDimitry Andric   unsigned SPOrEstablisher;
13150b57cec5SDimitry Andric   if (IsFunclet) {
13160b57cec5SDimitry Andric     if (IsClrFunclet) {
13170b57cec5SDimitry Andric       // The establisher parameter passed to a CLR funclet is actually a pointer
13180b57cec5SDimitry Andric       // to the (mostly empty) frame of its nearest enclosing funclet; we have
13190b57cec5SDimitry Andric       // to find the root function establisher frame by loading the PSPSym from
13200b57cec5SDimitry Andric       // the intermediate frame.
13210b57cec5SDimitry Andric       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
13220b57cec5SDimitry Andric       MachinePointerInfo NoInfo;
13230b57cec5SDimitry Andric       MBB.addLiveIn(Establisher);
13240b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
13250b57cec5SDimitry Andric                    Establisher, false, PSPSlotOffset)
13260b57cec5SDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
13270b57cec5SDimitry Andric               NoInfo, MachineMemOperand::MOLoad, SlotSize, SlotSize));
13280b57cec5SDimitry Andric       ;
13290b57cec5SDimitry Andric       // Save the root establisher back into the current funclet's (mostly
13300b57cec5SDimitry Andric       // empty) frame, in case a sub-funclet or the GC needs it.
13310b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
13320b57cec5SDimitry Andric                    false, PSPSlotOffset)
13330b57cec5SDimitry Andric           .addReg(Establisher)
13340b57cec5SDimitry Andric           .addMemOperand(
13350b57cec5SDimitry Andric               MF.getMachineMemOperand(NoInfo, MachineMemOperand::MOStore |
13360b57cec5SDimitry Andric                                                   MachineMemOperand::MOVolatile,
13370b57cec5SDimitry Andric                                       SlotSize, SlotSize));
13380b57cec5SDimitry Andric     }
13390b57cec5SDimitry Andric     SPOrEstablisher = Establisher;
13400b57cec5SDimitry Andric   } else {
13410b57cec5SDimitry Andric     SPOrEstablisher = StackPtr;
13420b57cec5SDimitry Andric   }
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric   if (IsWin64Prologue && HasFP) {
13450b57cec5SDimitry Andric     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
13460b57cec5SDimitry Andric     // this calculation on the incoming establisher, which holds the value of
13470b57cec5SDimitry Andric     // RSP from the parent frame at the end of the prologue.
13480b57cec5SDimitry Andric     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
13490b57cec5SDimitry Andric     if (SEHFrameOffset)
13500b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
13510b57cec5SDimitry Andric                    SPOrEstablisher, false, SEHFrameOffset);
13520b57cec5SDimitry Andric     else
13530b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
13540b57cec5SDimitry Andric           .addReg(SPOrEstablisher);
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric     // If this is not a funclet, emit the CFI describing our frame pointer.
13570b57cec5SDimitry Andric     if (NeedsWinCFI && !IsFunclet) {
13580b57cec5SDimitry Andric       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
13590b57cec5SDimitry Andric       HasWinCFI = true;
13600b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
13610b57cec5SDimitry Andric           .addImm(FramePtr)
13620b57cec5SDimitry Andric           .addImm(SEHFrameOffset)
13630b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
13640b57cec5SDimitry Andric       if (isAsynchronousEHPersonality(Personality))
13650b57cec5SDimitry Andric         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
13660b57cec5SDimitry Andric     }
13670b57cec5SDimitry Andric   } else if (IsFunclet && STI.is32Bit()) {
13680b57cec5SDimitry Andric     // Reset EBP / ESI to something good for funclets.
13690b57cec5SDimitry Andric     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
13700b57cec5SDimitry Andric     // If we're a catch funclet, we can be returned to via catchret. Save ESP
13710b57cec5SDimitry Andric     // into the registration node so that the runtime will restore it for us.
13720b57cec5SDimitry Andric     if (!MBB.isCleanupFuncletEntry()) {
13730b57cec5SDimitry Andric       assert(Personality == EHPersonality::MSVC_CXX);
13740b57cec5SDimitry Andric       unsigned FrameReg;
13750b57cec5SDimitry Andric       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
13760b57cec5SDimitry Andric       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
13770b57cec5SDimitry Andric       // ESP is the first field, so no extra displacement is needed.
13780b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
13790b57cec5SDimitry Andric                    false, EHRegOffset)
13800b57cec5SDimitry Andric           .addReg(X86::ESP);
13810b57cec5SDimitry Andric     }
13820b57cec5SDimitry Andric   }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
13850b57cec5SDimitry Andric     const MachineInstr &FrameInstr = *MBBI;
13860b57cec5SDimitry Andric     ++MBBI;
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric     if (NeedsWinCFI) {
13890b57cec5SDimitry Andric       int FI;
13900b57cec5SDimitry Andric       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
13910b57cec5SDimitry Andric         if (X86::FR64RegClass.contains(Reg)) {
1392c14a5a88SDimitry Andric           int Offset;
13930b57cec5SDimitry Andric           unsigned IgnoredFrameReg;
1394c14a5a88SDimitry Andric           if (IsWin64Prologue && IsFunclet)
1395c14a5a88SDimitry Andric             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
1396c14a5a88SDimitry Andric           else
1397c14a5a88SDimitry Andric             Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg) +
1398c14a5a88SDimitry Andric                      SEHFrameOffset;
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric           HasWinCFI = true;
14010b57cec5SDimitry Andric           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
14020b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
14030b57cec5SDimitry Andric               .addImm(Reg)
14040b57cec5SDimitry Andric               .addImm(Offset)
14050b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
14060b57cec5SDimitry Andric         }
14070b57cec5SDimitry Andric       }
14080b57cec5SDimitry Andric     }
14090b57cec5SDimitry Andric   }
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   if (NeedsWinCFI && HasWinCFI)
14120b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
14130b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   if (FnHasClrFunclet && !IsFunclet) {
14160b57cec5SDimitry Andric     // Save the so-called Initial-SP (i.e. the value of the stack pointer
14170b57cec5SDimitry Andric     // immediately after the prolog)  into the PSPSlot so that funclets
14180b57cec5SDimitry Andric     // and the GC can recover it.
14190b57cec5SDimitry Andric     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
14200b57cec5SDimitry Andric     auto PSPInfo = MachinePointerInfo::getFixedStack(
14210b57cec5SDimitry Andric         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
14220b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
14230b57cec5SDimitry Andric                  PSPSlotOffset)
14240b57cec5SDimitry Andric         .addReg(StackPtr)
14250b57cec5SDimitry Andric         .addMemOperand(MF.getMachineMemOperand(
14260b57cec5SDimitry Andric             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
14270b57cec5SDimitry Andric             SlotSize, SlotSize));
14280b57cec5SDimitry Andric   }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   // Realign stack after we spilled callee-saved registers (so that we'll be
14310b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
14320b57cec5SDimitry Andric   // Win64 requires aligning the stack after the prologue.
14330b57cec5SDimitry Andric   if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
14340b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
14350b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
14360b57cec5SDimitry Andric   }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // We already dealt with stack realignment and funclets above.
14390b57cec5SDimitry Andric   if (IsFunclet && STI.is32Bit())
14400b57cec5SDimitry Andric     return;
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
14430b57cec5SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
14440b57cec5SDimitry Andric   // will be allocated after this, so we can still use the base pointer
14450b57cec5SDimitry Andric   // to reference locals.
14460b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
14470b57cec5SDimitry Andric     // Update the base pointer with the current stack pointer.
14480b57cec5SDimitry Andric     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
14490b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
14500b57cec5SDimitry Andric       .addReg(SPOrEstablisher)
14510b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
14520b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer()) {
14530b57cec5SDimitry Andric       // Stash value of base pointer.  Saving RSP instead of EBP shortens
14540b57cec5SDimitry Andric       // dependence chain. Used by SjLj EH.
14550b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
14560b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
14570b57cec5SDimitry Andric                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
14580b57cec5SDimitry Andric         .addReg(SPOrEstablisher)
14590b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
14600b57cec5SDimitry Andric     }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
14630b57cec5SDimitry Andric       // Stash the value of the frame pointer relative to the base pointer for
14640b57cec5SDimitry Andric       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
14650b57cec5SDimitry Andric       // it recovers the frame pointer from the base pointer rather than the
14660b57cec5SDimitry Andric       // other way around.
14670b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
14680b57cec5SDimitry Andric       unsigned UsedReg;
14690b57cec5SDimitry Andric       int Offset =
14700b57cec5SDimitry Andric           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
14710b57cec5SDimitry Andric       assert(UsedReg == BasePtr);
14720b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
14730b57cec5SDimitry Andric           .addReg(FramePtr)
14740b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
14750b57cec5SDimitry Andric     }
14760b57cec5SDimitry Andric   }
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
14790b57cec5SDimitry Andric     // Mark end of stack pointer adjustment.
14800b57cec5SDimitry Andric     if (!HasFP && NumBytes) {
14810b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
14820b57cec5SDimitry Andric       assert(StackSize);
14830b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
14840b57cec5SDimitry Andric                                   nullptr, -StackSize + stackGrowth));
14850b57cec5SDimitry Andric     }
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric     // Emit DWARF info specifying the offsets of the callee-saved registers.
14880b57cec5SDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DL);
14890b57cec5SDimitry Andric   }
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   // X86 Interrupt handling function cannot assume anything about the direction
14920b57cec5SDimitry Andric   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
14930b57cec5SDimitry Andric   // in each prologue of interrupt handler function.
14940b57cec5SDimitry Andric   //
14950b57cec5SDimitry Andric   // FIXME: Create "cld" instruction only in these cases:
14960b57cec5SDimitry Andric   // 1. The interrupt handling function uses any of the "rep" instructions.
14970b57cec5SDimitry Andric   // 2. Interrupt handling function calls another function.
14980b57cec5SDimitry Andric   //
14990b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR)
15000b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
15010b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   // At this point we know if the function has WinCFI or not.
15040b57cec5SDimitry Andric   MF.setHasWinCFI(HasWinCFI);
15050b57cec5SDimitry Andric }
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric bool X86FrameLowering::canUseLEAForSPInEpilogue(
15080b57cec5SDimitry Andric     const MachineFunction &MF) const {
15090b57cec5SDimitry Andric   // We can't use LEA instructions for adjusting the stack pointer if we don't
15100b57cec5SDimitry Andric   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
15110b57cec5SDimitry Andric   // to deallocate the stack.
15120b57cec5SDimitry Andric   // This means that we can use LEA for SP in two situations:
15130b57cec5SDimitry Andric   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
15140b57cec5SDimitry Andric   // 2. We *have* a frame pointer which means we are permitted to use LEA.
15150b57cec5SDimitry Andric   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
15160b57cec5SDimitry Andric }
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric static bool isFuncletReturnInstr(MachineInstr &MI) {
15190b57cec5SDimitry Andric   switch (MI.getOpcode()) {
15200b57cec5SDimitry Andric   case X86::CATCHRET:
15210b57cec5SDimitry Andric   case X86::CLEANUPRET:
15220b57cec5SDimitry Andric     return true;
15230b57cec5SDimitry Andric   default:
15240b57cec5SDimitry Andric     return false;
15250b57cec5SDimitry Andric   }
15260b57cec5SDimitry Andric   llvm_unreachable("impossible");
15270b57cec5SDimitry Andric }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
15300b57cec5SDimitry Andric // stack. It holds a pointer to the bottom of the root function frame.  The
15310b57cec5SDimitry Andric // establisher frame pointer passed to a nested funclet may point to the
15320b57cec5SDimitry Andric // (mostly empty) frame of its parent funclet, but it will need to find
15330b57cec5SDimitry Andric // the frame of the root function to access locals.  To facilitate this,
15340b57cec5SDimitry Andric // every funclet copies the pointer to the bottom of the root function
15350b57cec5SDimitry Andric // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
15360b57cec5SDimitry Andric // same offset for the PSPSym in the root function frame that's used in the
15370b57cec5SDimitry Andric // funclets' frames allows each funclet to dynamically accept any ancestor
15380b57cec5SDimitry Andric // frame as its establisher argument (the runtime doesn't guarantee the
15390b57cec5SDimitry Andric // immediate parent for some reason lost to history), and also allows the GC,
15400b57cec5SDimitry Andric // which uses the PSPSym for some bookkeeping, to find it in any funclet's
15410b57cec5SDimitry Andric // frame with only a single offset reported for the entire method.
15420b57cec5SDimitry Andric unsigned
15430b57cec5SDimitry Andric X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
15440b57cec5SDimitry Andric   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
15450b57cec5SDimitry Andric   unsigned SPReg;
15460b57cec5SDimitry Andric   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
15470b57cec5SDimitry Andric                                               /*IgnoreSPUpdates*/ true);
15480b57cec5SDimitry Andric   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
15490b57cec5SDimitry Andric   return static_cast<unsigned>(Offset);
15500b57cec5SDimitry Andric }
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric unsigned
15530b57cec5SDimitry Andric X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
1554c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
15550b57cec5SDimitry Andric   // This is the size of the pushed CSRs.
1556c14a5a88SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1557c14a5a88SDimitry Andric   // This is the size of callee saved XMMs.
1558c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
1559c14a5a88SDimitry Andric   unsigned XMMSize = WinEHXMMSlotInfo.size() *
1560c14a5a88SDimitry Andric                      TRI->getSpillSize(X86::VR128RegClass);
15610b57cec5SDimitry Andric   // This is the amount of stack a funclet needs to allocate.
15620b57cec5SDimitry Andric   unsigned UsedSize;
15630b57cec5SDimitry Andric   EHPersonality Personality =
15640b57cec5SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn());
15650b57cec5SDimitry Andric   if (Personality == EHPersonality::CoreCLR) {
15660b57cec5SDimitry Andric     // CLR funclets need to hold enough space to include the PSPSym, at the
15670b57cec5SDimitry Andric     // same offset from the stack pointer (immediately after the prolog) as it
15680b57cec5SDimitry Andric     // resides at in the main function.
15690b57cec5SDimitry Andric     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
15700b57cec5SDimitry Andric   } else {
15710b57cec5SDimitry Andric     // Other funclets just need enough stack for outgoing call arguments.
15720b57cec5SDimitry Andric     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
15730b57cec5SDimitry Andric   }
15740b57cec5SDimitry Andric   // RBP is not included in the callee saved register block. After pushing RBP,
15750b57cec5SDimitry Andric   // everything is 16 byte aligned. Everything we allocate before an outgoing
15760b57cec5SDimitry Andric   // call must also be 16 byte aligned.
15770b57cec5SDimitry Andric   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlignment());
15780b57cec5SDimitry Andric   // Subtract out the size of the callee saved registers. This is how much stack
15790b57cec5SDimitry Andric   // each funclet will allocate.
1580c14a5a88SDimitry Andric   return FrameSizeMinusRBP + XMMSize - CSSize;
15810b57cec5SDimitry Andric }
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric static bool isTailCallOpcode(unsigned Opc) {
15840b57cec5SDimitry Andric     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
15850b57cec5SDimitry Andric         Opc == X86::TCRETURNmi ||
15860b57cec5SDimitry Andric         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
15870b57cec5SDimitry Andric         Opc == X86::TCRETURNmi64;
15880b57cec5SDimitry Andric }
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric void X86FrameLowering::emitEpilogue(MachineFunction &MF,
15910b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
15920b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
15930b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
15940b57cec5SDimitry Andric   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
15950b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = Terminator;
15960b57cec5SDimitry Andric   DebugLoc DL;
15970b57cec5SDimitry Andric   if (MBBI != MBB.end())
15980b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
15990b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
16000b57cec5SDimitry Andric   const bool Is64BitILP32 = STI.isTarget64BitILP32();
1601*8bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
16020b57cec5SDimitry Andric   unsigned MachineFramePtr =
1603*8bcb0991SDimitry Andric       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
16060b57cec5SDimitry Andric   bool NeedsWin64CFI =
16070b57cec5SDimitry Andric       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
16080b57cec5SDimitry Andric   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric   // Get the number of bytes to allocate from the FrameInfo.
16110b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
16120b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF);
16130b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
16140b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
16150b57cec5SDimitry Andric   uint64_t NumBytes = 0;
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   bool NeedsDwarfCFI =
16180b57cec5SDimitry Andric       (!MF.getTarget().getTargetTriple().isOSDarwin() &&
16190b57cec5SDimitry Andric        !MF.getTarget().getTargetTriple().isOSWindows()) &&
16200b57cec5SDimitry Andric       (MF.getMMI().hasDebugInfo() || MF.getFunction().needsUnwindTableEntry());
16210b57cec5SDimitry Andric 
16220b57cec5SDimitry Andric   if (IsFunclet) {
16230b57cec5SDimitry Andric     assert(HasFP && "EH funclets without FP not yet implemented");
16240b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
16250b57cec5SDimitry Andric   } else if (HasFP) {
16260b57cec5SDimitry Andric     // Calculate required stack adjustment.
16270b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
16280b57cec5SDimitry Andric     NumBytes = FrameSize - CSSize;
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric     // Callee-saved registers were pushed on stack before the stack was
16310b57cec5SDimitry Andric     // realigned.
16320b57cec5SDimitry Andric     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
16330b57cec5SDimitry Andric       NumBytes = alignTo(FrameSize, MaxAlign);
16340b57cec5SDimitry Andric   } else {
16350b57cec5SDimitry Andric     NumBytes = StackSize - CSSize;
16360b57cec5SDimitry Andric   }
16370b57cec5SDimitry Andric   uint64_t SEHStackAllocAmt = NumBytes;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   if (HasFP) {
16400b57cec5SDimitry Andric     // Pop EBP.
16410b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
16420b57cec5SDimitry Andric             MachineFramePtr)
16430b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
16440b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
16450b57cec5SDimitry Andric       unsigned DwarfStackPtr =
16460b57cec5SDimitry Andric           TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
16470b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfa(
16480b57cec5SDimitry Andric                                   nullptr, DwarfStackPtr, -SlotSize));
16490b57cec5SDimitry Andric       --MBBI;
16500b57cec5SDimitry Andric     }
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   MachineBasicBlock::iterator FirstCSPop = MBBI;
16540b57cec5SDimitry Andric   // Skip the callee-saved pop instructions.
16550b57cec5SDimitry Andric   while (MBBI != MBB.begin()) {
16560b57cec5SDimitry Andric     MachineBasicBlock::iterator PI = std::prev(MBBI);
16570b57cec5SDimitry Andric     unsigned Opc = PI->getOpcode();
16580b57cec5SDimitry Andric 
16590b57cec5SDimitry Andric     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
16600b57cec5SDimitry Andric       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
16610b57cec5SDimitry Andric           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)))
16620b57cec5SDimitry Andric         break;
16630b57cec5SDimitry Andric       FirstCSPop = PI;
16640b57cec5SDimitry Andric     }
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric     --MBBI;
16670b57cec5SDimitry Andric   }
16680b57cec5SDimitry Andric   MBBI = FirstCSPop;
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
16710b57cec5SDimitry Andric     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   if (MBBI != MBB.end())
16740b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   // If there is an ADD32ri or SUB32ri of ESP immediately before this
16770b57cec5SDimitry Andric   // instruction, merge the two instructions.
16780b57cec5SDimitry Andric   if (NumBytes || MFI.hasVarSizedObjects())
16790b57cec5SDimitry Andric     NumBytes += mergeSPUpdates(MBB, MBBI, true);
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   // If dynamic alloca is used, then reset esp to point to the last callee-saved
16820b57cec5SDimitry Andric   // slot before popping them off! Same applies for the case, when stack was
16830b57cec5SDimitry Andric   // realigned. Don't do this if this was a funclet epilogue, since the funclets
16840b57cec5SDimitry Andric   // will not do realignment or dynamic stack allocation.
16850b57cec5SDimitry Andric   if ((TRI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) &&
16860b57cec5SDimitry Andric       !IsFunclet) {
16870b57cec5SDimitry Andric     if (TRI->needsStackRealignment(MF))
16880b57cec5SDimitry Andric       MBBI = FirstCSPop;
16890b57cec5SDimitry Andric     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
16900b57cec5SDimitry Andric     uint64_t LEAAmount =
16910b57cec5SDimitry Andric         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric     // There are only two legal forms of epilogue:
16940b57cec5SDimitry Andric     // - add SEHAllocationSize, %rsp
16950b57cec5SDimitry Andric     // - lea SEHAllocationSize(%FramePtr), %rsp
16960b57cec5SDimitry Andric     //
16970b57cec5SDimitry Andric     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
16980b57cec5SDimitry Andric     // However, we may use this sequence if we have a frame pointer because the
16990b57cec5SDimitry Andric     // effects of the prologue can safely be undone.
17000b57cec5SDimitry Andric     if (LEAAmount != 0) {
17010b57cec5SDimitry Andric       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
17020b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
17030b57cec5SDimitry Andric                    FramePtr, false, LEAAmount);
17040b57cec5SDimitry Andric       --MBBI;
17050b57cec5SDimitry Andric     } else {
17060b57cec5SDimitry Andric       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
17070b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
17080b57cec5SDimitry Andric         .addReg(FramePtr);
17090b57cec5SDimitry Andric       --MBBI;
17100b57cec5SDimitry Andric     }
17110b57cec5SDimitry Andric   } else if (NumBytes) {
17120b57cec5SDimitry Andric     // Adjust stack pointer back: ESP += numbytes.
17130b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
17140b57cec5SDimitry Andric     if (!hasFP(MF) && NeedsDwarfCFI) {
17150b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
17160b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
17170b57cec5SDimitry Andric                                   nullptr, -CSSize - SlotSize));
17180b57cec5SDimitry Andric     }
17190b57cec5SDimitry Andric     --MBBI;
17200b57cec5SDimitry Andric   }
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   // Windows unwinder will not invoke function's exception handler if IP is
17230b57cec5SDimitry Andric   // either in prologue or in epilogue.  This behavior causes a problem when a
17240b57cec5SDimitry Andric   // call immediately precedes an epilogue, because the return address points
17250b57cec5SDimitry Andric   // into the epilogue.  To cope with that, we insert an epilogue marker here,
17260b57cec5SDimitry Andric   // then replace it with a 'nop' if it ends up immediately after a CALL in the
17270b57cec5SDimitry Andric   // final emitted code.
17280b57cec5SDimitry Andric   if (NeedsWin64CFI && MF.hasWinCFI())
17290b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   if (!hasFP(MF) && NeedsDwarfCFI) {
17320b57cec5SDimitry Andric     MBBI = FirstCSPop;
17330b57cec5SDimitry Andric     int64_t Offset = -CSSize - SlotSize;
17340b57cec5SDimitry Andric     // Mark callee-saved pop instruction.
17350b57cec5SDimitry Andric     // Define the current CFA rule to use the provided offset.
17360b57cec5SDimitry Andric     while (MBBI != MBB.end()) {
17370b57cec5SDimitry Andric       MachineBasicBlock::iterator PI = MBBI;
17380b57cec5SDimitry Andric       unsigned Opc = PI->getOpcode();
17390b57cec5SDimitry Andric       ++MBBI;
17400b57cec5SDimitry Andric       if (Opc == X86::POP32r || Opc == X86::POP64r) {
17410b57cec5SDimitry Andric         Offset += SlotSize;
17420b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
17430b57cec5SDimitry Andric                  MCCFIInstruction::createDefCfaOffset(nullptr, Offset));
17440b57cec5SDimitry Andric       }
17450b57cec5SDimitry Andric     }
17460b57cec5SDimitry Andric   }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
17490b57cec5SDimitry Andric     // Add the return addr area delta back since we are not tail calling.
17500b57cec5SDimitry Andric     int Offset = -1 * X86FI->getTCReturnAddrDelta();
17510b57cec5SDimitry Andric     assert(Offset >= 0 && "TCDelta should never be positive");
17520b57cec5SDimitry Andric     if (Offset) {
17530b57cec5SDimitry Andric       // Check for possible merge with preceding ADD instruction.
17540b57cec5SDimitry Andric       Offset += mergeSPUpdates(MBB, Terminator, true);
17550b57cec5SDimitry Andric       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
17560b57cec5SDimitry Andric     }
17570b57cec5SDimitry Andric   }
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
17610b57cec5SDimitry Andric                                              unsigned &FrameReg) const {
17620b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric   bool IsFixed = MFI.isFixedObjectIndex(FI);
17650b57cec5SDimitry Andric   // We can't calculate offset from frame pointer if the stack is realigned,
17660b57cec5SDimitry Andric   // so enforce usage of stack/base pointer.  The base pointer is used when we
17670b57cec5SDimitry Andric   // have dynamic allocas in addition to dynamic realignment.
17680b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF))
17690b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
17700b57cec5SDimitry Andric   else if (TRI->needsStackRealignment(MF))
17710b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
17720b57cec5SDimitry Andric   else
17730b57cec5SDimitry Andric     FrameReg = TRI->getFrameRegister(MF);
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric   // Offset will hold the offset from the stack pointer at function entry to the
17760b57cec5SDimitry Andric   // object.
17770b57cec5SDimitry Andric   // We need to factor in additional offsets applied during the prologue to the
17780b57cec5SDimitry Andric   // frame, base, and stack pointer depending on which is used.
17790b57cec5SDimitry Andric   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
17800b57cec5SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
17810b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
17820b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
17830b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
17840b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
17850b57cec5SDimitry Andric   int64_t FPDelta = 0;
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   // In an x86 interrupt, remove the offset we added to account for the return
17880b57cec5SDimitry Andric   // address from any stack object allocated in the caller's frame. Interrupts
17890b57cec5SDimitry Andric   // do not have a standard return address. Fixed objects in the current frame,
17900b57cec5SDimitry Andric   // such as SSE register spills, should not get this treatment.
17910b57cec5SDimitry Andric   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
17920b57cec5SDimitry Andric       Offset >= 0) {
17930b57cec5SDimitry Andric     Offset += getOffsetOfLocalArea();
17940b57cec5SDimitry Andric   }
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   if (IsWin64Prologue) {
17970b57cec5SDimitry Andric     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric     // Calculate required stack adjustment.
18000b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
18010b57cec5SDimitry Andric     // If required, include space for extra hidden slot for stashing base pointer.
18020b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
18030b57cec5SDimitry Andric       FrameSize += SlotSize;
18040b57cec5SDimitry Andric     uint64_t NumBytes = FrameSize - CSSize;
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
18070b57cec5SDimitry Andric     if (FI && FI == X86FI->getFAIndex())
18080b57cec5SDimitry Andric       return -SEHFrameOffset;
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric     // FPDelta is the offset from the "traditional" FP location of the old base
18110b57cec5SDimitry Andric     // pointer followed by return address and the location required by the
18120b57cec5SDimitry Andric     // restricted Win64 prologue.
18130b57cec5SDimitry Andric     // Add FPDelta to all offsets below that go through the frame pointer.
18140b57cec5SDimitry Andric     FPDelta = FrameSize - SEHFrameOffset;
18150b57cec5SDimitry Andric     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
18160b57cec5SDimitry Andric            "FPDelta isn't aligned per the Win64 ABI!");
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
18210b57cec5SDimitry Andric     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
18220b57cec5SDimitry Andric     if (FI < 0) {
18230b57cec5SDimitry Andric       // Skip the saved EBP.
18240b57cec5SDimitry Andric       return Offset + SlotSize + FPDelta;
18250b57cec5SDimitry Andric     } else {
18260b57cec5SDimitry Andric       assert((-(Offset + StackSize)) % MFI.getObjectAlignment(FI) == 0);
18270b57cec5SDimitry Andric       return Offset + StackSize;
18280b57cec5SDimitry Andric     }
18290b57cec5SDimitry Andric   } else if (TRI->needsStackRealignment(MF)) {
18300b57cec5SDimitry Andric     if (FI < 0) {
18310b57cec5SDimitry Andric       // Skip the saved EBP.
18320b57cec5SDimitry Andric       return Offset + SlotSize + FPDelta;
18330b57cec5SDimitry Andric     } else {
18340b57cec5SDimitry Andric       assert((-(Offset + StackSize)) % MFI.getObjectAlignment(FI) == 0);
18350b57cec5SDimitry Andric       return Offset + StackSize;
18360b57cec5SDimitry Andric     }
18370b57cec5SDimitry Andric     // FIXME: Support tail calls
18380b57cec5SDimitry Andric   } else {
18390b57cec5SDimitry Andric     if (!HasFP)
18400b57cec5SDimitry Andric       return Offset + StackSize;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric     // Skip the saved EBP.
18430b57cec5SDimitry Andric     Offset += SlotSize;
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric     // Skip the RETADDR move area
18460b57cec5SDimitry Andric     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
18470b57cec5SDimitry Andric     if (TailCallReturnAddrDelta < 0)
18480b57cec5SDimitry Andric       Offset -= TailCallReturnAddrDelta;
18490b57cec5SDimitry Andric   }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   return Offset + FPDelta;
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric 
1854c14a5a88SDimitry Andric int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF,
1855c14a5a88SDimitry Andric                                               int FI, unsigned &FrameReg) const {
1856c14a5a88SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
1857c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1858c14a5a88SDimitry Andric   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
1859c14a5a88SDimitry Andric   const auto it = WinEHXMMSlotInfo.find(FI);
1860c14a5a88SDimitry Andric 
1861c14a5a88SDimitry Andric   if (it == WinEHXMMSlotInfo.end())
1862c14a5a88SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
1863c14a5a88SDimitry Andric 
1864c14a5a88SDimitry Andric   FrameReg = TRI->getStackRegister();
1865*8bcb0991SDimitry Andric   return alignTo(MFI.getMaxCallFrameSize(), getStackAlignment()) + it->second;
1866c14a5a88SDimitry Andric }
1867c14a5a88SDimitry Andric 
18680b57cec5SDimitry Andric int X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF,
18690b57cec5SDimitry Andric                                                int FI, unsigned &FrameReg,
18700b57cec5SDimitry Andric                                                int Adjustment) const {
18710b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
18720b57cec5SDimitry Andric   FrameReg = TRI->getStackRegister();
18730b57cec5SDimitry Andric   return MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + Adjustment;
18740b57cec5SDimitry Andric }
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric int
18770b57cec5SDimitry Andric X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
18780b57cec5SDimitry Andric                                                  int FI, unsigned &FrameReg,
18790b57cec5SDimitry Andric                                                  bool IgnoreSPUpdates) const {
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
18820b57cec5SDimitry Andric   // Does not include any dynamic realign.
18830b57cec5SDimitry Andric   const uint64_t StackSize = MFI.getStackSize();
18840b57cec5SDimitry Andric   // LLVM arranges the stack as follows:
18850b57cec5SDimitry Andric   //   ...
18860b57cec5SDimitry Andric   //   ARG2
18870b57cec5SDimitry Andric   //   ARG1
18880b57cec5SDimitry Andric   //   RETADDR
18890b57cec5SDimitry Andric   //   PUSH RBP   <-- RBP points here
18900b57cec5SDimitry Andric   //   PUSH CSRs
18910b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (non-win64)
18920b57cec5SDimitry Andric   //   ...
18930b57cec5SDimitry Andric   //   STACK OBJECTS
18940b57cec5SDimitry Andric   //   ...        <-- RSP after prologue points here
18950b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (win64)
18960b57cec5SDimitry Andric   //
18970b57cec5SDimitry Andric   // if (hasVarSizedObjects()):
18980b57cec5SDimitry Andric   //   ...        <-- "base pointer" (ESI/RBX) points here
18990b57cec5SDimitry Andric   //   DYNAMIC ALLOCAS
19000b57cec5SDimitry Andric   //   ...        <-- RSP points here
19010b57cec5SDimitry Andric   //
19020b57cec5SDimitry Andric   // Case 1: In the simple case of no stack realignment and no dynamic
19030b57cec5SDimitry Andric   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
19040b57cec5SDimitry Andric   // with fixed offsets from RSP.
19050b57cec5SDimitry Andric   //
19060b57cec5SDimitry Andric   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
19070b57cec5SDimitry Andric   // stack objects are addressed with RBP and regular stack objects with RSP.
19080b57cec5SDimitry Andric   //
19090b57cec5SDimitry Andric   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
19100b57cec5SDimitry Andric   // to address stack arguments for outgoing calls and nothing else. The "base
19110b57cec5SDimitry Andric   // pointer" points to local variables, and RBP points to fixed objects.
19120b57cec5SDimitry Andric   //
19130b57cec5SDimitry Andric   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
19140b57cec5SDimitry Andric   // answer we give is relative to the SP after the prologue, and not the
19150b57cec5SDimitry Andric   // SP in the middle of the function.
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric   if (MFI.isFixedObjectIndex(FI) && TRI->needsStackRealignment(MF) &&
19180b57cec5SDimitry Andric       !STI.isTargetWin64())
19190b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   // If !hasReservedCallFrame the function might have SP adjustement in the
19220b57cec5SDimitry Andric   // body.  So, even though the offset is statically known, it depends on where
19230b57cec5SDimitry Andric   // we are in the function.
19240b57cec5SDimitry Andric   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
19250b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   // We don't handle tail calls, and shouldn't be seeing them either.
19280b57cec5SDimitry Andric   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
19290b57cec5SDimitry Andric          "we don't handle this case!");
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric   // This is how the math works out:
19320b57cec5SDimitry Andric   //
19330b57cec5SDimitry Andric   //  %rsp grows (i.e. gets lower) left to right. Each box below is
19340b57cec5SDimitry Andric   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
19350b57cec5SDimitry Andric   //  get to.
19360b57cec5SDimitry Andric   //
19370b57cec5SDimitry Andric   //    ----------------------------------
19380b57cec5SDimitry Andric   //    | BP | Obj0 | Obj1 | ... | ObjN |
19390b57cec5SDimitry Andric   //    ----------------------------------
19400b57cec5SDimitry Andric   //    ^    ^      ^                   ^
19410b57cec5SDimitry Andric   //    A    B      C                   E
19420b57cec5SDimitry Andric   //
19430b57cec5SDimitry Andric   // A is the incoming stack pointer.
19440b57cec5SDimitry Andric   // (B - A) is the local area offset (-8 for x86-64) [1]
19450b57cec5SDimitry Andric   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
19460b57cec5SDimitry Andric   //
19470b57cec5SDimitry Andric   // |(E - B)| is the StackSize (absolute value, positive).  For a
19480b57cec5SDimitry Andric   // stack that grown down, this works out to be (B - E). [3]
19490b57cec5SDimitry Andric   //
19500b57cec5SDimitry Andric   // E is also the value of %rsp after stack has been set up, and we
19510b57cec5SDimitry Andric   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
19520b57cec5SDimitry Andric   // (C - E) == (C - A) - (B - A) + (B - E)
19530b57cec5SDimitry Andric   //            { Using [1], [2] and [3] above }
19540b57cec5SDimitry Andric   //         == getObjectOffset - LocalAreaOffset + StackSize
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
19570b57cec5SDimitry Andric }
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric bool X86FrameLowering::assignCalleeSavedSpillSlots(
19600b57cec5SDimitry Andric     MachineFunction &MF, const TargetRegisterInfo *TRI,
19610b57cec5SDimitry Andric     std::vector<CalleeSavedInfo> &CSI) const {
19620b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
19630b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   unsigned CalleeSavedFrameSize = 0;
1966c14a5a88SDimitry Andric   unsigned XMMCalleeSavedFrameSize = 0;
1967c14a5a88SDimitry Andric   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
19680b57cec5SDimitry Andric   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
19710b57cec5SDimitry Andric 
19720b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0) {
19730b57cec5SDimitry Andric     // create RETURNADDR area
19740b57cec5SDimitry Andric     //   arg
19750b57cec5SDimitry Andric     //   arg
19760b57cec5SDimitry Andric     //   RETADDR
19770b57cec5SDimitry Andric     //   { ...
19780b57cec5SDimitry Andric     //     RETADDR area
19790b57cec5SDimitry Andric     //     ...
19800b57cec5SDimitry Andric     //   }
19810b57cec5SDimitry Andric     //   [EBP]
19820b57cec5SDimitry Andric     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
19830b57cec5SDimitry Andric                            TailCallReturnAddrDelta - SlotSize, true);
19840b57cec5SDimitry Andric   }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
19870b57cec5SDimitry Andric   if (this->TRI->hasBasePointer(MF)) {
19880b57cec5SDimitry Andric     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
19890b57cec5SDimitry Andric     if (MF.hasEHFunclets()) {
19900b57cec5SDimitry Andric       int FI = MFI.CreateSpillStackObject(SlotSize, SlotSize);
19910b57cec5SDimitry Andric       X86FI->setHasSEHFramePtrSave(true);
19920b57cec5SDimitry Andric       X86FI->setSEHFramePtrSaveIndex(FI);
19930b57cec5SDimitry Andric     }
19940b57cec5SDimitry Andric   }
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric   if (hasFP(MF)) {
19970b57cec5SDimitry Andric     // emitPrologue always spills frame register the first thing.
19980b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
19990b57cec5SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
20020b57cec5SDimitry Andric     // the frame register, we can delete it from CSI list and not have to worry
20030b57cec5SDimitry Andric     // about avoiding it later.
2004*8bcb0991SDimitry Andric     Register FPReg = TRI->getFrameRegister(MF);
20050b57cec5SDimitry Andric     for (unsigned i = 0; i < CSI.size(); ++i) {
20060b57cec5SDimitry Andric       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
20070b57cec5SDimitry Andric         CSI.erase(CSI.begin() + i);
20080b57cec5SDimitry Andric         break;
20090b57cec5SDimitry Andric       }
20100b57cec5SDimitry Andric     }
20110b57cec5SDimitry Andric   }
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   // Assign slots for GPRs. It increases frame size.
20140b57cec5SDimitry Andric   for (unsigned i = CSI.size(); i != 0; --i) {
20150b57cec5SDimitry Andric     unsigned Reg = CSI[i - 1].getReg();
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
20180b57cec5SDimitry Andric       continue;
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
20210b57cec5SDimitry Andric     CalleeSavedFrameSize += SlotSize;
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
20240b57cec5SDimitry Andric     CSI[i - 1].setFrameIdx(SlotIndex);
20250b57cec5SDimitry Andric   }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
20280b57cec5SDimitry Andric   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   // Assign slots for XMMs.
20310b57cec5SDimitry Andric   for (unsigned i = CSI.size(); i != 0; --i) {
20320b57cec5SDimitry Andric     unsigned Reg = CSI[i - 1].getReg();
20330b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
20340b57cec5SDimitry Andric       continue;
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
20370b57cec5SDimitry Andric     MVT VT = MVT::Other;
20380b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
20390b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
20420b57cec5SDimitry Andric     unsigned Size = TRI->getSpillSize(*RC);
20430b57cec5SDimitry Andric     unsigned Align = TRI->getSpillAlignment(*RC);
20440b57cec5SDimitry Andric     // ensure alignment
2045c14a5a88SDimitry Andric     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
2046c14a5a88SDimitry Andric     SpillSlotOffset = -alignTo(-SpillSlotOffset, Align);
2047c14a5a88SDimitry Andric 
20480b57cec5SDimitry Andric     // spill into slot
20490b57cec5SDimitry Andric     SpillSlotOffset -= Size;
20500b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
20510b57cec5SDimitry Andric     CSI[i - 1].setFrameIdx(SlotIndex);
20520b57cec5SDimitry Andric     MFI.ensureMaxAlignment(Align);
2053c14a5a88SDimitry Andric 
2054c14a5a88SDimitry Andric     // Save the start offset and size of XMM in stack frame for funclets.
2055c14a5a88SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
2056c14a5a88SDimitry Andric       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2057c14a5a88SDimitry Andric       XMMCalleeSavedFrameSize += Size;
2058c14a5a88SDimitry Andric     }
20590b57cec5SDimitry Andric   }
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric   return true;
20620b57cec5SDimitry Andric }
20630b57cec5SDimitry Andric 
20640b57cec5SDimitry Andric bool X86FrameLowering::spillCalleeSavedRegisters(
20650b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
20660b57cec5SDimitry Andric     const std::vector<CalleeSavedInfo> &CSI,
20670b57cec5SDimitry Andric     const TargetRegisterInfo *TRI) const {
20680b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
20710b57cec5SDimitry Andric   // for us, and there are no XMM CSRs on Win32.
20720b57cec5SDimitry Andric   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
20730b57cec5SDimitry Andric     return true;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   // Push GPRs. It increases frame size.
20760b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
20770b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
20780b57cec5SDimitry Andric   for (unsigned i = CSI.size(); i != 0; --i) {
20790b57cec5SDimitry Andric     unsigned Reg = CSI[i - 1].getReg();
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
20820b57cec5SDimitry Andric       continue;
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
20850b57cec5SDimitry Andric     bool isLiveIn = MRI.isLiveIn(Reg);
20860b57cec5SDimitry Andric     if (!isLiveIn)
20870b57cec5SDimitry Andric       MBB.addLiveIn(Reg);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric     // Decide whether we can add a kill flag to the use.
20900b57cec5SDimitry Andric     bool CanKill = !isLiveIn;
20910b57cec5SDimitry Andric     // Check if any subregister is live-in
20920b57cec5SDimitry Andric     if (CanKill) {
20930b57cec5SDimitry Andric       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
20940b57cec5SDimitry Andric         if (MRI.isLiveIn(*AReg)) {
20950b57cec5SDimitry Andric           CanKill = false;
20960b57cec5SDimitry Andric           break;
20970b57cec5SDimitry Andric         }
20980b57cec5SDimitry Andric       }
20990b57cec5SDimitry Andric     }
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric     // Do not set a kill flag on values that are also marked as live-in. This
21020b57cec5SDimitry Andric     // happens with the @llvm-returnaddress intrinsic and with arguments
21030b57cec5SDimitry Andric     // passed in callee saved registers.
21040b57cec5SDimitry Andric     // Omitting the kill flags is conservatively correct even if the live-in
21050b57cec5SDimitry Andric     // is not used after all.
21060b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
21070b57cec5SDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
21080b57cec5SDimitry Andric   }
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
21110b57cec5SDimitry Andric   // It can be done by spilling XMMs to stack frame.
21120b57cec5SDimitry Andric   for (unsigned i = CSI.size(); i != 0; --i) {
21130b57cec5SDimitry Andric     unsigned Reg = CSI[i-1].getReg();
21140b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
21150b57cec5SDimitry Andric       continue;
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
21180b57cec5SDimitry Andric     MVT VT = MVT::Other;
21190b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
21200b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
21210b57cec5SDimitry Andric 
21220b57cec5SDimitry Andric     // Add the callee-saved register as live-in. It's killed at the spill.
21230b57cec5SDimitry Andric     MBB.addLiveIn(Reg);
21240b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
21270b57cec5SDimitry Andric                             TRI);
21280b57cec5SDimitry Andric     --MI;
21290b57cec5SDimitry Andric     MI->setFlag(MachineInstr::FrameSetup);
21300b57cec5SDimitry Andric     ++MI;
21310b57cec5SDimitry Andric   }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   return true;
21340b57cec5SDimitry Andric }
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
21370b57cec5SDimitry Andric                                                MachineBasicBlock::iterator MBBI,
21380b57cec5SDimitry Andric                                                MachineInstr *CatchRet) const {
21390b57cec5SDimitry Andric   // SEH shouldn't use catchret.
21400b57cec5SDimitry Andric   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
21410b57cec5SDimitry Andric              MBB.getParent()->getFunction().getPersonalityFn())) &&
21420b57cec5SDimitry Andric          "SEH should not use CATCHRET");
21430b57cec5SDimitry Andric   DebugLoc DL = CatchRet->getDebugLoc();
21440b57cec5SDimitry Andric   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   // Fill EAX/RAX with the address of the target block.
21470b57cec5SDimitry Andric   if (STI.is64Bit()) {
21480b57cec5SDimitry Andric     // LEA64r CatchRetTarget(%rip), %rax
21490b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
21500b57cec5SDimitry Andric         .addReg(X86::RIP)
21510b57cec5SDimitry Andric         .addImm(0)
21520b57cec5SDimitry Andric         .addReg(0)
21530b57cec5SDimitry Andric         .addMBB(CatchRetTarget)
21540b57cec5SDimitry Andric         .addReg(0);
21550b57cec5SDimitry Andric   } else {
21560b57cec5SDimitry Andric     // MOV32ri $CatchRetTarget, %eax
21570b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
21580b57cec5SDimitry Andric         .addMBB(CatchRetTarget);
21590b57cec5SDimitry Andric   }
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric   // Record that we've taken the address of CatchRetTarget and no longer just
21620b57cec5SDimitry Andric   // reference it in a terminator.
21630b57cec5SDimitry Andric   CatchRetTarget->setHasAddressTaken();
21640b57cec5SDimitry Andric }
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
21670b57cec5SDimitry Andric                                                MachineBasicBlock::iterator MI,
21680b57cec5SDimitry Andric                                           std::vector<CalleeSavedInfo> &CSI,
21690b57cec5SDimitry Andric                                           const TargetRegisterInfo *TRI) const {
21700b57cec5SDimitry Andric   if (CSI.empty())
21710b57cec5SDimitry Andric     return false;
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
21740b57cec5SDimitry Andric     // Don't restore CSRs in 32-bit EH funclets. Matches
21750b57cec5SDimitry Andric     // spillCalleeSavedRegisters.
21760b57cec5SDimitry Andric     if (STI.is32Bit())
21770b57cec5SDimitry Andric       return true;
21780b57cec5SDimitry Andric     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
21790b57cec5SDimitry Andric     // funclets. emitEpilogue transforms these to normal jumps.
21800b57cec5SDimitry Andric     if (MI->getOpcode() == X86::CATCHRET) {
21810b57cec5SDimitry Andric       const Function &F = MBB.getParent()->getFunction();
21820b57cec5SDimitry Andric       bool IsSEH = isAsynchronousEHPersonality(
21830b57cec5SDimitry Andric           classifyEHPersonality(F.getPersonalityFn()));
21840b57cec5SDimitry Andric       if (IsSEH)
21850b57cec5SDimitry Andric         return true;
21860b57cec5SDimitry Andric     }
21870b57cec5SDimitry Andric   }
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   // Reload XMMs from stack frame.
21920b57cec5SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
21930b57cec5SDimitry Andric     unsigned Reg = CSI[i].getReg();
21940b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) ||
21950b57cec5SDimitry Andric         X86::GR32RegClass.contains(Reg))
21960b57cec5SDimitry Andric       continue;
21970b57cec5SDimitry Andric 
21980b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
21990b57cec5SDimitry Andric     MVT VT = MVT::Other;
22000b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
22010b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
22040b57cec5SDimitry Andric     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
22050b57cec5SDimitry Andric   }
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // POP GPRs.
22080b57cec5SDimitry Andric   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
22090b57cec5SDimitry Andric   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
22100b57cec5SDimitry Andric     unsigned Reg = CSI[i].getReg();
22110b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) &&
22120b57cec5SDimitry Andric         !X86::GR32RegClass.contains(Reg))
22130b57cec5SDimitry Andric       continue;
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
22160b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
22170b57cec5SDimitry Andric   }
22180b57cec5SDimitry Andric   return true;
22190b57cec5SDimitry Andric }
22200b57cec5SDimitry Andric 
22210b57cec5SDimitry Andric void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
22220b57cec5SDimitry Andric                                             BitVector &SavedRegs,
22230b57cec5SDimitry Andric                                             RegScavenger *RS) const {
22240b57cec5SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
22270b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)){
2228*8bcb0991SDimitry Andric     Register BasePtr = TRI->getBaseRegister();
22290b57cec5SDimitry Andric     if (STI.isTarget64BitILP32())
22300b57cec5SDimitry Andric       BasePtr = getX86SubSuperRegister(BasePtr, 64);
22310b57cec5SDimitry Andric     SavedRegs.set(BasePtr);
22320b57cec5SDimitry Andric   }
22330b57cec5SDimitry Andric }
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric static bool
22360b57cec5SDimitry Andric HasNestArgument(const MachineFunction *MF) {
22370b57cec5SDimitry Andric   const Function &F = MF->getFunction();
22380b57cec5SDimitry Andric   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
22390b57cec5SDimitry Andric        I != E; I++) {
2240*8bcb0991SDimitry Andric     if (I->hasNestAttr() && !I->use_empty())
22410b57cec5SDimitry Andric       return true;
22420b57cec5SDimitry Andric   }
22430b57cec5SDimitry Andric   return false;
22440b57cec5SDimitry Andric }
22450b57cec5SDimitry Andric 
22460b57cec5SDimitry Andric /// GetScratchRegister - Get a temp register for performing work in the
22470b57cec5SDimitry Andric /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
22480b57cec5SDimitry Andric /// and the properties of the function either one or two registers will be
22490b57cec5SDimitry Andric /// needed. Set primary to true for the first register, false for the second.
22500b57cec5SDimitry Andric static unsigned
22510b57cec5SDimitry Andric GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
22520b57cec5SDimitry Andric   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric   // Erlang stuff.
22550b57cec5SDimitry Andric   if (CallingConvention == CallingConv::HiPE) {
22560b57cec5SDimitry Andric     if (Is64Bit)
22570b57cec5SDimitry Andric       return Primary ? X86::R14 : X86::R13;
22580b57cec5SDimitry Andric     else
22590b57cec5SDimitry Andric       return Primary ? X86::EBX : X86::EDI;
22600b57cec5SDimitry Andric   }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric   if (Is64Bit) {
22630b57cec5SDimitry Andric     if (IsLP64)
22640b57cec5SDimitry Andric       return Primary ? X86::R11 : X86::R12;
22650b57cec5SDimitry Andric     else
22660b57cec5SDimitry Andric       return Primary ? X86::R11D : X86::R12D;
22670b57cec5SDimitry Andric   }
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   bool IsNested = HasNestArgument(&MF);
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric   if (CallingConvention == CallingConv::X86_FastCall ||
2272*8bcb0991SDimitry Andric       CallingConvention == CallingConv::Fast ||
2273*8bcb0991SDimitry Andric       CallingConvention == CallingConv::Tail) {
22740b57cec5SDimitry Andric     if (IsNested)
22750b57cec5SDimitry Andric       report_fatal_error("Segmented stacks does not support fastcall with "
22760b57cec5SDimitry Andric                          "nested function.");
22770b57cec5SDimitry Andric     return Primary ? X86::EAX : X86::ECX;
22780b57cec5SDimitry Andric   }
22790b57cec5SDimitry Andric   if (IsNested)
22800b57cec5SDimitry Andric     return Primary ? X86::EDX : X86::EAX;
22810b57cec5SDimitry Andric   return Primary ? X86::ECX : X86::EAX;
22820b57cec5SDimitry Andric }
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual stack
22850b57cec5SDimitry Andric // limit.
22860b57cec5SDimitry Andric static const uint64_t kSplitStackAvailable = 256;
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric void X86FrameLowering::adjustForSegmentedStacks(
22890b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
22900b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
22910b57cec5SDimitry Andric   uint64_t StackSize;
22920b57cec5SDimitry Andric   unsigned TlsReg, TlsOffset;
22930b57cec5SDimitry Andric   DebugLoc DL;
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
22960b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
22970b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
23000b57cec5SDimitry Andric   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
23010b57cec5SDimitry Andric          "Scratch register is live-in");
23020b57cec5SDimitry Andric 
23030b57cec5SDimitry Andric   if (MF.getFunction().isVarArg())
23040b57cec5SDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
23050b57cec5SDimitry Andric   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
23060b57cec5SDimitry Andric       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
23070b57cec5SDimitry Andric       !STI.isTargetDragonFly())
23080b57cec5SDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric   // Eventually StackSize will be calculated by a link-time pass; which will
23110b57cec5SDimitry Andric   // also decide whether checking code needs to be injected into this particular
23120b57cec5SDimitry Andric   // prologue.
23130b57cec5SDimitry Andric   StackSize = MFI.getStackSize();
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   // Do not generate a prologue for leaf functions with a stack of size zero.
23160b57cec5SDimitry Andric   // For non-leaf functions we have to allow for the possibility that the
23170b57cec5SDimitry Andric   // callis to a non-split function, as in PR37807. This function could also
23180b57cec5SDimitry Andric   // take the address of a non-split function. When the linker tries to adjust
23190b57cec5SDimitry Andric   // its non-existent prologue, it would fail with an error. Mark the object
23200b57cec5SDimitry Andric   // file so that such failures are not errors. See this Go language bug-report
23210b57cec5SDimitry Andric   // https://go-review.googlesource.com/c/go/+/148819/
23220b57cec5SDimitry Andric   if (StackSize == 0 && !MFI.hasTailCall()) {
23230b57cec5SDimitry Andric     MF.getMMI().setHasNosplitStack(true);
23240b57cec5SDimitry Andric     return;
23250b57cec5SDimitry Andric   }
23260b57cec5SDimitry Andric 
23270b57cec5SDimitry Andric   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
23280b57cec5SDimitry Andric   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
23290b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
23300b57cec5SDimitry Andric   bool IsNested = false;
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric   // We need to know if the function has a nest argument only in 64 bit mode.
23330b57cec5SDimitry Andric   if (Is64Bit)
23340b57cec5SDimitry Andric     IsNested = HasNestArgument(&MF);
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
23370b57cec5SDimitry Andric   // allocMBB needs to be last (terminating) instruction.
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
23400b57cec5SDimitry Andric     allocMBB->addLiveIn(LI);
23410b57cec5SDimitry Andric     checkMBB->addLiveIn(LI);
23420b57cec5SDimitry Andric   }
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   if (IsNested)
23450b57cec5SDimitry Andric     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   MF.push_front(allocMBB);
23480b57cec5SDimitry Andric   MF.push_front(checkMBB);
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric   // When the frame size is less than 256 we just compare the stack
23510b57cec5SDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
23520b57cec5SDimitry Andric   bool CompareStackPointer = StackSize < kSplitStackAvailable;
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric   // Read the limit off the current stacklet off the stack_guard location.
23550b57cec5SDimitry Andric   if (Is64Bit) {
23560b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
23570b57cec5SDimitry Andric       TlsReg = X86::FS;
23580b57cec5SDimitry Andric       TlsOffset = IsLP64 ? 0x70 : 0x40;
23590b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
23600b57cec5SDimitry Andric       TlsReg = X86::GS;
23610b57cec5SDimitry Andric       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
23620b57cec5SDimitry Andric     } else if (STI.isTargetWin64()) {
23630b57cec5SDimitry Andric       TlsReg = X86::GS;
23640b57cec5SDimitry Andric       TlsOffset = 0x28; // pvArbitrary, reserved for application use
23650b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
23660b57cec5SDimitry Andric       TlsReg = X86::FS;
23670b57cec5SDimitry Andric       TlsOffset = 0x18;
23680b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
23690b57cec5SDimitry Andric       TlsReg = X86::FS;
23700b57cec5SDimitry Andric       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
23710b57cec5SDimitry Andric     } else {
23720b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
23730b57cec5SDimitry Andric     }
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric     if (CompareStackPointer)
23760b57cec5SDimitry Andric       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
23770b57cec5SDimitry Andric     else
23780b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
23790b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
23820b57cec5SDimitry Andric       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
23830b57cec5SDimitry Andric   } else {
23840b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
23850b57cec5SDimitry Andric       TlsReg = X86::GS;
23860b57cec5SDimitry Andric       TlsOffset = 0x30;
23870b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
23880b57cec5SDimitry Andric       TlsReg = X86::GS;
23890b57cec5SDimitry Andric       TlsOffset = 0x48 + 90*4;
23900b57cec5SDimitry Andric     } else if (STI.isTargetWin32()) {
23910b57cec5SDimitry Andric       TlsReg = X86::FS;
23920b57cec5SDimitry Andric       TlsOffset = 0x14; // pvArbitrary, reserved for application use
23930b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
23940b57cec5SDimitry Andric       TlsReg = X86::FS;
23950b57cec5SDimitry Andric       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
23960b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
23970b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
23980b57cec5SDimitry Andric     } else {
23990b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
24000b57cec5SDimitry Andric     }
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric     if (CompareStackPointer)
24030b57cec5SDimitry Andric       ScratchReg = X86::ESP;
24040b57cec5SDimitry Andric     else
24050b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
24060b57cec5SDimitry Andric         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
24090b57cec5SDimitry Andric         STI.isTargetDragonFly()) {
24100b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
24110b57cec5SDimitry Andric         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
24120b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
24150b57cec5SDimitry Andric       unsigned ScratchReg2;
24160b57cec5SDimitry Andric       bool SaveScratch2;
24170b57cec5SDimitry Andric       if (CompareStackPointer) {
24180b57cec5SDimitry Andric         // The primary scratch register is available for holding the TLS offset.
24190b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
24200b57cec5SDimitry Andric         SaveScratch2 = false;
24210b57cec5SDimitry Andric       } else {
24220b57cec5SDimitry Andric         // Need to use a second register to hold the TLS offset
24230b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric         // Unfortunately, with fastcc the second scratch register may hold an
24260b57cec5SDimitry Andric         // argument.
24270b57cec5SDimitry Andric         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
24280b57cec5SDimitry Andric       }
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric       // If Scratch2 is live-in then it needs to be saved.
24310b57cec5SDimitry Andric       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
24320b57cec5SDimitry Andric              "Scratch register is live-in and not saved");
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric       if (SaveScratch2)
24350b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
24360b57cec5SDimitry Andric           .addReg(ScratchReg2, RegState::Kill);
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
24390b57cec5SDimitry Andric         .addImm(TlsOffset);
24400b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
24410b57cec5SDimitry Andric         .addReg(ScratchReg)
24420b57cec5SDimitry Andric         .addReg(ScratchReg2).addImm(1).addReg(0)
24430b57cec5SDimitry Andric         .addImm(0)
24440b57cec5SDimitry Andric         .addReg(TlsReg);
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric       if (SaveScratch2)
24470b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
24480b57cec5SDimitry Andric     }
24490b57cec5SDimitry Andric   }
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
24520b57cec5SDimitry Andric   // It jumps to normal execution of the function body.
24530b57cec5SDimitry Andric   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
24540b57cec5SDimitry Andric 
24550b57cec5SDimitry Andric   // On 32 bit we first push the arguments size and then the frame size. On 64
24560b57cec5SDimitry Andric   // bit, we pass the stack frame size in r10 and the argument size in r11.
24570b57cec5SDimitry Andric   if (Is64Bit) {
24580b57cec5SDimitry Andric     // Functions with nested arguments use R10, so it needs to be saved across
24590b57cec5SDimitry Andric     // the call to _morestack
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
24620b57cec5SDimitry Andric     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
24630b57cec5SDimitry Andric     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
24640b57cec5SDimitry Andric     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
24650b57cec5SDimitry Andric     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric     if (IsNested)
24680b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
24710b57cec5SDimitry Andric       .addImm(StackSize);
24720b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
24730b57cec5SDimitry Andric       .addImm(X86FI->getArgumentStackSize());
24740b57cec5SDimitry Andric   } else {
24750b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
24760b57cec5SDimitry Andric       .addImm(X86FI->getArgumentStackSize());
24770b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
24780b57cec5SDimitry Andric       .addImm(StackSize);
24790b57cec5SDimitry Andric   }
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric   // __morestack is in libgcc
24820b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
24830b57cec5SDimitry Andric     // Under the large code model, we cannot assume that __morestack lives
24840b57cec5SDimitry Andric     // within 2^31 bytes of the call site, so we cannot use pc-relative
24850b57cec5SDimitry Andric     // addressing. We cannot perform the call via a temporary register,
24860b57cec5SDimitry Andric     // as the rax register may be used to store the static chain, and all
24870b57cec5SDimitry Andric     // other suitable registers may be either callee-save or used for
24880b57cec5SDimitry Andric     // parameter passing. We cannot use the stack at this point either
24890b57cec5SDimitry Andric     // because __morestack manipulates the stack directly.
24900b57cec5SDimitry Andric     //
24910b57cec5SDimitry Andric     // To avoid these issues, perform an indirect call via a read-only memory
24920b57cec5SDimitry Andric     // location containing the address.
24930b57cec5SDimitry Andric     //
24940b57cec5SDimitry Andric     // This solution is not perfect, as it assumes that the .rodata section
24950b57cec5SDimitry Andric     // is laid out within 2^31 bytes of each function body, but this seems
24960b57cec5SDimitry Andric     // to be sufficient for JIT.
24970b57cec5SDimitry Andric     // FIXME: Add retpoline support and remove the error here..
24980b57cec5SDimitry Andric     if (STI.useRetpolineIndirectCalls())
24990b57cec5SDimitry Andric       report_fatal_error("Emitting morestack calls on 64-bit with the large "
25000b57cec5SDimitry Andric                          "code model and retpoline not yet implemented.");
25010b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
25020b57cec5SDimitry Andric         .addReg(X86::RIP)
25030b57cec5SDimitry Andric         .addImm(0)
25040b57cec5SDimitry Andric         .addReg(0)
25050b57cec5SDimitry Andric         .addExternalSymbol("__morestack_addr")
25060b57cec5SDimitry Andric         .addReg(0);
25070b57cec5SDimitry Andric     MF.getMMI().setUsesMorestackAddr(true);
25080b57cec5SDimitry Andric   } else {
25090b57cec5SDimitry Andric     if (Is64Bit)
25100b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
25110b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
25120b57cec5SDimitry Andric     else
25130b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
25140b57cec5SDimitry Andric         .addExternalSymbol("__morestack");
25150b57cec5SDimitry Andric   }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   if (IsNested)
25180b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
25190b57cec5SDimitry Andric   else
25200b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric   allocMBB->addSuccessor(&PrologueMBB);
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
25250b57cec5SDimitry Andric   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
25280b57cec5SDimitry Andric   MF.verify();
25290b57cec5SDimitry Andric #endif
25300b57cec5SDimitry Andric }
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
25330b57cec5SDimitry Andric /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
25340b57cec5SDimitry Andric /// to fields it needs, through a named metadata node "hipe.literals" containing
25350b57cec5SDimitry Andric /// name-value pairs.
25360b57cec5SDimitry Andric static unsigned getHiPELiteral(
25370b57cec5SDimitry Andric     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
25380b57cec5SDimitry Andric   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
25390b57cec5SDimitry Andric     MDNode *Node = HiPELiteralsMD->getOperand(i);
25400b57cec5SDimitry Andric     if (Node->getNumOperands() != 2) continue;
25410b57cec5SDimitry Andric     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
25420b57cec5SDimitry Andric     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
25430b57cec5SDimitry Andric     if (!NodeName || !NodeVal) continue;
25440b57cec5SDimitry Andric     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
25450b57cec5SDimitry Andric     if (ValConst && NodeName->getString() == LiteralName) {
25460b57cec5SDimitry Andric       return ValConst->getZExtValue();
25470b57cec5SDimitry Andric     }
25480b57cec5SDimitry Andric   }
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric   report_fatal_error("HiPE literal " + LiteralName
25510b57cec5SDimitry Andric                      + " required but not provided");
25520b57cec5SDimitry Andric }
25530b57cec5SDimitry Andric 
2554*8bcb0991SDimitry Andric // Return true if there are no non-ehpad successors to MBB and there are no
2555*8bcb0991SDimitry Andric // non-meta instructions between MBBI and MBB.end().
2556*8bcb0991SDimitry Andric static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
2557*8bcb0991SDimitry Andric                                   MachineBasicBlock::const_iterator MBBI) {
2558*8bcb0991SDimitry Andric   return std::all_of(
2559*8bcb0991SDimitry Andric              MBB.succ_begin(), MBB.succ_end(),
2560*8bcb0991SDimitry Andric              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
2561*8bcb0991SDimitry Andric          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
2562*8bcb0991SDimitry Andric            return MI.isMetaInstruction();
2563*8bcb0991SDimitry Andric          });
2564*8bcb0991SDimitry Andric }
2565*8bcb0991SDimitry Andric 
25660b57cec5SDimitry Andric /// Erlang programs may need a special prologue to handle the stack size they
25670b57cec5SDimitry Andric /// might need at runtime. That is because Erlang/OTP does not implement a C
25680b57cec5SDimitry Andric /// stack but uses a custom implementation of hybrid stack/heap architecture.
25690b57cec5SDimitry Andric /// (for more information see Eric Stenman's Ph.D. thesis:
25700b57cec5SDimitry Andric /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
25710b57cec5SDimitry Andric ///
25720b57cec5SDimitry Andric /// CheckStack:
25730b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
25740b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
25750b57cec5SDimitry Andric /// OldStart:
25760b57cec5SDimitry Andric ///       ...
25770b57cec5SDimitry Andric /// IncStack:
25780b57cec5SDimitry Andric ///       call inc_stack   # doubles the stack space
25790b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
25800b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
25810b57cec5SDimitry Andric void X86FrameLowering::adjustForHiPEPrologue(
25820b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
25830b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
25840b57cec5SDimitry Andric   DebugLoc DL;
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
25870b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
25880b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   // HiPE-specific values
25910b57cec5SDimitry Andric   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
25920b57cec5SDimitry Andric     ->getNamedMetadata("hipe.literals");
25930b57cec5SDimitry Andric   if (!HiPELiteralsMD)
25940b57cec5SDimitry Andric     report_fatal_error(
25950b57cec5SDimitry Andric         "Can't generate HiPE prologue without runtime parameters");
25960b57cec5SDimitry Andric   const unsigned HipeLeafWords
25970b57cec5SDimitry Andric     = getHiPELiteral(HiPELiteralsMD,
25980b57cec5SDimitry Andric                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
25990b57cec5SDimitry Andric   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
26000b57cec5SDimitry Andric   const unsigned Guaranteed = HipeLeafWords * SlotSize;
26010b57cec5SDimitry Andric   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
26020b57cec5SDimitry Andric                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
26030b57cec5SDimitry Andric   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric   assert(STI.isTargetLinux() &&
26060b57cec5SDimitry Andric          "HiPE prologue is only supported on Linux operating systems.");
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric   // Compute the largest caller's frame that is needed to fit the callees'
26090b57cec5SDimitry Andric   // frames. This 'MaxStack' is computed from:
26100b57cec5SDimitry Andric   //
26110b57cec5SDimitry Andric   // a) the fixed frame size, which is the space needed for all spilled temps,
26120b57cec5SDimitry Andric   // b) outgoing on-stack parameter areas, and
26130b57cec5SDimitry Andric   // c) the minimum stack space this function needs to make available for the
26140b57cec5SDimitry Andric   //    functions it calls (a tunable ABI property).
26150b57cec5SDimitry Andric   if (MFI.hasCalls()) {
26160b57cec5SDimitry Andric     unsigned MoreStackForCalls = 0;
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric     for (auto &MBB : MF) {
26190b57cec5SDimitry Andric       for (auto &MI : MBB) {
26200b57cec5SDimitry Andric         if (!MI.isCall())
26210b57cec5SDimitry Andric           continue;
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric         // Get callee operand.
26240b57cec5SDimitry Andric         const MachineOperand &MO = MI.getOperand(0);
26250b57cec5SDimitry Andric 
26260b57cec5SDimitry Andric         // Only take account of global function calls (no closures etc.).
26270b57cec5SDimitry Andric         if (!MO.isGlobal())
26280b57cec5SDimitry Andric           continue;
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric         const Function *F = dyn_cast<Function>(MO.getGlobal());
26310b57cec5SDimitry Andric         if (!F)
26320b57cec5SDimitry Andric           continue;
26330b57cec5SDimitry Andric 
26340b57cec5SDimitry Andric         // Do not update 'MaxStack' for primitive and built-in functions
26350b57cec5SDimitry Andric         // (encoded with names either starting with "erlang."/"bif_" or not
26360b57cec5SDimitry Andric         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
26370b57cec5SDimitry Andric         // "_", such as the BIF "suspend_0") as they are executed on another
26380b57cec5SDimitry Andric         // stack.
26390b57cec5SDimitry Andric         if (F->getName().find("erlang.") != StringRef::npos ||
26400b57cec5SDimitry Andric             F->getName().find("bif_") != StringRef::npos ||
26410b57cec5SDimitry Andric             F->getName().find_first_of("._") == StringRef::npos)
26420b57cec5SDimitry Andric           continue;
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric         unsigned CalleeStkArity =
26450b57cec5SDimitry Andric           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
26460b57cec5SDimitry Andric         if (HipeLeafWords - 1 > CalleeStkArity)
26470b57cec5SDimitry Andric           MoreStackForCalls = std::max(MoreStackForCalls,
26480b57cec5SDimitry Andric                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
26490b57cec5SDimitry Andric       }
26500b57cec5SDimitry Andric     }
26510b57cec5SDimitry Andric     MaxStack += MoreStackForCalls;
26520b57cec5SDimitry Andric   }
26530b57cec5SDimitry Andric 
26540b57cec5SDimitry Andric   // If the stack frame needed is larger than the guaranteed then runtime checks
26550b57cec5SDimitry Andric   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
26560b57cec5SDimitry Andric   if (MaxStack > Guaranteed) {
26570b57cec5SDimitry Andric     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
26580b57cec5SDimitry Andric     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric     for (const auto &LI : PrologueMBB.liveins()) {
26610b57cec5SDimitry Andric       stackCheckMBB->addLiveIn(LI);
26620b57cec5SDimitry Andric       incStackMBB->addLiveIn(LI);
26630b57cec5SDimitry Andric     }
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric     MF.push_front(incStackMBB);
26660b57cec5SDimitry Andric     MF.push_front(stackCheckMBB);
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
26690b57cec5SDimitry Andric     unsigned LEAop, CMPop, CALLop;
26700b57cec5SDimitry Andric     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
26710b57cec5SDimitry Andric     if (Is64Bit) {
26720b57cec5SDimitry Andric       SPReg = X86::RSP;
26730b57cec5SDimitry Andric       PReg  = X86::RBP;
26740b57cec5SDimitry Andric       LEAop = X86::LEA64r;
26750b57cec5SDimitry Andric       CMPop = X86::CMP64rm;
26760b57cec5SDimitry Andric       CALLop = X86::CALL64pcrel32;
26770b57cec5SDimitry Andric     } else {
26780b57cec5SDimitry Andric       SPReg = X86::ESP;
26790b57cec5SDimitry Andric       PReg  = X86::EBP;
26800b57cec5SDimitry Andric       LEAop = X86::LEA32r;
26810b57cec5SDimitry Andric       CMPop = X86::CMP32rm;
26820b57cec5SDimitry Andric       CALLop = X86::CALLpcrel32;
26830b57cec5SDimitry Andric     }
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
26860b57cec5SDimitry Andric     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
26870b57cec5SDimitry Andric            "HiPE prologue scratch register is live-in");
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric     // Create new MBB for StackCheck:
26900b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
26910b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
26920b57cec5SDimitry Andric     // SPLimitOffset is in a fixed heap location (pointed by BP).
26930b57cec5SDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
26940b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
26950b57cec5SDimitry Andric     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
26960b57cec5SDimitry Andric 
26970b57cec5SDimitry Andric     // Create new MBB for IncStack:
26980b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(CALLop)).
26990b57cec5SDimitry Andric       addExternalSymbol("inc_stack_0");
27000b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
27010b57cec5SDimitry Andric                  SPReg, false, -MaxStack);
27020b57cec5SDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
27030b57cec5SDimitry Andric                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
27040b57cec5SDimitry Andric     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
27050b57cec5SDimitry Andric 
27060b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
27070b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
27080b57cec5SDimitry Andric     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
27090b57cec5SDimitry Andric     incStackMBB->addSuccessor(incStackMBB, {1, 100});
27100b57cec5SDimitry Andric   }
27110b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
27120b57cec5SDimitry Andric   MF.verify();
27130b57cec5SDimitry Andric #endif
27140b57cec5SDimitry Andric }
27150b57cec5SDimitry Andric 
27160b57cec5SDimitry Andric bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
27170b57cec5SDimitry Andric                                            MachineBasicBlock::iterator MBBI,
27180b57cec5SDimitry Andric                                            const DebugLoc &DL,
27190b57cec5SDimitry Andric                                            int Offset) const {
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric   if (Offset <= 0)
27220b57cec5SDimitry Andric     return false;
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   if (Offset % SlotSize)
27250b57cec5SDimitry Andric     return false;
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   int NumPops = Offset / SlotSize;
27280b57cec5SDimitry Andric   // This is only worth it if we have at most 2 pops.
27290b57cec5SDimitry Andric   if (NumPops != 1 && NumPops != 2)
27300b57cec5SDimitry Andric     return false;
27310b57cec5SDimitry Andric 
27320b57cec5SDimitry Andric   // Handle only the trivial case where the adjustment directly follows
27330b57cec5SDimitry Andric   // a call. This is the most common one, anyway.
27340b57cec5SDimitry Andric   if (MBBI == MBB.begin())
27350b57cec5SDimitry Andric     return false;
27360b57cec5SDimitry Andric   MachineBasicBlock::iterator Prev = std::prev(MBBI);
27370b57cec5SDimitry Andric   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
27380b57cec5SDimitry Andric     return false;
27390b57cec5SDimitry Andric 
27400b57cec5SDimitry Andric   unsigned Regs[2];
27410b57cec5SDimitry Andric   unsigned FoundRegs = 0;
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric   auto &MRI = MBB.getParent()->getRegInfo();
27440b57cec5SDimitry Andric   auto RegMask = Prev->getOperand(1);
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric   auto &RegClass =
27470b57cec5SDimitry Andric       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
27480b57cec5SDimitry Andric   // Try to find up to NumPops free registers.
27490b57cec5SDimitry Andric   for (auto Candidate : RegClass) {
27500b57cec5SDimitry Andric 
27510b57cec5SDimitry Andric     // Poor man's liveness:
27520b57cec5SDimitry Andric     // Since we're immediately after a call, any register that is clobbered
27530b57cec5SDimitry Andric     // by the call and not defined by it can be considered dead.
27540b57cec5SDimitry Andric     if (!RegMask.clobbersPhysReg(Candidate))
27550b57cec5SDimitry Andric       continue;
27560b57cec5SDimitry Andric 
27570b57cec5SDimitry Andric     // Don't clobber reserved registers
27580b57cec5SDimitry Andric     if (MRI.isReserved(Candidate))
27590b57cec5SDimitry Andric       continue;
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric     bool IsDef = false;
27620b57cec5SDimitry Andric     for (const MachineOperand &MO : Prev->implicit_operands()) {
27630b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() &&
27640b57cec5SDimitry Andric           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
27650b57cec5SDimitry Andric         IsDef = true;
27660b57cec5SDimitry Andric         break;
27670b57cec5SDimitry Andric       }
27680b57cec5SDimitry Andric     }
27690b57cec5SDimitry Andric 
27700b57cec5SDimitry Andric     if (IsDef)
27710b57cec5SDimitry Andric       continue;
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric     Regs[FoundRegs++] = Candidate;
27740b57cec5SDimitry Andric     if (FoundRegs == (unsigned)NumPops)
27750b57cec5SDimitry Andric       break;
27760b57cec5SDimitry Andric   }
27770b57cec5SDimitry Andric 
27780b57cec5SDimitry Andric   if (FoundRegs == 0)
27790b57cec5SDimitry Andric     return false;
27800b57cec5SDimitry Andric 
27810b57cec5SDimitry Andric   // If we found only one free register, but need two, reuse the same one twice.
27820b57cec5SDimitry Andric   while (FoundRegs < (unsigned)NumPops)
27830b57cec5SDimitry Andric     Regs[FoundRegs++] = Regs[0];
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric   for (int i = 0; i < NumPops; ++i)
27860b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL,
27870b57cec5SDimitry Andric             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   return true;
27900b57cec5SDimitry Andric }
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::
27930b57cec5SDimitry Andric eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
27940b57cec5SDimitry Andric                               MachineBasicBlock::iterator I) const {
27950b57cec5SDimitry Andric   bool reserveCallFrame = hasReservedCallFrame(MF);
27960b57cec5SDimitry Andric   unsigned Opcode = I->getOpcode();
27970b57cec5SDimitry Andric   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
27980b57cec5SDimitry Andric   DebugLoc DL = I->getDebugLoc();
2799*8bcb0991SDimitry Andric   uint64_t Amount = TII.getFrameSize(*I);
28000b57cec5SDimitry Andric   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
28010b57cec5SDimitry Andric   I = MBB.erase(I);
28020b57cec5SDimitry Andric   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
28030b57cec5SDimitry Andric 
28040b57cec5SDimitry Andric   if (!reserveCallFrame) {
28050b57cec5SDimitry Andric     // If the stack pointer can be changed after prologue, turn the
28060b57cec5SDimitry Andric     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
28070b57cec5SDimitry Andric     // adjcallstackdown instruction into 'add ESP, <amt>'
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric     // We need to keep the stack aligned properly.  To do this, we round the
28100b57cec5SDimitry Andric     // amount of space needed for the outgoing arguments up to the next
28110b57cec5SDimitry Andric     // alignment boundary.
28120b57cec5SDimitry Andric     unsigned StackAlign = getStackAlignment();
28130b57cec5SDimitry Andric     Amount = alignTo(Amount, StackAlign);
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric     MachineModuleInfo &MMI = MF.getMMI();
28160b57cec5SDimitry Andric     const Function &F = MF.getFunction();
28170b57cec5SDimitry Andric     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
28180b57cec5SDimitry Andric     bool DwarfCFI = !WindowsCFI &&
28190b57cec5SDimitry Andric                     (MMI.hasDebugInfo() || F.needsUnwindTableEntry());
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric     // If we have any exception handlers in this function, and we adjust
28220b57cec5SDimitry Andric     // the SP before calls, we may need to indicate this to the unwinder
28230b57cec5SDimitry Andric     // using GNU_ARGS_SIZE. Note that this may be necessary even when
28240b57cec5SDimitry Andric     // Amount == 0, because the preceding function may have set a non-0
28250b57cec5SDimitry Andric     // GNU_ARGS_SIZE.
28260b57cec5SDimitry Andric     // TODO: We don't need to reset this between subsequent functions,
28270b57cec5SDimitry Andric     // if it didn't change.
28280b57cec5SDimitry Andric     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric     if (HasDwarfEHHandlers && !isDestroy &&
28310b57cec5SDimitry Andric         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
28320b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
28330b57cec5SDimitry Andric                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
28340b57cec5SDimitry Andric 
28350b57cec5SDimitry Andric     if (Amount == 0)
28360b57cec5SDimitry Andric       return I;
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric     // Factor out the amount that gets handled inside the sequence
28390b57cec5SDimitry Andric     // (Pushes of argument for frame setup, callee pops for frame destroy)
28400b57cec5SDimitry Andric     Amount -= InternalAmt;
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric     // TODO: This is needed only if we require precise CFA.
28430b57cec5SDimitry Andric     // If this is a callee-pop calling convention, emit a CFA adjust for
28440b57cec5SDimitry Andric     // the amount the callee popped.
28450b57cec5SDimitry Andric     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
28460b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
28470b57cec5SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric     // Add Amount to SP to destroy a frame, or subtract to setup.
28500b57cec5SDimitry Andric     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric     if (StackAdjustment) {
28530b57cec5SDimitry Andric       // Merge with any previous or following adjustment instruction. Note: the
28540b57cec5SDimitry Andric       // instructions merged with here do not have CFI, so their stack
28550b57cec5SDimitry Andric       // adjustments do not feed into CfaAdjustment.
28560b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
28570b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric       if (StackAdjustment) {
28600b57cec5SDimitry Andric         if (!(F.hasMinSize() &&
28610b57cec5SDimitry Andric               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
28620b57cec5SDimitry Andric           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
28630b57cec5SDimitry Andric                                /*InEpilogue=*/false);
28640b57cec5SDimitry Andric       }
28650b57cec5SDimitry Andric     }
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric     if (DwarfCFI && !hasFP(MF)) {
28680b57cec5SDimitry Andric       // If we don't have FP, but need to generate unwind information,
28690b57cec5SDimitry Andric       // we need to set the correct CFA offset after the stack adjustment.
28700b57cec5SDimitry Andric       // How much we adjust the CFA offset depends on whether we're emitting
28710b57cec5SDimitry Andric       // CFI only for EH purposes or for debugging. EH only requires the CFA
28720b57cec5SDimitry Andric       // offset to be correct at each call site, while for debugging we want
28730b57cec5SDimitry Andric       // it to be more precise.
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric       int64_t CfaAdjustment = -StackAdjustment;
28760b57cec5SDimitry Andric       // TODO: When not using precise CFA, we also need to adjust for the
28770b57cec5SDimitry Andric       // InternalAmt here.
28780b57cec5SDimitry Andric       if (CfaAdjustment) {
28790b57cec5SDimitry Andric         BuildCFI(MBB, InsertPos, DL,
28800b57cec5SDimitry Andric                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
28810b57cec5SDimitry Andric                                                          CfaAdjustment));
28820b57cec5SDimitry Andric       }
28830b57cec5SDimitry Andric     }
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric     return I;
28860b57cec5SDimitry Andric   }
28870b57cec5SDimitry Andric 
2888*8bcb0991SDimitry Andric   if (isDestroy && InternalAmt && !blockEndIsUnreachable(MBB, I)) {
28890b57cec5SDimitry Andric     // If we are performing frame pointer elimination and if the callee pops
28900b57cec5SDimitry Andric     // something off the stack pointer, add it back.  We do this until we have
28910b57cec5SDimitry Andric     // more advanced stack pointer tracking ability.
28920b57cec5SDimitry Andric     // We are not tracking the stack pointer adjustment by the callee, so make
28930b57cec5SDimitry Andric     // sure we restore the stack pointer immediately after the call, there may
28940b57cec5SDimitry Andric     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
28950b57cec5SDimitry Andric     MachineBasicBlock::iterator CI = I;
28960b57cec5SDimitry Andric     MachineBasicBlock::iterator B = MBB.begin();
28970b57cec5SDimitry Andric     while (CI != B && !std::prev(CI)->isCall())
28980b57cec5SDimitry Andric       --CI;
28990b57cec5SDimitry Andric     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
29000b57cec5SDimitry Andric   }
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   return I;
29030b57cec5SDimitry Andric }
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
29060b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
29070b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
29080b57cec5SDimitry Andric   return !TRI->needsStackRealignment(MF) || !MBB.isLiveIn(X86::EFLAGS);
29090b57cec5SDimitry Andric }
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
29120b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric   // Win64 has strict requirements in terms of epilogue and we are
29150b57cec5SDimitry Andric   // not taking a chance at messing with them.
29160b57cec5SDimitry Andric   // I.e., unless this block is already an exit block, we can't use
29170b57cec5SDimitry Andric   // it as an epilogue.
29180b57cec5SDimitry Andric   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
29190b57cec5SDimitry Andric     return false;
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
29220b57cec5SDimitry Andric     return true;
29230b57cec5SDimitry Andric 
29240b57cec5SDimitry Andric   // If we cannot use LEA to adjust SP, we may need to use ADD, which
29250b57cec5SDimitry Andric   // clobbers the EFLAGS. Check that we do not need to preserve it,
29260b57cec5SDimitry Andric   // otherwise, conservatively assume this is not
29270b57cec5SDimitry Andric   // safe to insert the epilogue here.
29280b57cec5SDimitry Andric   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
29290b57cec5SDimitry Andric }
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
29320b57cec5SDimitry Andric   // If we may need to emit frameless compact unwind information, give
29330b57cec5SDimitry Andric   // up as this is currently broken: PR25614.
29340b57cec5SDimitry Andric   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF)) &&
29350b57cec5SDimitry Andric          // The lowering of segmented stack and HiPE only support entry blocks
29360b57cec5SDimitry Andric          // as prologue blocks: PR26107.
29370b57cec5SDimitry Andric          // This limitation may be lifted if we fix:
29380b57cec5SDimitry Andric          // - adjustForSegmentedStacks
29390b57cec5SDimitry Andric          // - adjustForHiPEPrologue
29400b57cec5SDimitry Andric          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
29410b57cec5SDimitry Andric          !MF.shouldSplitStack();
29420b57cec5SDimitry Andric }
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
29450b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
29460b57cec5SDimitry Andric     const DebugLoc &DL, bool RestoreSP) const {
29470b57cec5SDimitry Andric   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
29480b57cec5SDimitry Andric   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
29490b57cec5SDimitry Andric   assert(STI.is32Bit() && !Uses64BitFramePtr &&
29500b57cec5SDimitry Andric          "restoring EBP/ESI on non-32-bit target");
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
2953*8bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
2954*8bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
29550b57cec5SDimitry Andric   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
29560b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
29570b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   // FIXME: Don't set FrameSetup flag in catchret case.
29600b57cec5SDimitry Andric 
29610b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
29620b57cec5SDimitry Andric   int EHRegSize = MFI.getObjectSize(FI);
29630b57cec5SDimitry Andric 
29640b57cec5SDimitry Andric   if (RestoreSP) {
29650b57cec5SDimitry Andric     // MOV32rm -EHRegSize(%ebp), %esp
29660b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
29670b57cec5SDimitry Andric                  X86::EBP, true, -EHRegSize)
29680b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
29690b57cec5SDimitry Andric   }
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric   unsigned UsedReg;
29720b57cec5SDimitry Andric   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
29730b57cec5SDimitry Andric   int EndOffset = -EHRegOffset - EHRegSize;
29740b57cec5SDimitry Andric   FuncInfo.EHRegNodeEndOffset = EndOffset;
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   if (UsedReg == FramePtr) {
29770b57cec5SDimitry Andric     // ADD $offset, %ebp
29780b57cec5SDimitry Andric     unsigned ADDri = getADDriOpcode(false, EndOffset);
29790b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
29800b57cec5SDimitry Andric         .addReg(FramePtr)
29810b57cec5SDimitry Andric         .addImm(EndOffset)
29820b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup)
29830b57cec5SDimitry Andric         ->getOperand(3)
29840b57cec5SDimitry Andric         .setIsDead();
29850b57cec5SDimitry Andric     assert(EndOffset >= 0 &&
29860b57cec5SDimitry Andric            "end of registration object above normal EBP position!");
29870b57cec5SDimitry Andric   } else if (UsedReg == BasePtr) {
29880b57cec5SDimitry Andric     // LEA offset(%ebp), %esi
29890b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
29900b57cec5SDimitry Andric                  FramePtr, false, EndOffset)
29910b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
29920b57cec5SDimitry Andric     // MOV32rm SavedEBPOffset(%esi), %ebp
29930b57cec5SDimitry Andric     assert(X86FI->getHasSEHFramePtrSave());
29940b57cec5SDimitry Andric     int Offset =
29950b57cec5SDimitry Andric         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
29960b57cec5SDimitry Andric     assert(UsedReg == BasePtr);
29970b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
29980b57cec5SDimitry Andric                  UsedReg, true, Offset)
29990b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
30000b57cec5SDimitry Andric   } else {
30010b57cec5SDimitry Andric     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
30020b57cec5SDimitry Andric   }
30030b57cec5SDimitry Andric   return MBBI;
30040b57cec5SDimitry Andric }
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
30070b57cec5SDimitry Andric   return TRI->getSlotSize();
30080b57cec5SDimitry Andric }
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric unsigned X86FrameLowering::getInitialCFARegister(const MachineFunction &MF)
30110b57cec5SDimitry Andric     const {
30120b57cec5SDimitry Andric   return TRI->getDwarfRegNum(StackPtr, true);
30130b57cec5SDimitry Andric }
30140b57cec5SDimitry Andric 
30150b57cec5SDimitry Andric namespace {
30160b57cec5SDimitry Andric // Struct used by orderFrameObjects to help sort the stack objects.
30170b57cec5SDimitry Andric struct X86FrameSortingObject {
30180b57cec5SDimitry Andric   bool IsValid = false;         // true if we care about this Object.
30190b57cec5SDimitry Andric   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
30200b57cec5SDimitry Andric   unsigned ObjectSize = 0;      // Size of Object in bytes.
30210b57cec5SDimitry Andric   unsigned ObjectAlignment = 1; // Alignment of Object in bytes.
30220b57cec5SDimitry Andric   unsigned ObjectNumUses = 0;   // Object static number of uses.
30230b57cec5SDimitry Andric };
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric // The comparison function we use for std::sort to order our local
30260b57cec5SDimitry Andric // stack symbols. The current algorithm is to use an estimated
30270b57cec5SDimitry Andric // "density". This takes into consideration the size and number of
30280b57cec5SDimitry Andric // uses each object has in order to roughly minimize code size.
30290b57cec5SDimitry Andric // So, for example, an object of size 16B that is referenced 5 times
30300b57cec5SDimitry Andric // will get higher priority than 4 4B objects referenced 1 time each.
30310b57cec5SDimitry Andric // It's not perfect and we may be able to squeeze a few more bytes out of
30320b57cec5SDimitry Andric // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
30330b57cec5SDimitry Andric // fringe end can have special consideration, given their size is less
30340b57cec5SDimitry Andric // important, etc.), but the algorithmic complexity grows too much to be
30350b57cec5SDimitry Andric // worth the extra gains we get. This gets us pretty close.
30360b57cec5SDimitry Andric // The final order leaves us with objects with highest priority going
30370b57cec5SDimitry Andric // at the end of our list.
30380b57cec5SDimitry Andric struct X86FrameSortingComparator {
30390b57cec5SDimitry Andric   inline bool operator()(const X86FrameSortingObject &A,
30400b57cec5SDimitry Andric                          const X86FrameSortingObject &B) {
30410b57cec5SDimitry Andric     uint64_t DensityAScaled, DensityBScaled;
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric     // For consistency in our comparison, all invalid objects are placed
30440b57cec5SDimitry Andric     // at the end. This also allows us to stop walking when we hit the
30450b57cec5SDimitry Andric     // first invalid item after it's all sorted.
30460b57cec5SDimitry Andric     if (!A.IsValid)
30470b57cec5SDimitry Andric       return false;
30480b57cec5SDimitry Andric     if (!B.IsValid)
30490b57cec5SDimitry Andric       return true;
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric     // The density is calculated by doing :
30520b57cec5SDimitry Andric     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
30530b57cec5SDimitry Andric     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
30540b57cec5SDimitry Andric     // Since this approach may cause inconsistencies in
30550b57cec5SDimitry Andric     // the floating point <, >, == comparisons, depending on the floating
30560b57cec5SDimitry Andric     // point model with which the compiler was built, we're going
30570b57cec5SDimitry Andric     // to scale both sides by multiplying with
30580b57cec5SDimitry Andric     // A.ObjectSize * B.ObjectSize. This ends up factoring away
30590b57cec5SDimitry Andric     // the division and, with it, the need for any floating point
30600b57cec5SDimitry Andric     // arithmetic.
30610b57cec5SDimitry Andric     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
30620b57cec5SDimitry Andric       static_cast<uint64_t>(B.ObjectSize);
30630b57cec5SDimitry Andric     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
30640b57cec5SDimitry Andric       static_cast<uint64_t>(A.ObjectSize);
30650b57cec5SDimitry Andric 
30660b57cec5SDimitry Andric     // If the two densities are equal, prioritize highest alignment
30670b57cec5SDimitry Andric     // objects. This allows for similar alignment objects
30680b57cec5SDimitry Andric     // to be packed together (given the same density).
30690b57cec5SDimitry Andric     // There's room for improvement here, also, since we can pack
30700b57cec5SDimitry Andric     // similar alignment (different density) objects next to each
30710b57cec5SDimitry Andric     // other to save padding. This will also require further
30720b57cec5SDimitry Andric     // complexity/iterations, and the overall gain isn't worth it,
30730b57cec5SDimitry Andric     // in general. Something to keep in mind, though.
30740b57cec5SDimitry Andric     if (DensityAScaled == DensityBScaled)
30750b57cec5SDimitry Andric       return A.ObjectAlignment < B.ObjectAlignment;
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric     return DensityAScaled < DensityBScaled;
30780b57cec5SDimitry Andric   }
30790b57cec5SDimitry Andric };
30800b57cec5SDimitry Andric } // namespace
30810b57cec5SDimitry Andric 
30820b57cec5SDimitry Andric // Order the symbols in the local stack.
30830b57cec5SDimitry Andric // We want to place the local stack objects in some sort of sensible order.
30840b57cec5SDimitry Andric // The heuristic we use is to try and pack them according to static number
30850b57cec5SDimitry Andric // of uses and size of object in order to minimize code size.
30860b57cec5SDimitry Andric void X86FrameLowering::orderFrameObjects(
30870b57cec5SDimitry Andric     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
30880b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   // Don't waste time if there's nothing to do.
30910b57cec5SDimitry Andric   if (ObjectsToAllocate.empty())
30920b57cec5SDimitry Andric     return;
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric   // Create an array of all MFI objects. We won't need all of these
30950b57cec5SDimitry Andric   // objects, but we're going to create a full array of them to make
30960b57cec5SDimitry Andric   // it easier to index into when we're counting "uses" down below.
30970b57cec5SDimitry Andric   // We want to be able to easily/cheaply access an object by simply
30980b57cec5SDimitry Andric   // indexing into it, instead of having to search for it every time.
30990b57cec5SDimitry Andric   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric   // Walk the objects we care about and mark them as such in our working
31020b57cec5SDimitry Andric   // struct.
31030b57cec5SDimitry Andric   for (auto &Obj : ObjectsToAllocate) {
31040b57cec5SDimitry Andric     SortingObjects[Obj].IsValid = true;
31050b57cec5SDimitry Andric     SortingObjects[Obj].ObjectIndex = Obj;
31060b57cec5SDimitry Andric     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlignment(Obj);
31070b57cec5SDimitry Andric     // Set the size.
31080b57cec5SDimitry Andric     int ObjectSize = MFI.getObjectSize(Obj);
31090b57cec5SDimitry Andric     if (ObjectSize == 0)
31100b57cec5SDimitry Andric       // Variable size. Just use 4.
31110b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = 4;
31120b57cec5SDimitry Andric     else
31130b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = ObjectSize;
31140b57cec5SDimitry Andric   }
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric   // Count the number of uses for each object.
31170b57cec5SDimitry Andric   for (auto &MBB : MF) {
31180b57cec5SDimitry Andric     for (auto &MI : MBB) {
31190b57cec5SDimitry Andric       if (MI.isDebugInstr())
31200b57cec5SDimitry Andric         continue;
31210b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
31220b57cec5SDimitry Andric         // Check to see if it's a local stack symbol.
31230b57cec5SDimitry Andric         if (!MO.isFI())
31240b57cec5SDimitry Andric           continue;
31250b57cec5SDimitry Andric         int Index = MO.getIndex();
31260b57cec5SDimitry Andric         // Check to see if it falls within our range, and is tagged
31270b57cec5SDimitry Andric         // to require ordering.
31280b57cec5SDimitry Andric         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
31290b57cec5SDimitry Andric             SortingObjects[Index].IsValid)
31300b57cec5SDimitry Andric           SortingObjects[Index].ObjectNumUses++;
31310b57cec5SDimitry Andric       }
31320b57cec5SDimitry Andric     }
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
31360b57cec5SDimitry Andric   // info).
31370b57cec5SDimitry Andric   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric   // Now modify the original list to represent the final order that
31400b57cec5SDimitry Andric   // we want. The order will depend on whether we're going to access them
31410b57cec5SDimitry Andric   // from the stack pointer or the frame pointer. For SP, the list should
31420b57cec5SDimitry Andric   // end up with the END containing objects that we want with smaller offsets.
31430b57cec5SDimitry Andric   // For FP, it should be flipped.
31440b57cec5SDimitry Andric   int i = 0;
31450b57cec5SDimitry Andric   for (auto &Obj : SortingObjects) {
31460b57cec5SDimitry Andric     // All invalid items are sorted at the end, so it's safe to stop.
31470b57cec5SDimitry Andric     if (!Obj.IsValid)
31480b57cec5SDimitry Andric       break;
31490b57cec5SDimitry Andric     ObjectsToAllocate[i++] = Obj.ObjectIndex;
31500b57cec5SDimitry Andric   }
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric   // Flip it if we're accessing off of the FP.
31530b57cec5SDimitry Andric   if (!TRI->needsStackRealignment(MF) && hasFP(MF))
31540b57cec5SDimitry Andric     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
31550b57cec5SDimitry Andric }
31560b57cec5SDimitry Andric 
31570b57cec5SDimitry Andric 
31580b57cec5SDimitry Andric unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
31590b57cec5SDimitry Andric   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
31600b57cec5SDimitry Andric   unsigned Offset = 16;
31610b57cec5SDimitry Andric   // RBP is immediately pushed.
31620b57cec5SDimitry Andric   Offset += SlotSize;
31630b57cec5SDimitry Andric   // All callee-saved registers are then pushed.
31640b57cec5SDimitry Andric   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
31650b57cec5SDimitry Andric   // Every funclet allocates enough stack space for the largest outgoing call.
31660b57cec5SDimitry Andric   Offset += getWinEHFuncletFrameSize(MF);
31670b57cec5SDimitry Andric   return Offset;
31680b57cec5SDimitry Andric }
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric void X86FrameLowering::processFunctionBeforeFrameFinalized(
31710b57cec5SDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
31720b57cec5SDimitry Andric   // Mark the function as not having WinCFI. We will set it back to true in
31730b57cec5SDimitry Andric   // emitPrologue if it gets called and emits CFI.
31740b57cec5SDimitry Andric   MF.setHasWinCFI(false);
31750b57cec5SDimitry Andric 
31760b57cec5SDimitry Andric   // If this function isn't doing Win64-style C++ EH, we don't need to do
31770b57cec5SDimitry Andric   // anything.
31780b57cec5SDimitry Andric   const Function &F = MF.getFunction();
31790b57cec5SDimitry Andric   if (!STI.is64Bit() || !MF.hasEHFunclets() ||
31800b57cec5SDimitry Andric       classifyEHPersonality(F.getPersonalityFn()) != EHPersonality::MSVC_CXX)
31810b57cec5SDimitry Andric     return;
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
31840b57cec5SDimitry Andric   // relative to RSP after the prologue.  Find the offset of the last fixed
31850b57cec5SDimitry Andric   // object, so that we can allocate a slot immediately following it. If there
31860b57cec5SDimitry Andric   // were no fixed objects, use offset -SlotSize, which is immediately after the
31870b57cec5SDimitry Andric   // return address. Fixed objects have negative frame indices.
31880b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
31890b57cec5SDimitry Andric   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
31900b57cec5SDimitry Andric   int64_t MinFixedObjOffset = -SlotSize;
31910b57cec5SDimitry Andric   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
31920b57cec5SDimitry Andric     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
31930b57cec5SDimitry Andric 
31940b57cec5SDimitry Andric   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
31950b57cec5SDimitry Andric     for (WinEHHandlerType &H : TBME.HandlerArray) {
31960b57cec5SDimitry Andric       int FrameIndex = H.CatchObj.FrameIndex;
31970b57cec5SDimitry Andric       if (FrameIndex != INT_MAX) {
31980b57cec5SDimitry Andric         // Ensure alignment.
31990b57cec5SDimitry Andric         unsigned Align = MFI.getObjectAlignment(FrameIndex);
32000b57cec5SDimitry Andric         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
32010b57cec5SDimitry Andric         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
32020b57cec5SDimitry Andric         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
32030b57cec5SDimitry Andric       }
32040b57cec5SDimitry Andric     }
32050b57cec5SDimitry Andric   }
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   // Ensure alignment.
32080b57cec5SDimitry Andric   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
32090b57cec5SDimitry Andric   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
32100b57cec5SDimitry Andric   int UnwindHelpFI =
32110b57cec5SDimitry Andric       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
32120b57cec5SDimitry Andric   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
32150b57cec5SDimitry Andric   // other frame setup instructions.
32160b57cec5SDimitry Andric   MachineBasicBlock &MBB = MF.front();
32170b57cec5SDimitry Andric   auto MBBI = MBB.begin();
32180b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
32190b57cec5SDimitry Andric     ++MBBI;
32200b57cec5SDimitry Andric 
32210b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MBBI);
32220b57cec5SDimitry Andric   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
32230b57cec5SDimitry Andric                     UnwindHelpFI)
32240b57cec5SDimitry Andric       .addImm(-2);
32250b57cec5SDimitry Andric }
3226