xref: /openbsd-src/gnu/llvm/llvm/lib/Target/X86/X86FrameLowering.cpp (revision a96b36398fcfb4953e8190127da8bf074c7552f1)
109467b48Spatrick //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file contains the X86 implementation of TargetFrameLowering class.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "X86FrameLowering.h"
14*a96b3639Srobert #include "MCTargetDesc/X86MCTargetDesc.h"
1509467b48Spatrick #include "X86InstrBuilder.h"
1609467b48Spatrick #include "X86InstrInfo.h"
1709467b48Spatrick #include "X86MachineFunctionInfo.h"
18adae0cfdSpatrick #include "X86ReturnProtectorLowering.h"
1909467b48Spatrick #include "X86Subtarget.h"
2009467b48Spatrick #include "X86TargetMachine.h"
2109467b48Spatrick #include "llvm/ADT/SmallSet.h"
22097a140dSpatrick #include "llvm/ADT/Statistic.h"
2309467b48Spatrick #include "llvm/Analysis/EHPersonalities.h"
24*a96b3639Srobert #include "llvm/CodeGen/LivePhysRegs.h"
2509467b48Spatrick #include "llvm/CodeGen/MachineFrameInfo.h"
2609467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
2709467b48Spatrick #include "llvm/CodeGen/MachineInstrBuilder.h"
2809467b48Spatrick #include "llvm/CodeGen/MachineModuleInfo.h"
2909467b48Spatrick #include "llvm/CodeGen/MachineRegisterInfo.h"
3009467b48Spatrick #include "llvm/CodeGen/WinEHFuncInfo.h"
3109467b48Spatrick #include "llvm/IR/DataLayout.h"
3209467b48Spatrick #include "llvm/IR/Function.h"
3309467b48Spatrick #include "llvm/MC/MCAsmInfo.h"
34a0747c9fSpatrick #include "llvm/MC/MCObjectFileInfo.h"
3509467b48Spatrick #include "llvm/MC/MCSymbol.h"
3609467b48Spatrick #include "llvm/Support/Debug.h"
3709467b48Spatrick #include "llvm/Target/TargetOptions.h"
3809467b48Spatrick #include <cstdlib>
3909467b48Spatrick 
40097a140dSpatrick #define DEBUG_TYPE "x86-fl"
41097a140dSpatrick 
42097a140dSpatrick STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
43097a140dSpatrick STATISTIC(NumFrameExtraProbe,
44097a140dSpatrick           "Number of extra stack probes generated in prologue");
45097a140dSpatrick 
4609467b48Spatrick using namespace llvm;
4709467b48Spatrick 
X86FrameLowering(const X86Subtarget & STI,MaybeAlign StackAlignOverride)4809467b48Spatrick X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
4909467b48Spatrick                                    MaybeAlign StackAlignOverride)
5009467b48Spatrick     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
5109467b48Spatrick                           STI.is64Bit() ? -8 : -4),
52adae0cfdSpatrick       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()), RPL() {
5309467b48Spatrick   // Cache a bunch of frame-related predicates for this subtarget.
5409467b48Spatrick   SlotSize = TRI->getSlotSize();
5509467b48Spatrick   Is64Bit = STI.is64Bit();
5609467b48Spatrick   IsLP64 = STI.isTarget64BitLP64();
5709467b48Spatrick   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
5809467b48Spatrick   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
5909467b48Spatrick   StackPtr = TRI->getStackRegister();
60adae0cfdSpatrick   SaveArgs = Is64Bit ? STI.getSaveArgs() : 0;
6109467b48Spatrick }
6209467b48Spatrick 
hasReservedCallFrame(const MachineFunction & MF) const6309467b48Spatrick bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
6409467b48Spatrick   return !MF.getFrameInfo().hasVarSizedObjects() &&
65097a140dSpatrick          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
66097a140dSpatrick          !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
6709467b48Spatrick }
6809467b48Spatrick 
6909467b48Spatrick /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
7009467b48Spatrick /// call frame pseudos can be simplified.  Having a FP, as in the default
7109467b48Spatrick /// implementation, is not sufficient here since we can't always use it.
7209467b48Spatrick /// Use a more nuanced condition.
7309467b48Spatrick bool
canSimplifyCallFramePseudos(const MachineFunction & MF) const7409467b48Spatrick X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
7509467b48Spatrick   return hasReservedCallFrame(MF) ||
76097a140dSpatrick          MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
77a0747c9fSpatrick          (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
7809467b48Spatrick          TRI->hasBasePointer(MF);
7909467b48Spatrick }
8009467b48Spatrick 
8109467b48Spatrick // needsFrameIndexResolution - Do we need to perform FI resolution for
8209467b48Spatrick // this function. Normally, this is required only when the function
8309467b48Spatrick // has any stack objects. However, FI resolution actually has another job,
8409467b48Spatrick // not apparent from the title - it resolves callframesetup/destroy
8509467b48Spatrick // that were not simplified earlier.
8609467b48Spatrick // So, this is required for x86 functions that have push sequences even
8709467b48Spatrick // when there are no stack objects.
8809467b48Spatrick bool
needsFrameIndexResolution(const MachineFunction & MF) const8909467b48Spatrick X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
9009467b48Spatrick   return MF.getFrameInfo().hasStackObjects() ||
9109467b48Spatrick          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
9209467b48Spatrick }
9309467b48Spatrick 
9409467b48Spatrick /// hasFP - Return true if the specified function should have a dedicated frame
9509467b48Spatrick /// pointer register.  This is true if the function has variable sized allocas
9609467b48Spatrick /// or if frame pointer elimination is disabled.
hasFP(const MachineFunction & MF) const9709467b48Spatrick bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
9809467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
9909467b48Spatrick   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
100a0747c9fSpatrick           TRI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
10109467b48Spatrick           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
10209467b48Spatrick           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
103097a140dSpatrick           MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
10409467b48Spatrick           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
10509467b48Spatrick           MFI.hasStackMap() || MFI.hasPatchPoint() ||
106*a96b3639Srobert           (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment()) ||
107adae0cfdSpatrick           SaveArgs);
10809467b48Spatrick }
10909467b48Spatrick 
getSUBriOpcode(bool IsLP64,int64_t Imm)11009467b48Spatrick static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
11109467b48Spatrick   if (IsLP64) {
11209467b48Spatrick     if (isInt<8>(Imm))
11309467b48Spatrick       return X86::SUB64ri8;
11409467b48Spatrick     return X86::SUB64ri32;
11509467b48Spatrick   } else {
11609467b48Spatrick     if (isInt<8>(Imm))
11709467b48Spatrick       return X86::SUB32ri8;
11809467b48Spatrick     return X86::SUB32ri;
11909467b48Spatrick   }
12009467b48Spatrick }
12109467b48Spatrick 
getADDriOpcode(bool IsLP64,int64_t Imm)12209467b48Spatrick static unsigned getADDriOpcode(bool IsLP64, int64_t Imm) {
12309467b48Spatrick   if (IsLP64) {
12409467b48Spatrick     if (isInt<8>(Imm))
12509467b48Spatrick       return X86::ADD64ri8;
12609467b48Spatrick     return X86::ADD64ri32;
12709467b48Spatrick   } else {
12809467b48Spatrick     if (isInt<8>(Imm))
12909467b48Spatrick       return X86::ADD32ri8;
13009467b48Spatrick     return X86::ADD32ri;
13109467b48Spatrick   }
13209467b48Spatrick }
13309467b48Spatrick 
getSUBrrOpcode(bool IsLP64)13409467b48Spatrick static unsigned getSUBrrOpcode(bool IsLP64) {
13509467b48Spatrick   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
13609467b48Spatrick }
13709467b48Spatrick 
getADDrrOpcode(bool IsLP64)13809467b48Spatrick static unsigned getADDrrOpcode(bool IsLP64) {
13909467b48Spatrick   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
14009467b48Spatrick }
14109467b48Spatrick 
getANDriOpcode(bool IsLP64,int64_t Imm)14209467b48Spatrick static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
14309467b48Spatrick   if (IsLP64) {
14409467b48Spatrick     if (isInt<8>(Imm))
14509467b48Spatrick       return X86::AND64ri8;
14609467b48Spatrick     return X86::AND64ri32;
14709467b48Spatrick   }
14809467b48Spatrick   if (isInt<8>(Imm))
14909467b48Spatrick     return X86::AND32ri8;
15009467b48Spatrick   return X86::AND32ri;
15109467b48Spatrick }
15209467b48Spatrick 
getLEArOpcode(bool IsLP64)15309467b48Spatrick static unsigned getLEArOpcode(bool IsLP64) {
15409467b48Spatrick   return IsLP64 ? X86::LEA64r : X86::LEA32r;
15509467b48Spatrick }
15609467b48Spatrick 
getMOVriOpcode(bool Use64BitReg,int64_t Imm)157*a96b3639Srobert static unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm) {
158*a96b3639Srobert   if (Use64BitReg) {
159*a96b3639Srobert     if (isUInt<32>(Imm))
160*a96b3639Srobert       return X86::MOV32ri64;
161*a96b3639Srobert     if (isInt<32>(Imm))
162*a96b3639Srobert       return X86::MOV64ri32;
163*a96b3639Srobert     return X86::MOV64ri;
164*a96b3639Srobert   }
165*a96b3639Srobert   return X86::MOV32ri;
166*a96b3639Srobert }
167*a96b3639Srobert 
isEAXLiveIn(MachineBasicBlock & MBB)16809467b48Spatrick static bool isEAXLiveIn(MachineBasicBlock &MBB) {
16909467b48Spatrick   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
17009467b48Spatrick     unsigned Reg = RegMask.PhysReg;
17109467b48Spatrick 
17209467b48Spatrick     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
17309467b48Spatrick         Reg == X86::AH || Reg == X86::AL)
17409467b48Spatrick       return true;
17509467b48Spatrick   }
17609467b48Spatrick 
17709467b48Spatrick   return false;
17809467b48Spatrick }
17909467b48Spatrick 
18009467b48Spatrick /// Check if the flags need to be preserved before the terminators.
18109467b48Spatrick /// This would be the case, if the eflags is live-in of the region
18209467b48Spatrick /// composed by the terminators or live-out of that region, without
18309467b48Spatrick /// being defined by a terminator.
18409467b48Spatrick static bool
flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock & MBB)18509467b48Spatrick flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
18609467b48Spatrick   for (const MachineInstr &MI : MBB.terminators()) {
18709467b48Spatrick     bool BreakNext = false;
18809467b48Spatrick     for (const MachineOperand &MO : MI.operands()) {
18909467b48Spatrick       if (!MO.isReg())
19009467b48Spatrick         continue;
19109467b48Spatrick       Register Reg = MO.getReg();
19209467b48Spatrick       if (Reg != X86::EFLAGS)
19309467b48Spatrick         continue;
19409467b48Spatrick 
19509467b48Spatrick       // This terminator needs an eflags that is not defined
19609467b48Spatrick       // by a previous another terminator:
19709467b48Spatrick       // EFLAGS is live-in of the region composed by the terminators.
19809467b48Spatrick       if (!MO.isDef())
19909467b48Spatrick         return true;
20009467b48Spatrick       // This terminator defines the eflags, i.e., we don't need to preserve it.
20109467b48Spatrick       // However, we still need to check this specific terminator does not
20209467b48Spatrick       // read a live-in value.
20309467b48Spatrick       BreakNext = true;
20409467b48Spatrick     }
20509467b48Spatrick     // We found a definition of the eflags, no need to preserve them.
20609467b48Spatrick     if (BreakNext)
20709467b48Spatrick       return false;
20809467b48Spatrick   }
20909467b48Spatrick 
21009467b48Spatrick   // None of the terminators use or define the eflags.
21109467b48Spatrick   // Check if they are live-out, that would imply we need to preserve them.
21209467b48Spatrick   for (const MachineBasicBlock *Succ : MBB.successors())
21309467b48Spatrick     if (Succ->isLiveIn(X86::EFLAGS))
21409467b48Spatrick       return true;
21509467b48Spatrick 
21609467b48Spatrick   return false;
21709467b48Spatrick }
21809467b48Spatrick 
21909467b48Spatrick /// emitSPUpdate - Emit a series of instructions to increment / decrement the
22009467b48Spatrick /// stack pointer by a constant value.
emitSPUpdate(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & DL,int64_t NumBytes,bool InEpilogue) const22109467b48Spatrick void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
22209467b48Spatrick                                     MachineBasicBlock::iterator &MBBI,
22309467b48Spatrick                                     const DebugLoc &DL,
22409467b48Spatrick                                     int64_t NumBytes, bool InEpilogue) const {
22509467b48Spatrick   bool isSub = NumBytes < 0;
22609467b48Spatrick   uint64_t Offset = isSub ? -NumBytes : NumBytes;
22709467b48Spatrick   MachineInstr::MIFlag Flag =
22809467b48Spatrick       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
22909467b48Spatrick 
23009467b48Spatrick   uint64_t Chunk = (1LL << 31) - 1;
23109467b48Spatrick 
232097a140dSpatrick   MachineFunction &MF = *MBB.getParent();
233097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
234097a140dSpatrick   const X86TargetLowering &TLI = *STI.getTargetLowering();
235097a140dSpatrick   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
236097a140dSpatrick 
237097a140dSpatrick   // It's ok to not take into account large chunks when probing, as the
238097a140dSpatrick   // allocation is split in smaller chunks anyway.
239097a140dSpatrick   if (EmitInlineStackProbe && !InEpilogue) {
240097a140dSpatrick 
241097a140dSpatrick     // This pseudo-instruction is going to be expanded, potentially using a
242097a140dSpatrick     // loop, by inlineStackProbe().
243097a140dSpatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset);
244097a140dSpatrick     return;
245097a140dSpatrick   } else if (Offset > Chunk) {
24609467b48Spatrick     // Rather than emit a long series of instructions for large offsets,
24709467b48Spatrick     // load the offset into a register and do one sub/add
24809467b48Spatrick     unsigned Reg = 0;
24909467b48Spatrick     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
25009467b48Spatrick 
25109467b48Spatrick     if (isSub && !isEAXLiveIn(MBB))
25209467b48Spatrick       Reg = Rax;
25309467b48Spatrick     else
254a0747c9fSpatrick       Reg = TRI->findDeadCallerSavedReg(MBB, MBBI);
25509467b48Spatrick 
25609467b48Spatrick     unsigned AddSubRROpc =
25709467b48Spatrick         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
25809467b48Spatrick     if (Reg) {
259*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Reg)
26009467b48Spatrick           .addImm(Offset)
26109467b48Spatrick           .setMIFlag(Flag);
26209467b48Spatrick       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
26309467b48Spatrick                              .addReg(StackPtr)
26409467b48Spatrick                              .addReg(Reg);
26509467b48Spatrick       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
26609467b48Spatrick       return;
26709467b48Spatrick     } else if (Offset > 8 * Chunk) {
26809467b48Spatrick       // If we would need more than 8 add or sub instructions (a >16GB stack
26909467b48Spatrick       // frame), it's worth spilling RAX to materialize this immediate.
27009467b48Spatrick       //   pushq %rax
27109467b48Spatrick       //   movabsq +-$Offset+-SlotSize, %rax
27209467b48Spatrick       //   addq %rsp, %rax
27309467b48Spatrick       //   xchg %rax, (%rsp)
27409467b48Spatrick       //   movq (%rsp), %rsp
27509467b48Spatrick       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
27609467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
27709467b48Spatrick           .addReg(Rax, RegState::Kill)
27809467b48Spatrick           .setMIFlag(Flag);
27909467b48Spatrick       // Subtract is not commutative, so negate the offset and always use add.
28009467b48Spatrick       // Subtract 8 less and add 8 more to account for the PUSH we just did.
28109467b48Spatrick       if (isSub)
28209467b48Spatrick         Offset = -(Offset - SlotSize);
28309467b48Spatrick       else
28409467b48Spatrick         Offset = Offset + SlotSize;
285*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Rax)
28609467b48Spatrick           .addImm(Offset)
28709467b48Spatrick           .setMIFlag(Flag);
28809467b48Spatrick       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
28909467b48Spatrick                              .addReg(Rax)
29009467b48Spatrick                              .addReg(StackPtr);
29109467b48Spatrick       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
29209467b48Spatrick       // Exchange the new SP in RAX with the top of the stack.
29309467b48Spatrick       addRegOffset(
29409467b48Spatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
29509467b48Spatrick           StackPtr, false, 0);
29609467b48Spatrick       // Load new SP from the top of the stack into RSP.
29709467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
29809467b48Spatrick                    StackPtr, false, 0);
29909467b48Spatrick       return;
30009467b48Spatrick     }
30109467b48Spatrick   }
30209467b48Spatrick 
30309467b48Spatrick   while (Offset) {
30409467b48Spatrick     uint64_t ThisVal = std::min(Offset, Chunk);
30509467b48Spatrick     if (ThisVal == SlotSize) {
30609467b48Spatrick       // Use push / pop for slot sized adjustments as a size optimization. We
30709467b48Spatrick       // need to find a dead register when using pop.
30809467b48Spatrick       unsigned Reg = isSub
30909467b48Spatrick         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
310a0747c9fSpatrick         : TRI->findDeadCallerSavedReg(MBB, MBBI);
31109467b48Spatrick       if (Reg) {
31209467b48Spatrick         unsigned Opc = isSub
31309467b48Spatrick           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
31409467b48Spatrick           : (Is64Bit ? X86::POP64r  : X86::POP32r);
31509467b48Spatrick         BuildMI(MBB, MBBI, DL, TII.get(Opc))
31609467b48Spatrick             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
31709467b48Spatrick             .setMIFlag(Flag);
31809467b48Spatrick         Offset -= ThisVal;
31909467b48Spatrick         continue;
32009467b48Spatrick       }
32109467b48Spatrick     }
32209467b48Spatrick 
32309467b48Spatrick     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
32409467b48Spatrick         .setMIFlag(Flag);
32509467b48Spatrick 
32609467b48Spatrick     Offset -= ThisVal;
32709467b48Spatrick   }
32809467b48Spatrick }
32909467b48Spatrick 
BuildStackAdjustment(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,int64_t Offset,bool InEpilogue) const33009467b48Spatrick MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
33109467b48Spatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
33209467b48Spatrick     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
33309467b48Spatrick   assert(Offset != 0 && "zero offset stack adjustment requested");
33409467b48Spatrick 
33509467b48Spatrick   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
33609467b48Spatrick   // is tricky.
33709467b48Spatrick   bool UseLEA;
33809467b48Spatrick   if (!InEpilogue) {
33909467b48Spatrick     // Check if inserting the prologue at the beginning
34009467b48Spatrick     // of MBB would require to use LEA operations.
34109467b48Spatrick     // We need to use LEA operations if EFLAGS is live in, because
34209467b48Spatrick     // it means an instruction will read it before it gets defined.
34309467b48Spatrick     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
34409467b48Spatrick   } else {
34509467b48Spatrick     // If we can use LEA for SP but we shouldn't, check that none
34609467b48Spatrick     // of the terminators uses the eflags. Otherwise we will insert
34709467b48Spatrick     // a ADD that will redefine the eflags and break the condition.
34809467b48Spatrick     // Alternatively, we could move the ADD, but this may not be possible
34909467b48Spatrick     // and is an optimization anyway.
35009467b48Spatrick     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
35109467b48Spatrick     if (UseLEA && !STI.useLeaForSP())
35209467b48Spatrick       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
35309467b48Spatrick     // If that assert breaks, that means we do not do the right thing
35409467b48Spatrick     // in canUseAsEpilogue.
35509467b48Spatrick     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
35609467b48Spatrick            "We shouldn't have allowed this insertion point");
35709467b48Spatrick   }
35809467b48Spatrick 
35909467b48Spatrick   MachineInstrBuilder MI;
36009467b48Spatrick   if (UseLEA) {
36109467b48Spatrick     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
36209467b48Spatrick                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
36309467b48Spatrick                               StackPtr),
36409467b48Spatrick                       StackPtr, false, Offset);
36509467b48Spatrick   } else {
36609467b48Spatrick     bool IsSub = Offset < 0;
36709467b48Spatrick     uint64_t AbsOffset = IsSub ? -Offset : Offset;
368097a140dSpatrick     const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
36909467b48Spatrick                                : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
37009467b48Spatrick     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
37109467b48Spatrick              .addReg(StackPtr)
37209467b48Spatrick              .addImm(AbsOffset);
37309467b48Spatrick     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
37409467b48Spatrick   }
37509467b48Spatrick   return MI;
37609467b48Spatrick }
37709467b48Spatrick 
mergeSPUpdates(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,bool doMergeWithPrevious) const37809467b48Spatrick int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
37909467b48Spatrick                                      MachineBasicBlock::iterator &MBBI,
38009467b48Spatrick                                      bool doMergeWithPrevious) const {
38109467b48Spatrick   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
38209467b48Spatrick       (!doMergeWithPrevious && MBBI == MBB.end()))
38309467b48Spatrick     return 0;
38409467b48Spatrick 
38509467b48Spatrick   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
38609467b48Spatrick 
38709467b48Spatrick   PI = skipDebugInstructionsBackward(PI, MBB.begin());
38809467b48Spatrick   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
38909467b48Spatrick   // instruction, and that there are no DBG_VALUE or other instructions between
39009467b48Spatrick   // ADD/SUB/LEA and its corresponding CFI instruction.
39109467b48Spatrick   /* TODO: Add support for the case where there are multiple CFI instructions
39209467b48Spatrick     below the ADD/SUB/LEA, e.g.:
39309467b48Spatrick     ...
39409467b48Spatrick     add
39509467b48Spatrick     cfi_def_cfa_offset
39609467b48Spatrick     cfi_offset
39709467b48Spatrick     ...
39809467b48Spatrick   */
39909467b48Spatrick   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
40009467b48Spatrick     PI = std::prev(PI);
40109467b48Spatrick 
40209467b48Spatrick   unsigned Opc = PI->getOpcode();
40309467b48Spatrick   int Offset = 0;
40409467b48Spatrick 
40509467b48Spatrick   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
40609467b48Spatrick        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
40709467b48Spatrick       PI->getOperand(0).getReg() == StackPtr){
40809467b48Spatrick     assert(PI->getOperand(1).getReg() == StackPtr);
40909467b48Spatrick     Offset = PI->getOperand(2).getImm();
41009467b48Spatrick   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
41109467b48Spatrick              PI->getOperand(0).getReg() == StackPtr &&
41209467b48Spatrick              PI->getOperand(1).getReg() == StackPtr &&
41309467b48Spatrick              PI->getOperand(2).getImm() == 1 &&
41409467b48Spatrick              PI->getOperand(3).getReg() == X86::NoRegister &&
41509467b48Spatrick              PI->getOperand(5).getReg() == X86::NoRegister) {
41609467b48Spatrick     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
41709467b48Spatrick     Offset = PI->getOperand(4).getImm();
41809467b48Spatrick   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
41909467b48Spatrick               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
42009467b48Spatrick              PI->getOperand(0).getReg() == StackPtr) {
42109467b48Spatrick     assert(PI->getOperand(1).getReg() == StackPtr);
42209467b48Spatrick     Offset = -PI->getOperand(2).getImm();
42309467b48Spatrick   } else
42409467b48Spatrick     return 0;
42509467b48Spatrick 
42609467b48Spatrick   PI = MBB.erase(PI);
427a0747c9fSpatrick   if (PI != MBB.end() && PI->isCFIInstruction()) {
428a0747c9fSpatrick     auto CIs = MBB.getParent()->getFrameInstructions();
429a0747c9fSpatrick     MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()];
430a0747c9fSpatrick     if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset ||
431a0747c9fSpatrick         CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
432a0747c9fSpatrick       PI = MBB.erase(PI);
433a0747c9fSpatrick   }
43409467b48Spatrick   if (!doMergeWithPrevious)
43509467b48Spatrick     MBBI = skipDebugInstructionsForward(PI, MBB.end());
43609467b48Spatrick 
43709467b48Spatrick   return Offset;
43809467b48Spatrick }
43909467b48Spatrick 
BuildCFI(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,const MCCFIInstruction & CFIInst,MachineInstr::MIFlag Flag) const44009467b48Spatrick void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
44109467b48Spatrick                                 MachineBasicBlock::iterator MBBI,
44209467b48Spatrick                                 const DebugLoc &DL,
443*a96b3639Srobert                                 const MCCFIInstruction &CFIInst,
444*a96b3639Srobert                                 MachineInstr::MIFlag Flag) const {
44509467b48Spatrick   MachineFunction &MF = *MBB.getParent();
44609467b48Spatrick   unsigned CFIIndex = MF.addFrameInst(CFIInst);
44709467b48Spatrick   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
448*a96b3639Srobert       .addCFIIndex(CFIIndex)
449*a96b3639Srobert       .setMIFlag(Flag);
45009467b48Spatrick }
45109467b48Spatrick 
452097a140dSpatrick /// Emits Dwarf Info specifying offsets of callee saved registers and
453097a140dSpatrick /// frame pointer. This is called only when basic block sections are enabled.
emitCalleeSavedFrameMovesFullCFA(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI) const454*a96b3639Srobert void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA(
455097a140dSpatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
456097a140dSpatrick   MachineFunction &MF = *MBB.getParent();
457097a140dSpatrick   if (!hasFP(MF)) {
458097a140dSpatrick     emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
459097a140dSpatrick     return;
460097a140dSpatrick   }
461097a140dSpatrick   const MachineModuleInfo &MMI = MF.getMMI();
462097a140dSpatrick   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
463a0747c9fSpatrick   const Register FramePtr = TRI->getFrameRegister(MF);
464a0747c9fSpatrick   const Register MachineFramePtr =
465a0747c9fSpatrick       STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
466097a140dSpatrick                                : FramePtr;
467097a140dSpatrick   unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true);
468097a140dSpatrick   // Offset = space for return address + size of the frame pointer itself.
469097a140dSpatrick   unsigned Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
470097a140dSpatrick   BuildCFI(MBB, MBBI, DebugLoc{},
471097a140dSpatrick            MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset));
472097a140dSpatrick   emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
473097a140dSpatrick }
474097a140dSpatrick 
emitCalleeSavedFrameMoves(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool IsPrologue) const47509467b48Spatrick void X86FrameLowering::emitCalleeSavedFrameMoves(
47609467b48Spatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
477097a140dSpatrick     const DebugLoc &DL, bool IsPrologue) const {
47809467b48Spatrick   MachineFunction &MF = *MBB.getParent();
47909467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
48009467b48Spatrick   MachineModuleInfo &MMI = MF.getMMI();
48109467b48Spatrick   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
48209467b48Spatrick 
48309467b48Spatrick   // Add callee saved registers to move list.
48409467b48Spatrick   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
48509467b48Spatrick 
48609467b48Spatrick   // Calculate offsets.
487*a96b3639Srobert   for (const CalleeSavedInfo &I : CSI) {
488*a96b3639Srobert     int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
489*a96b3639Srobert     Register Reg = I.getReg();
49009467b48Spatrick     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
491097a140dSpatrick 
492097a140dSpatrick     if (IsPrologue) {
49309467b48Spatrick       BuildCFI(MBB, MBBI, DL,
49409467b48Spatrick                MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
495097a140dSpatrick     } else {
496097a140dSpatrick       BuildCFI(MBB, MBBI, DL,
497097a140dSpatrick                MCCFIInstruction::createRestore(nullptr, DwarfReg));
498097a140dSpatrick     }
49909467b48Spatrick   }
50009467b48Spatrick }
50109467b48Spatrick 
emitZeroCallUsedRegs(BitVector RegsToZero,MachineBasicBlock & MBB) const502*a96b3639Srobert void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
503*a96b3639Srobert                                             MachineBasicBlock &MBB) const {
504*a96b3639Srobert   const MachineFunction &MF = *MBB.getParent();
505*a96b3639Srobert 
506*a96b3639Srobert   // Insertion point.
507*a96b3639Srobert   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
508*a96b3639Srobert 
509*a96b3639Srobert   // Fake a debug loc.
510*a96b3639Srobert   DebugLoc DL;
511*a96b3639Srobert   if (MBBI != MBB.end())
512*a96b3639Srobert     DL = MBBI->getDebugLoc();
513*a96b3639Srobert 
514*a96b3639Srobert   // Zero out FP stack if referenced. Do this outside of the loop below so that
515*a96b3639Srobert   // it's done only once.
516*a96b3639Srobert   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
517*a96b3639Srobert   for (MCRegister Reg : RegsToZero.set_bits()) {
518*a96b3639Srobert     if (!X86::RFP80RegClass.contains(Reg))
519*a96b3639Srobert       continue;
520*a96b3639Srobert 
521*a96b3639Srobert     unsigned NumFPRegs = ST.is64Bit() ? 8 : 7;
522*a96b3639Srobert     for (unsigned i = 0; i != NumFPRegs; ++i)
523*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0));
524*a96b3639Srobert 
525*a96b3639Srobert     for (unsigned i = 0; i != NumFPRegs; ++i)
526*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0);
527*a96b3639Srobert     break;
528*a96b3639Srobert   }
529*a96b3639Srobert 
530*a96b3639Srobert   // For GPRs, we only care to clear out the 32-bit register.
531*a96b3639Srobert   BitVector GPRsToZero(TRI->getNumRegs());
532*a96b3639Srobert   for (MCRegister Reg : RegsToZero.set_bits())
533*a96b3639Srobert     if (TRI->isGeneralPurposeRegister(MF, Reg)) {
534*a96b3639Srobert       GPRsToZero.set(getX86SubSuperRegisterOrZero(Reg, 32));
535*a96b3639Srobert       RegsToZero.reset(Reg);
536*a96b3639Srobert     }
537*a96b3639Srobert 
538*a96b3639Srobert   for (MCRegister Reg : GPRsToZero.set_bits())
539*a96b3639Srobert     BuildMI(MBB, MBBI, DL, TII.get(X86::XOR32rr), Reg)
540*a96b3639Srobert         .addReg(Reg, RegState::Undef)
541*a96b3639Srobert         .addReg(Reg, RegState::Undef);
542*a96b3639Srobert 
543*a96b3639Srobert   // Zero out registers.
544*a96b3639Srobert   for (MCRegister Reg : RegsToZero.set_bits()) {
545*a96b3639Srobert     if (ST.hasMMX() && X86::VR64RegClass.contains(Reg))
546*a96b3639Srobert       // FIXME: Ignore MMX registers?
547*a96b3639Srobert       continue;
548*a96b3639Srobert 
549*a96b3639Srobert     unsigned XorOp;
550*a96b3639Srobert     if (X86::VR128RegClass.contains(Reg)) {
551*a96b3639Srobert       // XMM#
552*a96b3639Srobert       if (!ST.hasSSE1())
553*a96b3639Srobert         continue;
554*a96b3639Srobert       XorOp = X86::PXORrr;
555*a96b3639Srobert     } else if (X86::VR256RegClass.contains(Reg)) {
556*a96b3639Srobert       // YMM#
557*a96b3639Srobert       if (!ST.hasAVX())
558*a96b3639Srobert         continue;
559*a96b3639Srobert       XorOp = X86::VPXORrr;
560*a96b3639Srobert     } else if (X86::VR512RegClass.contains(Reg)) {
561*a96b3639Srobert       // ZMM#
562*a96b3639Srobert       if (!ST.hasAVX512())
563*a96b3639Srobert         continue;
564*a96b3639Srobert       XorOp = X86::VPXORYrr;
565*a96b3639Srobert     } else if (X86::VK1RegClass.contains(Reg) ||
566*a96b3639Srobert                X86::VK2RegClass.contains(Reg) ||
567*a96b3639Srobert                X86::VK4RegClass.contains(Reg) ||
568*a96b3639Srobert                X86::VK8RegClass.contains(Reg) ||
569*a96b3639Srobert                X86::VK16RegClass.contains(Reg)) {
570*a96b3639Srobert       if (!ST.hasVLX())
571*a96b3639Srobert         continue;
572*a96b3639Srobert       XorOp = ST.hasBWI() ? X86::KXORQrr : X86::KXORWrr;
573*a96b3639Srobert     } else {
574*a96b3639Srobert       continue;
575*a96b3639Srobert     }
576*a96b3639Srobert 
577*a96b3639Srobert     BuildMI(MBB, MBBI, DL, TII.get(XorOp), Reg)
578*a96b3639Srobert       .addReg(Reg, RegState::Undef)
579*a96b3639Srobert       .addReg(Reg, RegState::Undef);
580*a96b3639Srobert   }
581*a96b3639Srobert }
582*a96b3639Srobert 
emitStackProbe(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool InProlog,std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const583*a96b3639Srobert void X86FrameLowering::emitStackProbe(
584*a96b3639Srobert     MachineFunction &MF, MachineBasicBlock &MBB,
585*a96b3639Srobert     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
586*a96b3639Srobert     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
58709467b48Spatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
58809467b48Spatrick   if (STI.isTargetWindowsCoreCLR()) {
58909467b48Spatrick     if (InProlog) {
590097a140dSpatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING))
591097a140dSpatrick           .addImm(0 /* no explicit stack size */);
59209467b48Spatrick     } else {
59309467b48Spatrick       emitStackProbeInline(MF, MBB, MBBI, DL, false);
59409467b48Spatrick     }
59509467b48Spatrick   } else {
596*a96b3639Srobert     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
59709467b48Spatrick   }
59809467b48Spatrick }
59909467b48Spatrick 
stackProbeFunctionModifiesSP() const600*a96b3639Srobert bool X86FrameLowering::stackProbeFunctionModifiesSP() const {
601*a96b3639Srobert   return STI.isOSWindows() && !STI.isTargetWin64();
602*a96b3639Srobert }
603*a96b3639Srobert 
inlineStackProbe(MachineFunction & MF,MachineBasicBlock & PrologMBB) const60409467b48Spatrick void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
60509467b48Spatrick                                         MachineBasicBlock &PrologMBB) const {
606097a140dSpatrick   auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
607097a140dSpatrick     return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
608097a140dSpatrick   });
609097a140dSpatrick   if (Where != PrologMBB.end()) {
610097a140dSpatrick     DebugLoc DL = PrologMBB.findDebugLoc(Where);
611097a140dSpatrick     emitStackProbeInline(MF, PrologMBB, Where, DL, true);
612097a140dSpatrick     Where->eraseFromParent();
61309467b48Spatrick   }
61409467b48Spatrick }
61509467b48Spatrick 
emitStackProbeInline(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool InProlog) const61609467b48Spatrick void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
61709467b48Spatrick                                             MachineBasicBlock &MBB,
61809467b48Spatrick                                             MachineBasicBlock::iterator MBBI,
61909467b48Spatrick                                             const DebugLoc &DL,
62009467b48Spatrick                                             bool InProlog) const {
62109467b48Spatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
622097a140dSpatrick   if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
623097a140dSpatrick     emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
624097a140dSpatrick   else
625097a140dSpatrick     emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
626097a140dSpatrick }
627097a140dSpatrick 
emitStackProbeInlineGeneric(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool InProlog) const628097a140dSpatrick void X86FrameLowering::emitStackProbeInlineGeneric(
629097a140dSpatrick     MachineFunction &MF, MachineBasicBlock &MBB,
630097a140dSpatrick     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
631097a140dSpatrick   MachineInstr &AllocWithProbe = *MBBI;
632097a140dSpatrick   uint64_t Offset = AllocWithProbe.getOperand(0).getImm();
633097a140dSpatrick 
634097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
635097a140dSpatrick   const X86TargetLowering &TLI = *STI.getTargetLowering();
636097a140dSpatrick   assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
637097a140dSpatrick          "different expansion expected for CoreCLR 64 bit");
638097a140dSpatrick 
639097a140dSpatrick   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
640097a140dSpatrick   uint64_t ProbeChunk = StackProbeSize * 8;
641097a140dSpatrick 
642097a140dSpatrick   uint64_t MaxAlign =
643a0747c9fSpatrick       TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
644097a140dSpatrick 
645097a140dSpatrick   // Synthesize a loop or unroll it, depending on the number of iterations.
646097a140dSpatrick   // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
647097a140dSpatrick   // between the unaligned rsp and current rsp.
648097a140dSpatrick   if (Offset > ProbeChunk) {
649097a140dSpatrick     emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
650097a140dSpatrick                                     MaxAlign % StackProbeSize);
651097a140dSpatrick   } else {
652097a140dSpatrick     emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
653097a140dSpatrick                                      MaxAlign % StackProbeSize);
654097a140dSpatrick   }
655097a140dSpatrick }
656097a140dSpatrick 
emitStackProbeInlineGenericBlock(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,uint64_t Offset,uint64_t AlignOffset) const657097a140dSpatrick void X86FrameLowering::emitStackProbeInlineGenericBlock(
658097a140dSpatrick     MachineFunction &MF, MachineBasicBlock &MBB,
659097a140dSpatrick     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
660097a140dSpatrick     uint64_t AlignOffset) const {
661097a140dSpatrick 
662a0747c9fSpatrick   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
663a0747c9fSpatrick   const bool HasFP = hasFP(MF);
664097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
665097a140dSpatrick   const X86TargetLowering &TLI = *STI.getTargetLowering();
666097a140dSpatrick   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
667097a140dSpatrick   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
668097a140dSpatrick 
669097a140dSpatrick   uint64_t CurrentOffset = 0;
670097a140dSpatrick 
671097a140dSpatrick   assert(AlignOffset < StackProbeSize);
672097a140dSpatrick 
673097a140dSpatrick   // If the offset is so small it fits within a page, there's nothing to do.
674097a140dSpatrick   if (StackProbeSize < Offset + AlignOffset) {
675097a140dSpatrick 
676*a96b3639Srobert     uint64_t StackAdjustment = StackProbeSize - AlignOffset;
677*a96b3639Srobert     BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
678097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
679a0747c9fSpatrick     if (!HasFP && NeedsDwarfCFI) {
680*a96b3639Srobert       BuildCFI(
681*a96b3639Srobert           MBB, MBBI, DL,
682*a96b3639Srobert           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
683a0747c9fSpatrick     }
684097a140dSpatrick 
685097a140dSpatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
686097a140dSpatrick                      .setMIFlag(MachineInstr::FrameSetup),
687097a140dSpatrick                  StackPtr, false, 0)
688097a140dSpatrick         .addImm(0)
689097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
690097a140dSpatrick     NumFrameExtraProbe++;
691097a140dSpatrick     CurrentOffset = StackProbeSize - AlignOffset;
692097a140dSpatrick   }
693097a140dSpatrick 
694097a140dSpatrick   // For the next N - 1 pages, just probe. I tried to take advantage of
695097a140dSpatrick   // natural probes but it implies much more logic and there was very few
696097a140dSpatrick   // interesting natural probes to interleave.
697097a140dSpatrick   while (CurrentOffset + StackProbeSize < Offset) {
698*a96b3639Srobert     BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
699097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
700097a140dSpatrick 
701a0747c9fSpatrick     if (!HasFP && NeedsDwarfCFI) {
702a0747c9fSpatrick       BuildCFI(
703a0747c9fSpatrick           MBB, MBBI, DL,
704a0747c9fSpatrick           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
705a0747c9fSpatrick     }
706097a140dSpatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
707097a140dSpatrick                      .setMIFlag(MachineInstr::FrameSetup),
708097a140dSpatrick                  StackPtr, false, 0)
709097a140dSpatrick         .addImm(0)
710097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
711097a140dSpatrick     NumFrameExtraProbe++;
712097a140dSpatrick     CurrentOffset += StackProbeSize;
713097a140dSpatrick   }
714097a140dSpatrick 
715097a140dSpatrick   // No need to probe the tail, it is smaller than a Page.
716097a140dSpatrick   uint64_t ChunkSize = Offset - CurrentOffset;
717*a96b3639Srobert   if (ChunkSize == SlotSize) {
718*a96b3639Srobert     // Use push for slot sized adjustments as a size optimization,
719*a96b3639Srobert     // like emitSPUpdate does when not probing.
720*a96b3639Srobert     unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
721*a96b3639Srobert     unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
722*a96b3639Srobert     BuildMI(MBB, MBBI, DL, TII.get(Opc))
723*a96b3639Srobert         .addReg(Reg, RegState::Undef)
724097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
725*a96b3639Srobert   } else {
726*a96b3639Srobert     BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
727*a96b3639Srobert         .setMIFlag(MachineInstr::FrameSetup);
728*a96b3639Srobert   }
729a0747c9fSpatrick   // No need to adjust Dwarf CFA offset here, the last position of the stack has
730a0747c9fSpatrick   // been defined
731097a140dSpatrick }
732097a140dSpatrick 
emitStackProbeInlineGenericLoop(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,uint64_t Offset,uint64_t AlignOffset) const733097a140dSpatrick void X86FrameLowering::emitStackProbeInlineGenericLoop(
734097a140dSpatrick     MachineFunction &MF, MachineBasicBlock &MBB,
735097a140dSpatrick     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
736097a140dSpatrick     uint64_t AlignOffset) const {
737097a140dSpatrick   assert(Offset && "null offset");
738097a140dSpatrick 
739*a96b3639Srobert   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
740*a96b3639Srobert              MachineBasicBlock::LQR_Live &&
741*a96b3639Srobert          "Inline stack probe loop will clobber live EFLAGS.");
742*a96b3639Srobert 
743*a96b3639Srobert   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
744*a96b3639Srobert   const bool HasFP = hasFP(MF);
745097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
746097a140dSpatrick   const X86TargetLowering &TLI = *STI.getTargetLowering();
747097a140dSpatrick   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
748097a140dSpatrick   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
749097a140dSpatrick 
750097a140dSpatrick   if (AlignOffset) {
751097a140dSpatrick     if (AlignOffset < StackProbeSize) {
752097a140dSpatrick       // Perform a first smaller allocation followed by a probe.
753*a96b3639Srobert       BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
754097a140dSpatrick           .setMIFlag(MachineInstr::FrameSetup);
755097a140dSpatrick 
756097a140dSpatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
757097a140dSpatrick                        .setMIFlag(MachineInstr::FrameSetup),
758097a140dSpatrick                    StackPtr, false, 0)
759097a140dSpatrick           .addImm(0)
760097a140dSpatrick           .setMIFlag(MachineInstr::FrameSetup);
761097a140dSpatrick       NumFrameExtraProbe++;
762097a140dSpatrick       Offset -= AlignOffset;
763097a140dSpatrick     }
764097a140dSpatrick   }
765097a140dSpatrick 
766097a140dSpatrick   // Synthesize a loop
767097a140dSpatrick   NumFrameLoopProbe++;
768097a140dSpatrick   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
769097a140dSpatrick 
770097a140dSpatrick   MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
771097a140dSpatrick   MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
772097a140dSpatrick 
773097a140dSpatrick   MachineFunction::iterator MBBIter = ++MBB.getIterator();
774097a140dSpatrick   MF.insert(MBBIter, testMBB);
775097a140dSpatrick   MF.insert(MBBIter, tailMBB);
776097a140dSpatrick 
777a0747c9fSpatrick   Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
778a0747c9fSpatrick                               : Is64Bit         ? X86::R11D
779a0747c9fSpatrick                                                 : X86::EAX;
780*a96b3639Srobert 
781097a140dSpatrick   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
782097a140dSpatrick       .addReg(StackPtr)
783097a140dSpatrick       .setMIFlag(MachineInstr::FrameSetup);
784097a140dSpatrick 
785097a140dSpatrick   // save loop bound
786097a140dSpatrick   {
787*a96b3639Srobert     const unsigned BoundOffset = alignDown(Offset, StackProbeSize);
788*a96b3639Srobert     const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr, BoundOffset);
789097a140dSpatrick     BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
790097a140dSpatrick         .addReg(FinalStackProbed)
791*a96b3639Srobert         .addImm(BoundOffset)
792097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
793*a96b3639Srobert 
794*a96b3639Srobert     // while in the loop, use loop-invariant reg for CFI,
795*a96b3639Srobert     // instead of the stack pointer, which changes during the loop
796*a96b3639Srobert     if (!HasFP && NeedsDwarfCFI) {
797*a96b3639Srobert       // x32 uses the same DWARF register numbers as x86-64,
798*a96b3639Srobert       // so there isn't a register number for r11d, we must use r11 instead
799*a96b3639Srobert       const Register DwarfFinalStackProbed =
800*a96b3639Srobert           STI.isTarget64BitILP32()
801*a96b3639Srobert               ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
802*a96b3639Srobert               : FinalStackProbed;
803*a96b3639Srobert 
804*a96b3639Srobert       BuildCFI(MBB, MBBI, DL,
805*a96b3639Srobert                MCCFIInstruction::createDefCfaRegister(
806*a96b3639Srobert                    nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
807*a96b3639Srobert       BuildCFI(MBB, MBBI, DL,
808*a96b3639Srobert                MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
809*a96b3639Srobert     }
810097a140dSpatrick   }
811097a140dSpatrick 
812097a140dSpatrick   // allocate a page
813*a96b3639Srobert   BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
814*a96b3639Srobert                        /*InEpilogue=*/false)
815097a140dSpatrick       .setMIFlag(MachineInstr::FrameSetup);
816097a140dSpatrick 
817097a140dSpatrick   // touch the page
818097a140dSpatrick   addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
819097a140dSpatrick                    .setMIFlag(MachineInstr::FrameSetup),
820097a140dSpatrick                StackPtr, false, 0)
821097a140dSpatrick       .addImm(0)
822097a140dSpatrick       .setMIFlag(MachineInstr::FrameSetup);
823097a140dSpatrick 
824097a140dSpatrick   // cmp with stack pointer bound
825097a140dSpatrick   BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
826097a140dSpatrick       .addReg(StackPtr)
827097a140dSpatrick       .addReg(FinalStackProbed)
828097a140dSpatrick       .setMIFlag(MachineInstr::FrameSetup);
829097a140dSpatrick 
830097a140dSpatrick   // jump
831097a140dSpatrick   BuildMI(testMBB, DL, TII.get(X86::JCC_1))
832097a140dSpatrick       .addMBB(testMBB)
833097a140dSpatrick       .addImm(X86::COND_NE)
834097a140dSpatrick       .setMIFlag(MachineInstr::FrameSetup);
835097a140dSpatrick   testMBB->addSuccessor(testMBB);
836097a140dSpatrick   testMBB->addSuccessor(tailMBB);
837097a140dSpatrick 
838097a140dSpatrick   // BB management
839097a140dSpatrick   tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
840097a140dSpatrick   tailMBB->transferSuccessorsAndUpdatePHIs(&MBB);
841097a140dSpatrick   MBB.addSuccessor(testMBB);
842097a140dSpatrick 
843097a140dSpatrick   // handle tail
844*a96b3639Srobert   const uint64_t TailOffset = Offset % StackProbeSize;
845*a96b3639Srobert   MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
846097a140dSpatrick   if (TailOffset) {
847*a96b3639Srobert     BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
848*a96b3639Srobert                          /*InEpilogue=*/false)
849097a140dSpatrick         .setMIFlag(MachineInstr::FrameSetup);
850097a140dSpatrick   }
851097a140dSpatrick 
852*a96b3639Srobert   // after the loop, switch back to stack pointer for CFI
853*a96b3639Srobert   if (!HasFP && NeedsDwarfCFI) {
854*a96b3639Srobert     // x32 uses the same DWARF register numbers as x86-64,
855*a96b3639Srobert     // so there isn't a register number for esp, we must use rsp instead
856*a96b3639Srobert     const Register DwarfStackPtr =
857*a96b3639Srobert         STI.isTarget64BitILP32()
858*a96b3639Srobert             ? Register(getX86SubSuperRegister(StackPtr, 64))
859*a96b3639Srobert             : Register(StackPtr);
860*a96b3639Srobert 
861*a96b3639Srobert     BuildCFI(*tailMBB, TailMBBIter, DL,
862*a96b3639Srobert              MCCFIInstruction::createDefCfaRegister(
863*a96b3639Srobert                  nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
864*a96b3639Srobert   }
865*a96b3639Srobert 
866097a140dSpatrick   // Update Live In information
867097a140dSpatrick   recomputeLiveIns(*testMBB);
868097a140dSpatrick   recomputeLiveIns(*tailMBB);
869097a140dSpatrick }
870097a140dSpatrick 
emitStackProbeInlineWindowsCoreCLR64(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool InProlog) const871097a140dSpatrick void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
872097a140dSpatrick     MachineFunction &MF, MachineBasicBlock &MBB,
873097a140dSpatrick     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
874097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
87509467b48Spatrick   assert(STI.is64Bit() && "different expansion needed for 32 bit");
87609467b48Spatrick   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
87709467b48Spatrick   const TargetInstrInfo &TII = *STI.getInstrInfo();
87809467b48Spatrick   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
87909467b48Spatrick 
880*a96b3639Srobert   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
881*a96b3639Srobert              MachineBasicBlock::LQR_Live &&
882*a96b3639Srobert          "Inline stack probe loop will clobber live EFLAGS.");
883*a96b3639Srobert 
88409467b48Spatrick   // RAX contains the number of bytes of desired stack adjustment.
88509467b48Spatrick   // The handling here assumes this value has already been updated so as to
88609467b48Spatrick   // maintain stack alignment.
88709467b48Spatrick   //
88809467b48Spatrick   // We need to exit with RSP modified by this amount and execute suitable
88909467b48Spatrick   // page touches to notify the OS that we're growing the stack responsibly.
89009467b48Spatrick   // All stack probing must be done without modifying RSP.
89109467b48Spatrick   //
89209467b48Spatrick   // MBB:
89309467b48Spatrick   //    SizeReg = RAX;
89409467b48Spatrick   //    ZeroReg = 0
89509467b48Spatrick   //    CopyReg = RSP
89609467b48Spatrick   //    Flags, TestReg = CopyReg - SizeReg
89709467b48Spatrick   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
89809467b48Spatrick   //    LimitReg = gs magic thread env access
89909467b48Spatrick   //    if FinalReg >= LimitReg goto ContinueMBB
90009467b48Spatrick   // RoundBB:
90109467b48Spatrick   //    RoundReg = page address of FinalReg
90209467b48Spatrick   // LoopMBB:
90309467b48Spatrick   //    LoopReg = PHI(LimitReg,ProbeReg)
90409467b48Spatrick   //    ProbeReg = LoopReg - PageSize
90509467b48Spatrick   //    [ProbeReg] = 0
90609467b48Spatrick   //    if (ProbeReg > RoundReg) goto LoopMBB
90709467b48Spatrick   // ContinueMBB:
90809467b48Spatrick   //    RSP = RSP - RAX
90909467b48Spatrick   //    [rest of original MBB]
91009467b48Spatrick 
91109467b48Spatrick   // Set up the new basic blocks
91209467b48Spatrick   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
91309467b48Spatrick   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
91409467b48Spatrick   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
91509467b48Spatrick 
91609467b48Spatrick   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
91709467b48Spatrick   MF.insert(MBBIter, RoundMBB);
91809467b48Spatrick   MF.insert(MBBIter, LoopMBB);
91909467b48Spatrick   MF.insert(MBBIter, ContinueMBB);
92009467b48Spatrick 
92109467b48Spatrick   // Split MBB and move the tail portion down to ContinueMBB.
92209467b48Spatrick   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
92309467b48Spatrick   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
92409467b48Spatrick   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
92509467b48Spatrick 
92609467b48Spatrick   // Some useful constants
92709467b48Spatrick   const int64_t ThreadEnvironmentStackLimit = 0x10;
92809467b48Spatrick   const int64_t PageSize = 0x1000;
92909467b48Spatrick   const int64_t PageMask = ~(PageSize - 1);
93009467b48Spatrick 
93109467b48Spatrick   // Registers we need. For the normal case we use virtual
93209467b48Spatrick   // registers. For the prolog expansion we use RAX, RCX and RDX.
93309467b48Spatrick   MachineRegisterInfo &MRI = MF.getRegInfo();
93409467b48Spatrick   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
93509467b48Spatrick   const Register SizeReg = InProlog ? X86::RAX
93609467b48Spatrick                                     : MRI.createVirtualRegister(RegClass),
93709467b48Spatrick                  ZeroReg = InProlog ? X86::RCX
93809467b48Spatrick                                     : MRI.createVirtualRegister(RegClass),
93909467b48Spatrick                  CopyReg = InProlog ? X86::RDX
94009467b48Spatrick                                     : MRI.createVirtualRegister(RegClass),
94109467b48Spatrick                  TestReg = InProlog ? X86::RDX
94209467b48Spatrick                                     : MRI.createVirtualRegister(RegClass),
94309467b48Spatrick                  FinalReg = InProlog ? X86::RDX
94409467b48Spatrick                                      : MRI.createVirtualRegister(RegClass),
94509467b48Spatrick                  RoundedReg = InProlog ? X86::RDX
94609467b48Spatrick                                        : MRI.createVirtualRegister(RegClass),
94709467b48Spatrick                  LimitReg = InProlog ? X86::RCX
94809467b48Spatrick                                      : MRI.createVirtualRegister(RegClass),
94909467b48Spatrick                  JoinReg = InProlog ? X86::RCX
95009467b48Spatrick                                     : MRI.createVirtualRegister(RegClass),
95109467b48Spatrick                  ProbeReg = InProlog ? X86::RCX
95209467b48Spatrick                                      : MRI.createVirtualRegister(RegClass);
95309467b48Spatrick 
95409467b48Spatrick   // SP-relative offsets where we can save RCX and RDX.
95509467b48Spatrick   int64_t RCXShadowSlot = 0;
95609467b48Spatrick   int64_t RDXShadowSlot = 0;
95709467b48Spatrick 
95809467b48Spatrick   // If inlining in the prolog, save RCX and RDX.
95909467b48Spatrick   if (InProlog) {
96009467b48Spatrick     // Compute the offsets. We need to account for things already
96109467b48Spatrick     // pushed onto the stack at this point: return address, frame
96209467b48Spatrick     // pointer (if used), and callee saves.
96309467b48Spatrick     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
96409467b48Spatrick     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
96509467b48Spatrick     const bool HasFP = hasFP(MF);
96609467b48Spatrick 
96709467b48Spatrick     // Check if we need to spill RCX and/or RDX.
96809467b48Spatrick     // Here we assume that no earlier prologue instruction changes RCX and/or
96909467b48Spatrick     // RDX, so checking the block live-ins is enough.
97009467b48Spatrick     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
97109467b48Spatrick     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
97209467b48Spatrick     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
97309467b48Spatrick     // Assign the initial slot to both registers, then change RDX's slot if both
97409467b48Spatrick     // need to be spilled.
97509467b48Spatrick     if (IsRCXLiveIn)
97609467b48Spatrick       RCXShadowSlot = InitSlot;
97709467b48Spatrick     if (IsRDXLiveIn)
97809467b48Spatrick       RDXShadowSlot = InitSlot;
97909467b48Spatrick     if (IsRDXLiveIn && IsRCXLiveIn)
98009467b48Spatrick       RDXShadowSlot += 8;
98109467b48Spatrick     // Emit the saves if needed.
98209467b48Spatrick     if (IsRCXLiveIn)
98309467b48Spatrick       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
98409467b48Spatrick                    RCXShadowSlot)
98509467b48Spatrick           .addReg(X86::RCX);
98609467b48Spatrick     if (IsRDXLiveIn)
98709467b48Spatrick       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
98809467b48Spatrick                    RDXShadowSlot)
98909467b48Spatrick           .addReg(X86::RDX);
99009467b48Spatrick   } else {
99109467b48Spatrick     // Not in the prolog. Copy RAX to a virtual reg.
99209467b48Spatrick     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
99309467b48Spatrick   }
99409467b48Spatrick 
99509467b48Spatrick   // Add code to MBB to check for overflow and set the new target stack pointer
99609467b48Spatrick   // to zero if so.
99709467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
99809467b48Spatrick       .addReg(ZeroReg, RegState::Undef)
99909467b48Spatrick       .addReg(ZeroReg, RegState::Undef);
100009467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
100109467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
100209467b48Spatrick       .addReg(CopyReg)
100309467b48Spatrick       .addReg(SizeReg);
100409467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
100509467b48Spatrick       .addReg(TestReg)
100609467b48Spatrick       .addReg(ZeroReg)
100709467b48Spatrick       .addImm(X86::COND_B);
100809467b48Spatrick 
100909467b48Spatrick   // FinalReg now holds final stack pointer value, or zero if
101009467b48Spatrick   // allocation would overflow. Compare against the current stack
101109467b48Spatrick   // limit from the thread environment block. Note this limit is the
101209467b48Spatrick   // lowest touched page on the stack, not the point at which the OS
101309467b48Spatrick   // will cause an overflow exception, so this is just an optimization
101409467b48Spatrick   // to avoid unnecessarily touching pages that are below the current
101509467b48Spatrick   // SP but already committed to the stack by the OS.
101609467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
101709467b48Spatrick       .addReg(0)
101809467b48Spatrick       .addImm(1)
101909467b48Spatrick       .addReg(0)
102009467b48Spatrick       .addImm(ThreadEnvironmentStackLimit)
102109467b48Spatrick       .addReg(X86::GS);
102209467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
102309467b48Spatrick   // Jump if the desired stack pointer is at or above the stack limit.
102409467b48Spatrick   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
102509467b48Spatrick 
102609467b48Spatrick   // Add code to roundMBB to round the final stack pointer to a page boundary.
102709467b48Spatrick   RoundMBB->addLiveIn(FinalReg);
102809467b48Spatrick   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
102909467b48Spatrick       .addReg(FinalReg)
103009467b48Spatrick       .addImm(PageMask);
103109467b48Spatrick   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
103209467b48Spatrick 
103309467b48Spatrick   // LimitReg now holds the current stack limit, RoundedReg page-rounded
103409467b48Spatrick   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
103509467b48Spatrick   // and probe until we reach RoundedReg.
103609467b48Spatrick   if (!InProlog) {
103709467b48Spatrick     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
103809467b48Spatrick         .addReg(LimitReg)
103909467b48Spatrick         .addMBB(RoundMBB)
104009467b48Spatrick         .addReg(ProbeReg)
104109467b48Spatrick         .addMBB(LoopMBB);
104209467b48Spatrick   }
104309467b48Spatrick 
104409467b48Spatrick   LoopMBB->addLiveIn(JoinReg);
104509467b48Spatrick   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
104609467b48Spatrick                false, -PageSize);
104709467b48Spatrick 
104809467b48Spatrick   // Probe by storing a byte onto the stack.
104909467b48Spatrick   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
105009467b48Spatrick       .addReg(ProbeReg)
105109467b48Spatrick       .addImm(1)
105209467b48Spatrick       .addReg(0)
105309467b48Spatrick       .addImm(0)
105409467b48Spatrick       .addReg(0)
105509467b48Spatrick       .addImm(0);
105609467b48Spatrick 
105709467b48Spatrick   LoopMBB->addLiveIn(RoundedReg);
105809467b48Spatrick   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
105909467b48Spatrick       .addReg(RoundedReg)
106009467b48Spatrick       .addReg(ProbeReg);
106109467b48Spatrick   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
106209467b48Spatrick 
106309467b48Spatrick   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
106409467b48Spatrick 
106509467b48Spatrick   // If in prolog, restore RDX and RCX.
106609467b48Spatrick   if (InProlog) {
106709467b48Spatrick     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
106809467b48Spatrick       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
106909467b48Spatrick                            TII.get(X86::MOV64rm), X86::RCX),
107009467b48Spatrick                    X86::RSP, false, RCXShadowSlot);
107109467b48Spatrick     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
107209467b48Spatrick       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
107309467b48Spatrick                            TII.get(X86::MOV64rm), X86::RDX),
107409467b48Spatrick                    X86::RSP, false, RDXShadowSlot);
107509467b48Spatrick   }
107609467b48Spatrick 
107709467b48Spatrick   // Now that the probing is done, add code to continueMBB to update
107809467b48Spatrick   // the stack pointer for real.
107909467b48Spatrick   ContinueMBB->addLiveIn(SizeReg);
108009467b48Spatrick   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
108109467b48Spatrick       .addReg(X86::RSP)
108209467b48Spatrick       .addReg(SizeReg);
108309467b48Spatrick 
108409467b48Spatrick   // Add the control flow edges we need.
108509467b48Spatrick   MBB.addSuccessor(ContinueMBB);
108609467b48Spatrick   MBB.addSuccessor(RoundMBB);
108709467b48Spatrick   RoundMBB->addSuccessor(LoopMBB);
108809467b48Spatrick   LoopMBB->addSuccessor(ContinueMBB);
108909467b48Spatrick   LoopMBB->addSuccessor(LoopMBB);
109009467b48Spatrick 
109109467b48Spatrick   // Mark all the instructions added to the prolog as frame setup.
109209467b48Spatrick   if (InProlog) {
109309467b48Spatrick     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
109409467b48Spatrick       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
109509467b48Spatrick     }
109609467b48Spatrick     for (MachineInstr &MI : *RoundMBB) {
109709467b48Spatrick       MI.setFlag(MachineInstr::FrameSetup);
109809467b48Spatrick     }
109909467b48Spatrick     for (MachineInstr &MI : *LoopMBB) {
110009467b48Spatrick       MI.setFlag(MachineInstr::FrameSetup);
110109467b48Spatrick     }
1102*a96b3639Srobert     for (MachineInstr &MI :
1103*a96b3639Srobert          llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1104*a96b3639Srobert       MI.setFlag(MachineInstr::FrameSetup);
110509467b48Spatrick     }
110609467b48Spatrick   }
110709467b48Spatrick }
110809467b48Spatrick 
emitStackProbeCall(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool InProlog,std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const1109*a96b3639Srobert void X86FrameLowering::emitStackProbeCall(
1110*a96b3639Srobert     MachineFunction &MF, MachineBasicBlock &MBB,
1111*a96b3639Srobert     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1112*a96b3639Srobert     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
111309467b48Spatrick   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
111409467b48Spatrick 
11157299aa8dSpatrick   // FIXME: Add indirect thunk support and remove this.
11167299aa8dSpatrick   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
111709467b48Spatrick     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
11187299aa8dSpatrick                        "code model and indirect thunks not yet implemented.");
111909467b48Spatrick 
1120*a96b3639Srobert   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1121*a96b3639Srobert              MachineBasicBlock::LQR_Live &&
1122*a96b3639Srobert          "Stack probe calls will clobber live EFLAGS.");
1123*a96b3639Srobert 
112409467b48Spatrick   unsigned CallOp;
112509467b48Spatrick   if (Is64Bit)
112609467b48Spatrick     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
112709467b48Spatrick   else
112809467b48Spatrick     CallOp = X86::CALLpcrel32;
112909467b48Spatrick 
113009467b48Spatrick   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
113109467b48Spatrick 
113209467b48Spatrick   MachineInstrBuilder CI;
113309467b48Spatrick   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
113409467b48Spatrick 
113509467b48Spatrick   // All current stack probes take AX and SP as input, clobber flags, and
113609467b48Spatrick   // preserve all registers. x86_64 probes leave RSP unmodified.
113709467b48Spatrick   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
113809467b48Spatrick     // For the large code model, we have to call through a register. Use R11,
113909467b48Spatrick     // as it is scratch in all supported calling conventions.
114009467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
114109467b48Spatrick         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
114209467b48Spatrick     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
114309467b48Spatrick   } else {
114409467b48Spatrick     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
114509467b48Spatrick         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
114609467b48Spatrick   }
114709467b48Spatrick 
114809467b48Spatrick   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
114909467b48Spatrick   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
115009467b48Spatrick   CI.addReg(AX, RegState::Implicit)
115109467b48Spatrick       .addReg(SP, RegState::Implicit)
115209467b48Spatrick       .addReg(AX, RegState::Define | RegState::Implicit)
115309467b48Spatrick       .addReg(SP, RegState::Define | RegState::Implicit)
115409467b48Spatrick       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
115509467b48Spatrick 
1156*a96b3639Srobert   MachineInstr *ModInst = CI;
115709467b48Spatrick   if (STI.isTargetWin64() || !STI.isOSWindows()) {
115809467b48Spatrick     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
115909467b48Spatrick     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
116009467b48Spatrick     // themselves. They also does not clobber %rax so we can reuse it when
116109467b48Spatrick     // adjusting %rsp.
116209467b48Spatrick     // All other platforms do not specify a particular ABI for the stack probe
116309467b48Spatrick     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
1164*a96b3639Srobert     ModInst =
116509467b48Spatrick         BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
116609467b48Spatrick             .addReg(SP)
116709467b48Spatrick             .addReg(AX);
116809467b48Spatrick   }
116909467b48Spatrick 
1170*a96b3639Srobert   // DebugInfo variable locations -- if there's an instruction number for the
1171*a96b3639Srobert   // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
1172*a96b3639Srobert   // modifies SP.
1173*a96b3639Srobert   if (InstrNum) {
1174*a96b3639Srobert     if (STI.isTargetWin64() || !STI.isOSWindows()) {
1175*a96b3639Srobert       // Label destination operand of the subtract.
1176*a96b3639Srobert       MF.makeDebugValueSubstitution(*InstrNum,
1177*a96b3639Srobert                                     {ModInst->getDebugInstrNum(), 0});
1178*a96b3639Srobert     } else {
1179*a96b3639Srobert       // Label the call. The operand number is the penultimate operand, zero
1180*a96b3639Srobert       // based.
1181*a96b3639Srobert       unsigned SPDefOperand = ModInst->getNumOperands() - 2;
1182*a96b3639Srobert       MF.makeDebugValueSubstitution(
1183*a96b3639Srobert           *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
1184*a96b3639Srobert     }
1185*a96b3639Srobert   }
1186*a96b3639Srobert 
118709467b48Spatrick   if (InProlog) {
118809467b48Spatrick     // Apply the frame setup flag to all inserted instrs.
118909467b48Spatrick     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
119009467b48Spatrick       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
119109467b48Spatrick   }
119209467b48Spatrick }
119309467b48Spatrick 
calculateSetFPREG(uint64_t SPAdjust)119409467b48Spatrick static unsigned calculateSetFPREG(uint64_t SPAdjust) {
119509467b48Spatrick   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
119609467b48Spatrick   // and might require smaller successive adjustments.
119709467b48Spatrick   const uint64_t Win64MaxSEHOffset = 128;
119809467b48Spatrick   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
119909467b48Spatrick   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
120009467b48Spatrick   return SEHFrameOffset & -16;
120109467b48Spatrick }
120209467b48Spatrick 
120309467b48Spatrick // If we're forcing a stack realignment we can't rely on just the frame
120409467b48Spatrick // info, we need to know the ABI stack alignment as well in case we
120509467b48Spatrick // have a call out.  Otherwise just make sure we have some alignment - we'll
120609467b48Spatrick // go with the minimum SlotSize.
calculateMaxStackAlign(const MachineFunction & MF) const120709467b48Spatrick uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
120809467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
1209097a140dSpatrick   Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
1210097a140dSpatrick   Align StackAlign = getStackAlign();
121109467b48Spatrick   if (MF.getFunction().hasFnAttribute("stackrealign")) {
121209467b48Spatrick     if (MFI.hasCalls())
121309467b48Spatrick       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
121409467b48Spatrick     else if (MaxAlign < SlotSize)
1215097a140dSpatrick       MaxAlign = Align(SlotSize);
121609467b48Spatrick   }
1217097a140dSpatrick   return MaxAlign.value();
121809467b48Spatrick }
121909467b48Spatrick 
BuildStackAlignAND(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,unsigned Reg,uint64_t MaxAlign) const122009467b48Spatrick void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
122109467b48Spatrick                                           MachineBasicBlock::iterator MBBI,
122209467b48Spatrick                                           const DebugLoc &DL, unsigned Reg,
122309467b48Spatrick                                           uint64_t MaxAlign) const {
122409467b48Spatrick   uint64_t Val = -MaxAlign;
122509467b48Spatrick   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1226097a140dSpatrick 
1227097a140dSpatrick   MachineFunction &MF = *MBB.getParent();
1228097a140dSpatrick   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1229097a140dSpatrick   const X86TargetLowering &TLI = *STI.getTargetLowering();
1230097a140dSpatrick   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1231097a140dSpatrick   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1232097a140dSpatrick 
1233097a140dSpatrick   // We want to make sure that (in worst case) less than StackProbeSize bytes
1234097a140dSpatrick   // are not probed after the AND. This assumption is used in
1235097a140dSpatrick   // emitStackProbeInlineGeneric.
1236097a140dSpatrick   if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1237097a140dSpatrick     {
1238097a140dSpatrick       NumFrameLoopProbe++;
1239097a140dSpatrick       MachineBasicBlock *entryMBB =
1240097a140dSpatrick           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1241097a140dSpatrick       MachineBasicBlock *headMBB =
1242097a140dSpatrick           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1243097a140dSpatrick       MachineBasicBlock *bodyMBB =
1244097a140dSpatrick           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1245097a140dSpatrick       MachineBasicBlock *footMBB =
1246097a140dSpatrick           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1247097a140dSpatrick 
1248097a140dSpatrick       MachineFunction::iterator MBBIter = MBB.getIterator();
1249097a140dSpatrick       MF.insert(MBBIter, entryMBB);
1250097a140dSpatrick       MF.insert(MBBIter, headMBB);
1251097a140dSpatrick       MF.insert(MBBIter, bodyMBB);
1252097a140dSpatrick       MF.insert(MBBIter, footMBB);
1253097a140dSpatrick       const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
1254a0747c9fSpatrick       Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
1255a0747c9fSpatrick                                   : Is64Bit         ? X86::R11D
1256a0747c9fSpatrick                                                     : X86::EAX;
1257097a140dSpatrick 
1258097a140dSpatrick       // Setup entry block
1259097a140dSpatrick       {
1260097a140dSpatrick 
1261097a140dSpatrick         entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1262097a140dSpatrick         BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1263097a140dSpatrick             .addReg(StackPtr)
1264097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1265097a140dSpatrick         MachineInstr *MI =
1266097a140dSpatrick             BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1267097a140dSpatrick                 .addReg(FinalStackProbed)
1268097a140dSpatrick                 .addImm(Val)
1269097a140dSpatrick                 .setMIFlag(MachineInstr::FrameSetup);
1270097a140dSpatrick 
1271097a140dSpatrick         // The EFLAGS implicit def is dead.
1272097a140dSpatrick         MI->getOperand(3).setIsDead();
1273097a140dSpatrick 
1274097a140dSpatrick         BuildMI(entryMBB, DL,
1275097a140dSpatrick                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1276097a140dSpatrick             .addReg(FinalStackProbed)
1277097a140dSpatrick             .addReg(StackPtr)
1278097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1279097a140dSpatrick         BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1280097a140dSpatrick             .addMBB(&MBB)
1281097a140dSpatrick             .addImm(X86::COND_E)
1282097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1283097a140dSpatrick         entryMBB->addSuccessor(headMBB);
1284097a140dSpatrick         entryMBB->addSuccessor(&MBB);
1285097a140dSpatrick       }
1286097a140dSpatrick 
1287097a140dSpatrick       // Loop entry block
1288097a140dSpatrick 
1289097a140dSpatrick       {
1290097a140dSpatrick         const unsigned SUBOpc =
1291097a140dSpatrick             getSUBriOpcode(Uses64BitFramePtr, StackProbeSize);
1292097a140dSpatrick         BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1293097a140dSpatrick             .addReg(StackPtr)
1294097a140dSpatrick             .addImm(StackProbeSize)
1295097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1296097a140dSpatrick 
1297097a140dSpatrick         BuildMI(headMBB, DL,
1298097a140dSpatrick                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1299097a140dSpatrick             .addReg(StackPtr)
1300*a96b3639Srobert             .addReg(FinalStackProbed)
1301097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1302097a140dSpatrick 
1303*a96b3639Srobert         // jump to the footer if StackPtr < FinalStackProbed
1304097a140dSpatrick         BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1305097a140dSpatrick             .addMBB(footMBB)
1306097a140dSpatrick             .addImm(X86::COND_B)
1307097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1308097a140dSpatrick 
1309097a140dSpatrick         headMBB->addSuccessor(bodyMBB);
1310097a140dSpatrick         headMBB->addSuccessor(footMBB);
1311097a140dSpatrick       }
1312097a140dSpatrick 
1313097a140dSpatrick       // setup loop body
1314097a140dSpatrick       {
1315097a140dSpatrick         addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1316097a140dSpatrick                          .setMIFlag(MachineInstr::FrameSetup),
1317097a140dSpatrick                      StackPtr, false, 0)
1318097a140dSpatrick             .addImm(0)
1319097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1320097a140dSpatrick 
1321097a140dSpatrick         const unsigned SUBOpc =
1322097a140dSpatrick             getSUBriOpcode(Uses64BitFramePtr, StackProbeSize);
1323097a140dSpatrick         BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1324097a140dSpatrick             .addReg(StackPtr)
1325097a140dSpatrick             .addImm(StackProbeSize)
1326097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1327097a140dSpatrick 
1328097a140dSpatrick         // cmp with stack pointer bound
1329097a140dSpatrick         BuildMI(bodyMBB, DL,
1330097a140dSpatrick                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1331097a140dSpatrick             .addReg(FinalStackProbed)
1332097a140dSpatrick             .addReg(StackPtr)
1333097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1334097a140dSpatrick 
1335*a96b3639Srobert         // jump back while FinalStackProbed < StackPtr
1336097a140dSpatrick         BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1337097a140dSpatrick             .addMBB(bodyMBB)
1338097a140dSpatrick             .addImm(X86::COND_B)
1339097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1340097a140dSpatrick         bodyMBB->addSuccessor(bodyMBB);
1341097a140dSpatrick         bodyMBB->addSuccessor(footMBB);
1342097a140dSpatrick       }
1343097a140dSpatrick 
1344097a140dSpatrick       // setup loop footer
1345097a140dSpatrick       {
1346097a140dSpatrick         BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1347097a140dSpatrick             .addReg(FinalStackProbed)
1348097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1349097a140dSpatrick         addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1350097a140dSpatrick                          .setMIFlag(MachineInstr::FrameSetup),
1351097a140dSpatrick                      StackPtr, false, 0)
1352097a140dSpatrick             .addImm(0)
1353097a140dSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1354097a140dSpatrick         footMBB->addSuccessor(&MBB);
1355097a140dSpatrick       }
1356097a140dSpatrick 
1357097a140dSpatrick       recomputeLiveIns(*headMBB);
1358097a140dSpatrick       recomputeLiveIns(*bodyMBB);
1359097a140dSpatrick       recomputeLiveIns(*footMBB);
1360097a140dSpatrick       recomputeLiveIns(MBB);
1361097a140dSpatrick     }
1362097a140dSpatrick   } else {
136309467b48Spatrick     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
136409467b48Spatrick                            .addReg(Reg)
136509467b48Spatrick                            .addImm(Val)
136609467b48Spatrick                            .setMIFlag(MachineInstr::FrameSetup);
136709467b48Spatrick 
136809467b48Spatrick     // The EFLAGS implicit def is dead.
136909467b48Spatrick     MI->getOperand(3).setIsDead();
137009467b48Spatrick   }
137109467b48Spatrick }
137209467b48Spatrick 
1373adae0cfdSpatrick // FIXME: Get this from tablegen.
get64BitArgumentGPRs(CallingConv::ID CallConv,const X86Subtarget & Subtarget)1374adae0cfdSpatrick static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
1375adae0cfdSpatrick                                                 const X86Subtarget &Subtarget) {
1376adae0cfdSpatrick   assert(Subtarget.is64Bit());
1377adae0cfdSpatrick 
1378adae0cfdSpatrick   if (Subtarget.isCallingConvWin64(CallConv)) {
1379adae0cfdSpatrick     static const MCPhysReg GPR64ArgRegsWin64[] = {
1380adae0cfdSpatrick       X86::RCX, X86::RDX, X86::R8,  X86::R9
1381adae0cfdSpatrick     };
1382adae0cfdSpatrick     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
1383adae0cfdSpatrick   }
1384adae0cfdSpatrick 
1385adae0cfdSpatrick   static const MCPhysReg GPR64ArgRegs64Bit[] = {
1386adae0cfdSpatrick     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1387adae0cfdSpatrick   };
1388adae0cfdSpatrick   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
1389adae0cfdSpatrick }
1390adae0cfdSpatrick 
has128ByteRedZone(const MachineFunction & MF) const139109467b48Spatrick bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
139209467b48Spatrick   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
139309467b48Spatrick   // clobbered by any interrupt handler.
139409467b48Spatrick   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
139509467b48Spatrick          "MF used frame lowering for wrong subtarget");
139609467b48Spatrick   const Function &Fn = MF.getFunction();
139709467b48Spatrick   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
139809467b48Spatrick   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
139909467b48Spatrick }
140009467b48Spatrick 
1401*a96b3639Srobert /// Return true if we need to use the restricted Windows x64 prologue and
1402*a96b3639Srobert /// epilogue code patterns that can be described with WinCFI (.seh_*
1403*a96b3639Srobert /// directives).
isWin64Prologue(const MachineFunction & MF) const1404a0747c9fSpatrick bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const {
1405a0747c9fSpatrick   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1406a0747c9fSpatrick }
1407a0747c9fSpatrick 
needsDwarfCFI(const MachineFunction & MF) const1408a0747c9fSpatrick bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1409a0747c9fSpatrick   return !isWin64Prologue(MF) && MF.needsFrameMoves();
1410a0747c9fSpatrick }
141109467b48Spatrick 
141209467b48Spatrick /// emitPrologue - Push callee-saved registers onto the stack, which
141309467b48Spatrick /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
141409467b48Spatrick /// space for local variables. Also emit labels used by the exception handler to
141509467b48Spatrick /// generate the exception handling frames.
141609467b48Spatrick 
141709467b48Spatrick /*
141809467b48Spatrick   Here's a gist of what gets emitted:
141909467b48Spatrick 
142009467b48Spatrick   ; Establish frame pointer, if needed
142109467b48Spatrick   [if needs FP]
142209467b48Spatrick       push  %rbp
142309467b48Spatrick       .cfi_def_cfa_offset 16
142409467b48Spatrick       .cfi_offset %rbp, -16
142509467b48Spatrick       .seh_pushreg %rpb
142609467b48Spatrick       mov  %rsp, %rbp
142709467b48Spatrick       .cfi_def_cfa_register %rbp
142809467b48Spatrick 
142909467b48Spatrick   ; Spill general-purpose registers
143009467b48Spatrick   [for all callee-saved GPRs]
143109467b48Spatrick       pushq %<reg>
143209467b48Spatrick       [if not needs FP]
143309467b48Spatrick          .cfi_def_cfa_offset (offset from RETADDR)
143409467b48Spatrick       .seh_pushreg %<reg>
143509467b48Spatrick 
143609467b48Spatrick   ; If the required stack alignment > default stack alignment
143709467b48Spatrick   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
143809467b48Spatrick   ; of unknown size in the stack frame.
143909467b48Spatrick   [if stack needs re-alignment]
144009467b48Spatrick       and  $MASK, %rsp
144109467b48Spatrick 
144209467b48Spatrick   ; Allocate space for locals
144309467b48Spatrick   [if target is Windows and allocated space > 4096 bytes]
144409467b48Spatrick       ; Windows needs special care for allocations larger
144509467b48Spatrick       ; than one page.
144609467b48Spatrick       mov $NNN, %rax
144709467b48Spatrick       call ___chkstk_ms/___chkstk
144809467b48Spatrick       sub  %rax, %rsp
144909467b48Spatrick   [else]
145009467b48Spatrick       sub  $NNN, %rsp
145109467b48Spatrick 
145209467b48Spatrick   [if needs FP]
145309467b48Spatrick       .seh_stackalloc (size of XMM spill slots)
145409467b48Spatrick       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
145509467b48Spatrick   [else]
145609467b48Spatrick       .seh_stackalloc NNN
145709467b48Spatrick 
145809467b48Spatrick   ; Spill XMMs
145909467b48Spatrick   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
146009467b48Spatrick   ; they may get spilled on any platform, if the current function
146109467b48Spatrick   ; calls @llvm.eh.unwind.init
146209467b48Spatrick   [if needs FP]
146309467b48Spatrick       [for all callee-saved XMM registers]
146409467b48Spatrick           movaps  %<xmm reg>, -MMM(%rbp)
146509467b48Spatrick       [for all callee-saved XMM registers]
146609467b48Spatrick           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
146709467b48Spatrick               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
146809467b48Spatrick   [else]
146909467b48Spatrick       [for all callee-saved XMM registers]
147009467b48Spatrick           movaps  %<xmm reg>, KKK(%rsp)
147109467b48Spatrick       [for all callee-saved XMM registers]
147209467b48Spatrick           .seh_savexmm %<xmm reg>, KKK
147309467b48Spatrick 
147409467b48Spatrick   .seh_endprologue
147509467b48Spatrick 
147609467b48Spatrick   [if needs base pointer]
147709467b48Spatrick       mov  %rsp, %rbx
147809467b48Spatrick       [if needs to restore base pointer]
147909467b48Spatrick           mov %rsp, -MMM(%rbp)
148009467b48Spatrick 
148109467b48Spatrick   ; Emit CFI info
148209467b48Spatrick   [if needs FP]
148309467b48Spatrick       [for all callee-saved registers]
148409467b48Spatrick           .cfi_offset %<reg>, (offset from %rbp)
148509467b48Spatrick   [else]
148609467b48Spatrick        .cfi_def_cfa_offset (offset from RETADDR)
148709467b48Spatrick       [for all callee-saved registers]
148809467b48Spatrick           .cfi_offset %<reg>, (offset from %rsp)
148909467b48Spatrick 
149009467b48Spatrick   Notes:
149109467b48Spatrick   - .seh directives are emitted only for Windows 64 ABI
149209467b48Spatrick   - .cv_fpo directives are emitted on win32 when emitting CodeView
149309467b48Spatrick   - .cfi directives are emitted for all other ABIs
149409467b48Spatrick   - for 32-bit code, substitute %e?? registers for %r??
149509467b48Spatrick */
149609467b48Spatrick 
emitPrologue(MachineFunction & MF,MachineBasicBlock & MBB) const149709467b48Spatrick void X86FrameLowering::emitPrologue(MachineFunction &MF,
149809467b48Spatrick                                     MachineBasicBlock &MBB) const {
149909467b48Spatrick   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
150009467b48Spatrick          "MF used frame lowering for wrong subtarget");
150109467b48Spatrick   MachineBasicBlock::iterator MBBI = MBB.begin();
150209467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
150309467b48Spatrick   const Function &Fn = MF.getFunction();
150409467b48Spatrick   MachineModuleInfo &MMI = MF.getMMI();
150509467b48Spatrick   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
150609467b48Spatrick   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
150709467b48Spatrick   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
150809467b48Spatrick   bool IsFunclet = MBB.isEHFuncletEntry();
150909467b48Spatrick   EHPersonality Personality = EHPersonality::Unknown;
151009467b48Spatrick   if (Fn.hasPersonalityFn())
151109467b48Spatrick     Personality = classifyEHPersonality(Fn.getPersonalityFn());
151209467b48Spatrick   bool FnHasClrFunclet =
151309467b48Spatrick       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
151409467b48Spatrick   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
151509467b48Spatrick   bool HasFP = hasFP(MF);
1516a0747c9fSpatrick   bool IsWin64Prologue = isWin64Prologue(MF);
151709467b48Spatrick   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
151809467b48Spatrick   // FIXME: Emit FPO data for EH funclets.
151909467b48Spatrick   bool NeedsWinFPO =
152009467b48Spatrick       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
152109467b48Spatrick   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1522a0747c9fSpatrick   bool NeedsDwarfCFI = needsDwarfCFI(MF);
152309467b48Spatrick   Register FramePtr = TRI->getFrameRegister(MF);
152409467b48Spatrick   const Register MachineFramePtr =
152509467b48Spatrick       STI.isTarget64BitILP32()
152609467b48Spatrick           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
152709467b48Spatrick   Register BasePtr = TRI->getBaseRegister();
152809467b48Spatrick   bool HasWinCFI = false;
152909467b48Spatrick 
153009467b48Spatrick   // Debug location must be unknown since the first debug location is used
153109467b48Spatrick   // to determine the end of the prologue.
153209467b48Spatrick   DebugLoc DL;
153309467b48Spatrick 
1534*a96b3639Srobert   // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1535*a96b3639Srobert   // tail call.
1536*a96b3639Srobert   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1537*a96b3639Srobert   if (TailCallArgReserveSize  && IsWin64Prologue)
153809467b48Spatrick     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
153909467b48Spatrick 
1540097a140dSpatrick   const bool EmitStackProbeCall =
1541097a140dSpatrick       STI.getTargetLowering()->hasStackProbeSymbol(MF);
154209467b48Spatrick   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
154309467b48Spatrick 
1544a0747c9fSpatrick   if (HasFP && X86FI->hasSwiftAsyncContext()) {
1545*a96b3639Srobert     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1546*a96b3639Srobert     case SwiftAsyncFramePointerMode::DeploymentBased:
1547*a96b3639Srobert       if (STI.swiftAsyncContextIsDynamicallySet()) {
1548*a96b3639Srobert         // The special symbol below is absolute and has a *value* suitable to be
1549*a96b3639Srobert         // combined with the frame pointer directly.
1550*a96b3639Srobert         BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1551*a96b3639Srobert             .addUse(MachineFramePtr)
1552*a96b3639Srobert             .addUse(X86::RIP)
1553*a96b3639Srobert             .addImm(1)
1554*a96b3639Srobert             .addUse(X86::NoRegister)
1555*a96b3639Srobert             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1556*a96b3639Srobert                                X86II::MO_GOTPCREL)
1557*a96b3639Srobert             .addUse(X86::NoRegister);
1558*a96b3639Srobert         break;
1559*a96b3639Srobert       }
1560*a96b3639Srobert       [[fallthrough]];
1561*a96b3639Srobert 
1562*a96b3639Srobert     case SwiftAsyncFramePointerMode::Always:
1563*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1564a0747c9fSpatrick           .addUse(MachineFramePtr)
1565a0747c9fSpatrick           .addImm(60)
1566a0747c9fSpatrick           .setMIFlag(MachineInstr::FrameSetup);
1567*a96b3639Srobert       break;
1568*a96b3639Srobert 
1569*a96b3639Srobert     case SwiftAsyncFramePointerMode::Never:
1570*a96b3639Srobert       break;
1571*a96b3639Srobert     }
1572a0747c9fSpatrick   }
1573a0747c9fSpatrick 
157409467b48Spatrick   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
157509467b48Spatrick   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
157609467b48Spatrick   // stack alignment.
157709467b48Spatrick   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
157809467b48Spatrick       Fn.arg_size() == 2) {
157909467b48Spatrick     StackSize += 8;
158009467b48Spatrick     MFI.setStackSize(StackSize);
1581*a96b3639Srobert 
1582*a96b3639Srobert     // Update the stack pointer by pushing a register. This is the instruction
1583*a96b3639Srobert     // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1584*a96b3639Srobert     // Hard-coding the update to a push avoids emitting a second
1585*a96b3639Srobert     // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1586*a96b3639Srobert     // probing isn't needed anyways for an 8-byte update.
1587*a96b3639Srobert     // Pushing a register leaves us in a similar situation to a regular
1588*a96b3639Srobert     // function call where we know that the address at (rsp-8) is writeable.
1589*a96b3639Srobert     // That way we avoid any off-by-ones with stack probing for additional
1590*a96b3639Srobert     // stack pointer updates later on.
1591*a96b3639Srobert     BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1592*a96b3639Srobert         .addReg(X86::RAX, RegState::Undef)
1593*a96b3639Srobert         .setMIFlag(MachineInstr::FrameSetup);
159409467b48Spatrick   }
159509467b48Spatrick 
159609467b48Spatrick   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
159709467b48Spatrick   // function, and use up to 128 bytes of stack space, don't have a frame
159809467b48Spatrick   // pointer, calls, or dynamic alloca then we do not need to adjust the
159909467b48Spatrick   // stack pointer (we fit in the Red Zone). We also check that we don't
160009467b48Spatrick   // push and pop from the stack.
1601a0747c9fSpatrick   if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
160209467b48Spatrick       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
160309467b48Spatrick       !MFI.adjustsStack() &&                   // No calls.
1604097a140dSpatrick       !EmitStackProbeCall &&                   // No stack probes.
160509467b48Spatrick       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
160609467b48Spatrick       !MF.shouldSplitStack()) {                // Regular stack
1607*a96b3639Srobert     uint64_t MinSize =
1608*a96b3639Srobert         X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta();
160909467b48Spatrick     if (HasFP) MinSize += SlotSize;
161009467b48Spatrick     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
161109467b48Spatrick     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
161209467b48Spatrick     MFI.setStackSize(StackSize);
161309467b48Spatrick   }
161409467b48Spatrick 
161509467b48Spatrick   // Insert stack pointer adjustment for later moving of return addr.  Only
161609467b48Spatrick   // applies to tail call optimized functions where the callee argument stack
161709467b48Spatrick   // size is bigger than the callers.
1618*a96b3639Srobert   if (TailCallArgReserveSize != 0) {
1619*a96b3639Srobert     BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
162009467b48Spatrick                          /*InEpilogue=*/false)
162109467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
162209467b48Spatrick   }
162309467b48Spatrick 
162409467b48Spatrick   // Mapping for machine moves:
162509467b48Spatrick   //
162609467b48Spatrick   //   DST: VirtualFP AND
162709467b48Spatrick   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
162809467b48Spatrick   //        ELSE                        => DW_CFA_def_cfa
162909467b48Spatrick   //
163009467b48Spatrick   //   SRC: VirtualFP AND
163109467b48Spatrick   //        DST: Register               => DW_CFA_def_cfa_register
163209467b48Spatrick   //
163309467b48Spatrick   //   ELSE
163409467b48Spatrick   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
163509467b48Spatrick   //        REG < 64                    => DW_CFA_offset + Reg
163609467b48Spatrick   //        ELSE                        => DW_CFA_offset_extended
163709467b48Spatrick 
163809467b48Spatrick   uint64_t NumBytes = 0;
163909467b48Spatrick   int stackGrowth = -SlotSize;
164009467b48Spatrick 
164109467b48Spatrick   // Find the funclet establisher parameter
164209467b48Spatrick   Register Establisher = X86::NoRegister;
164309467b48Spatrick   if (IsClrFunclet)
164409467b48Spatrick     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
164509467b48Spatrick   else if (IsFunclet)
164609467b48Spatrick     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
164709467b48Spatrick 
164809467b48Spatrick   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
164909467b48Spatrick     // Immediately spill establisher into the home slot.
165009467b48Spatrick     // The runtime cares about this.
165109467b48Spatrick     // MOV64mr %rdx, 16(%rsp)
165209467b48Spatrick     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
165309467b48Spatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
165409467b48Spatrick         .addReg(Establisher)
165509467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
165609467b48Spatrick     MBB.addLiveIn(Establisher);
165709467b48Spatrick   }
165809467b48Spatrick 
165909467b48Spatrick   if (HasFP) {
166009467b48Spatrick     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
166109467b48Spatrick 
166209467b48Spatrick     // Calculate required stack adjustment.
166309467b48Spatrick     uint64_t FrameSize = StackSize - SlotSize;
166409467b48Spatrick     // If required, include space for extra hidden slot for stashing base pointer.
166509467b48Spatrick     if (X86FI->getRestoreBasePointer())
166609467b48Spatrick       FrameSize += SlotSize;
166709467b48Spatrick 
1668*a96b3639Srobert     NumBytes = FrameSize -
1669*a96b3639Srobert                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
167009467b48Spatrick 
167109467b48Spatrick     // Callee-saved registers are pushed on stack before the stack is realigned.
1672a0747c9fSpatrick     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
167309467b48Spatrick       NumBytes = alignTo(NumBytes, MaxAlign);
167409467b48Spatrick 
167509467b48Spatrick     // Save EBP/RBP into the appropriate stack slot.
167609467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
167709467b48Spatrick       .addReg(MachineFramePtr, RegState::Kill)
167809467b48Spatrick       .setMIFlag(MachineInstr::FrameSetup);
167909467b48Spatrick 
168009467b48Spatrick     if (NeedsDwarfCFI) {
168109467b48Spatrick       // Mark the place where EBP/RBP was saved.
168209467b48Spatrick       // Define the current CFA rule to use the provided offset.
168309467b48Spatrick       assert(StackSize);
168409467b48Spatrick       BuildCFI(MBB, MBBI, DL,
1685*a96b3639Srobert                MCCFIInstruction::cfiDefCfaOffset(nullptr, -2 * stackGrowth),
1686*a96b3639Srobert                MachineInstr::FrameSetup);
168709467b48Spatrick 
168809467b48Spatrick       // Change the rule for the FramePtr to be an "offset" rule.
168909467b48Spatrick       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1690*a96b3639Srobert       BuildCFI(MBB, MBBI, DL,
1691*a96b3639Srobert                MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
1692*a96b3639Srobert                                               2 * stackGrowth),
1693*a96b3639Srobert                MachineInstr::FrameSetup);
169409467b48Spatrick     }
169509467b48Spatrick 
169609467b48Spatrick     if (NeedsWinCFI) {
169709467b48Spatrick       HasWinCFI = true;
169809467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
169909467b48Spatrick           .addImm(FramePtr)
170009467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
170109467b48Spatrick     }
170209467b48Spatrick 
1703a0747c9fSpatrick     if (!IsFunclet) {
1704a0747c9fSpatrick       if (X86FI->hasSwiftAsyncContext()) {
1705a0747c9fSpatrick         const auto &Attrs = MF.getFunction().getAttributes();
1706a0747c9fSpatrick 
1707a0747c9fSpatrick         // Before we update the live frame pointer we have to ensure there's a
1708a0747c9fSpatrick         // valid (or null) asynchronous context in its slot just before FP in
1709a0747c9fSpatrick         // the frame record, so store it now.
1710a0747c9fSpatrick         if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
1711a0747c9fSpatrick           // We have an initial context in r14, store it just before the frame
1712a0747c9fSpatrick           // pointer.
1713a0747c9fSpatrick           MBB.addLiveIn(X86::R14);
1714a0747c9fSpatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1715a0747c9fSpatrick               .addReg(X86::R14)
1716a0747c9fSpatrick               .setMIFlag(MachineInstr::FrameSetup);
1717a0747c9fSpatrick         } else {
1718a0747c9fSpatrick           // No initial context, store null so that there's no pointer that
1719a0747c9fSpatrick           // could be misused.
1720a0747c9fSpatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i8))
1721a0747c9fSpatrick               .addImm(0)
1722a0747c9fSpatrick               .setMIFlag(MachineInstr::FrameSetup);
1723a0747c9fSpatrick         }
1724a0747c9fSpatrick 
1725a0747c9fSpatrick         if (NeedsWinCFI) {
1726a0747c9fSpatrick           HasWinCFI = true;
1727a0747c9fSpatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1728a0747c9fSpatrick               .addImm(X86::R14)
1729a0747c9fSpatrick               .setMIFlag(MachineInstr::FrameSetup);
1730a0747c9fSpatrick         }
1731a0747c9fSpatrick 
1732a0747c9fSpatrick         BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
1733a0747c9fSpatrick             .addUse(X86::RSP)
1734a0747c9fSpatrick             .addImm(1)
1735a0747c9fSpatrick             .addUse(X86::NoRegister)
1736a0747c9fSpatrick             .addImm(8)
1737a0747c9fSpatrick             .addUse(X86::NoRegister)
1738a0747c9fSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1739a0747c9fSpatrick         BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri8), X86::RSP)
1740a0747c9fSpatrick             .addUse(X86::RSP)
1741a0747c9fSpatrick             .addImm(8)
1742a0747c9fSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1743a0747c9fSpatrick       }
1744a0747c9fSpatrick 
174509467b48Spatrick       if (!IsWin64Prologue && !IsFunclet) {
174609467b48Spatrick         // Update EBP with the new base value.
1747a0747c9fSpatrick         if (!X86FI->hasSwiftAsyncContext())
174809467b48Spatrick           BuildMI(MBB, MBBI, DL,
174909467b48Spatrick                   TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
175009467b48Spatrick                   FramePtr)
175109467b48Spatrick               .addReg(StackPtr)
175209467b48Spatrick               .setMIFlag(MachineInstr::FrameSetup);
175309467b48Spatrick 
1754adae0cfdSpatrick       if (SaveArgs && !Fn.arg_empty()) {
1755adae0cfdSpatrick         ArrayRef<MCPhysReg> GPRs =
1756adae0cfdSpatrick           get64BitArgumentGPRs(Fn.getCallingConv(), STI);
1757adae0cfdSpatrick         unsigned arg_size = Fn.arg_size();
1758adae0cfdSpatrick         unsigned RI = 0;
1759adae0cfdSpatrick         int64_t SaveSize = 0;
1760adae0cfdSpatrick 
1761adae0cfdSpatrick         if (Fn.hasStructRetAttr()) {
1762adae0cfdSpatrick           GPRs = GPRs.drop_front(1);
1763adae0cfdSpatrick           arg_size--;
1764adae0cfdSpatrick         }
1765adae0cfdSpatrick 
1766adae0cfdSpatrick         for (MCPhysReg Reg : GPRs) {
1767adae0cfdSpatrick           if (++RI > arg_size)
1768adae0cfdSpatrick             break;
1769adae0cfdSpatrick 
1770adae0cfdSpatrick           SaveSize += SlotSize;
1771adae0cfdSpatrick 
1772adae0cfdSpatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1773adae0cfdSpatrick             .addReg(Reg)
1774adae0cfdSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1775adae0cfdSpatrick         }
1776adae0cfdSpatrick 
1777adae0cfdSpatrick         // Realign the stack. PUSHes are the most space efficient.
1778adae0cfdSpatrick         while (SaveSize % getStackAlignment()) {
1779adae0cfdSpatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1780adae0cfdSpatrick             .addReg(GPRs.front())
1781adae0cfdSpatrick             .setMIFlag(MachineInstr::FrameSetup);
1782adae0cfdSpatrick 
1783adae0cfdSpatrick           SaveSize += SlotSize;
1784adae0cfdSpatrick         }
1785adae0cfdSpatrick 
1786adae0cfdSpatrick         //dlg StackSize -= SaveSize;
1787adae0cfdSpatrick         //dlg MFI.setStackSize(StackSize);
1788adae0cfdSpatrick         X86FI->setSaveArgSize(SaveSize);
1789adae0cfdSpatrick       }
1790adae0cfdSpatrick 
1791a0747c9fSpatrick         if (NeedsDwarfCFI) {
1792a0747c9fSpatrick           // Mark effective beginning of when frame pointer becomes valid.
1793a0747c9fSpatrick           // Define the current CFA to use the EBP/RBP register.
1794a0747c9fSpatrick           unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1795a0747c9fSpatrick           BuildCFI(
1796a0747c9fSpatrick               MBB, MBBI, DL,
1797*a96b3639Srobert               MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
1798*a96b3639Srobert               MachineInstr::FrameSetup);
1799a0747c9fSpatrick         }
1800a0747c9fSpatrick 
180109467b48Spatrick         if (NeedsWinFPO) {
180209467b48Spatrick           // .cv_fpo_setframe $FramePtr
180309467b48Spatrick           HasWinCFI = true;
180409467b48Spatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
180509467b48Spatrick               .addImm(FramePtr)
180609467b48Spatrick               .addImm(0)
180709467b48Spatrick               .setMIFlag(MachineInstr::FrameSetup);
180809467b48Spatrick         }
180909467b48Spatrick       }
1810a0747c9fSpatrick     }
181109467b48Spatrick   } else {
181209467b48Spatrick     assert(!IsFunclet && "funclets without FPs not yet implemented");
1813*a96b3639Srobert     NumBytes = StackSize -
1814*a96b3639Srobert                (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
181509467b48Spatrick   }
181609467b48Spatrick 
181709467b48Spatrick   // Update the offset adjustment, which is mainly used by codeview to translate
181809467b48Spatrick   // from ESP to VFRAME relative local variable offsets.
181909467b48Spatrick   if (!IsFunclet) {
1820a0747c9fSpatrick     if (HasFP && TRI->hasStackRealignment(MF))
182109467b48Spatrick       MFI.setOffsetAdjustment(-NumBytes);
182209467b48Spatrick     else
182309467b48Spatrick       MFI.setOffsetAdjustment(-StackSize);
182409467b48Spatrick   }
182509467b48Spatrick 
182609467b48Spatrick   // For EH funclets, only allocate enough space for outgoing calls. Save the
182709467b48Spatrick   // NumBytes value that we would've used for the parent frame.
182809467b48Spatrick   unsigned ParentFrameNumBytes = NumBytes;
182909467b48Spatrick   if (IsFunclet)
183009467b48Spatrick     NumBytes = getWinEHFuncletFrameSize(MF);
183109467b48Spatrick 
183209467b48Spatrick   // Skip the callee-saved push instructions.
183309467b48Spatrick   bool PushedRegs = false;
183409467b48Spatrick   int StackOffset = 2 * stackGrowth;
183509467b48Spatrick 
183609467b48Spatrick   while (MBBI != MBB.end() &&
183709467b48Spatrick          MBBI->getFlag(MachineInstr::FrameSetup) &&
183809467b48Spatrick          (MBBI->getOpcode() == X86::PUSH32r ||
183909467b48Spatrick           MBBI->getOpcode() == X86::PUSH64r)) {
184009467b48Spatrick     PushedRegs = true;
184109467b48Spatrick     Register Reg = MBBI->getOperand(0).getReg();
184209467b48Spatrick     ++MBBI;
184309467b48Spatrick 
184409467b48Spatrick     if (!HasFP && NeedsDwarfCFI) {
184509467b48Spatrick       // Mark callee-saved push instruction.
184609467b48Spatrick       // Define the current CFA rule to use the provided offset.
184709467b48Spatrick       assert(StackSize);
184809467b48Spatrick       BuildCFI(MBB, MBBI, DL,
1849*a96b3639Srobert                MCCFIInstruction::cfiDefCfaOffset(nullptr, -StackOffset),
1850*a96b3639Srobert                MachineInstr::FrameSetup);
185109467b48Spatrick       StackOffset += stackGrowth;
185209467b48Spatrick     }
185309467b48Spatrick 
185409467b48Spatrick     if (NeedsWinCFI) {
185509467b48Spatrick       HasWinCFI = true;
185609467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
185709467b48Spatrick           .addImm(Reg)
185809467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
185909467b48Spatrick     }
186009467b48Spatrick   }
186109467b48Spatrick 
186209467b48Spatrick   // Realign stack after we pushed callee-saved registers (so that we'll be
186309467b48Spatrick   // able to calculate their offsets from the frame pointer).
186409467b48Spatrick   // Don't do this for Win64, it needs to realign the stack after the prologue.
1865a0747c9fSpatrick   if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF)) {
186609467b48Spatrick     assert(HasFP && "There should be a frame pointer if stack is realigned.");
186709467b48Spatrick     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
186809467b48Spatrick 
186909467b48Spatrick     if (NeedsWinCFI) {
187009467b48Spatrick       HasWinCFI = true;
187109467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
187209467b48Spatrick           .addImm(MaxAlign)
187309467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
187409467b48Spatrick     }
187509467b48Spatrick   }
187609467b48Spatrick 
187709467b48Spatrick   // If there is an SUB32ri of ESP immediately before this instruction, merge
187809467b48Spatrick   // the two. This can be the case when tail call elimination is enabled and
187909467b48Spatrick   // the callee has more arguments then the caller.
188009467b48Spatrick   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
188109467b48Spatrick 
188209467b48Spatrick   // Adjust stack pointer: ESP -= numbytes.
188309467b48Spatrick 
188409467b48Spatrick   // Windows and cygwin/mingw require a prologue helper routine when allocating
188509467b48Spatrick   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
188609467b48Spatrick   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
188709467b48Spatrick   // stack and adjust the stack pointer in one go.  The 64-bit version of
188809467b48Spatrick   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
188909467b48Spatrick   // responsible for adjusting the stack pointer.  Touching the stack at 4K
189009467b48Spatrick   // increments is necessary to ensure that the guard pages used by the OS
189109467b48Spatrick   // virtual memory manager are allocated in correct sequence.
189209467b48Spatrick   uint64_t AlignedNumBytes = NumBytes;
1893a0747c9fSpatrick   if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
189409467b48Spatrick     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
1895097a140dSpatrick   if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
189609467b48Spatrick     assert(!X86FI->getUsesRedZone() &&
189709467b48Spatrick            "The Red Zone is not accounted for in stack probes");
189809467b48Spatrick 
189909467b48Spatrick     // Check whether EAX is livein for this block.
190009467b48Spatrick     bool isEAXAlive = isEAXLiveIn(MBB);
190109467b48Spatrick 
190209467b48Spatrick     if (isEAXAlive) {
190309467b48Spatrick       if (Is64Bit) {
190409467b48Spatrick         // Save RAX
190509467b48Spatrick         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
190609467b48Spatrick           .addReg(X86::RAX, RegState::Kill)
190709467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
190809467b48Spatrick       } else {
190909467b48Spatrick         // Save EAX
191009467b48Spatrick         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
191109467b48Spatrick           .addReg(X86::EAX, RegState::Kill)
191209467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
191309467b48Spatrick       }
191409467b48Spatrick     }
191509467b48Spatrick 
191609467b48Spatrick     if (Is64Bit) {
191709467b48Spatrick       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
191809467b48Spatrick       // Function prologue is responsible for adjusting the stack pointer.
191909467b48Spatrick       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
1920*a96b3639Srobert       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Alloc)), X86::RAX)
192109467b48Spatrick           .addImm(Alloc)
192209467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
192309467b48Spatrick     } else {
192409467b48Spatrick       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
192509467b48Spatrick       // We'll also use 4 already allocated bytes for EAX.
192609467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
192709467b48Spatrick           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
192809467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
192909467b48Spatrick     }
193009467b48Spatrick 
193109467b48Spatrick     // Call __chkstk, __chkstk_ms, or __alloca.
193209467b48Spatrick     emitStackProbe(MF, MBB, MBBI, DL, true);
193309467b48Spatrick 
193409467b48Spatrick     if (isEAXAlive) {
193509467b48Spatrick       // Restore RAX/EAX
193609467b48Spatrick       MachineInstr *MI;
193709467b48Spatrick       if (Is64Bit)
193809467b48Spatrick         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
193909467b48Spatrick                           StackPtr, false, NumBytes - 8);
194009467b48Spatrick       else
194109467b48Spatrick         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
194209467b48Spatrick                           StackPtr, false, NumBytes - 4);
194309467b48Spatrick       MI->setFlag(MachineInstr::FrameSetup);
194409467b48Spatrick       MBB.insert(MBBI, MI);
194509467b48Spatrick     }
194609467b48Spatrick   } else if (NumBytes) {
194709467b48Spatrick     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
194809467b48Spatrick   }
194909467b48Spatrick 
195009467b48Spatrick   if (NeedsWinCFI && NumBytes) {
195109467b48Spatrick     HasWinCFI = true;
195209467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
195309467b48Spatrick         .addImm(NumBytes)
195409467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
195509467b48Spatrick   }
195609467b48Spatrick 
195709467b48Spatrick   int SEHFrameOffset = 0;
195809467b48Spatrick   unsigned SPOrEstablisher;
195909467b48Spatrick   if (IsFunclet) {
196009467b48Spatrick     if (IsClrFunclet) {
196109467b48Spatrick       // The establisher parameter passed to a CLR funclet is actually a pointer
196209467b48Spatrick       // to the (mostly empty) frame of its nearest enclosing funclet; we have
196309467b48Spatrick       // to find the root function establisher frame by loading the PSPSym from
196409467b48Spatrick       // the intermediate frame.
196509467b48Spatrick       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
196609467b48Spatrick       MachinePointerInfo NoInfo;
196709467b48Spatrick       MBB.addLiveIn(Establisher);
196809467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
196909467b48Spatrick                    Establisher, false, PSPSlotOffset)
197009467b48Spatrick           .addMemOperand(MF.getMachineMemOperand(
1971097a140dSpatrick               NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize)));
197209467b48Spatrick       ;
197309467b48Spatrick       // Save the root establisher back into the current funclet's (mostly
197409467b48Spatrick       // empty) frame, in case a sub-funclet or the GC needs it.
197509467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
197609467b48Spatrick                    false, PSPSlotOffset)
197709467b48Spatrick           .addReg(Establisher)
1978097a140dSpatrick           .addMemOperand(MF.getMachineMemOperand(
1979097a140dSpatrick               NoInfo,
1980097a140dSpatrick               MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1981097a140dSpatrick               SlotSize, Align(SlotSize)));
198209467b48Spatrick     }
198309467b48Spatrick     SPOrEstablisher = Establisher;
198409467b48Spatrick   } else {
198509467b48Spatrick     SPOrEstablisher = StackPtr;
198609467b48Spatrick   }
198709467b48Spatrick 
198809467b48Spatrick   if (IsWin64Prologue && HasFP) {
198909467b48Spatrick     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
199009467b48Spatrick     // this calculation on the incoming establisher, which holds the value of
199109467b48Spatrick     // RSP from the parent frame at the end of the prologue.
199209467b48Spatrick     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
199309467b48Spatrick     if (SEHFrameOffset)
199409467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
199509467b48Spatrick                    SPOrEstablisher, false, SEHFrameOffset);
199609467b48Spatrick     else
199709467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
199809467b48Spatrick           .addReg(SPOrEstablisher);
199909467b48Spatrick 
200009467b48Spatrick     // If this is not a funclet, emit the CFI describing our frame pointer.
200109467b48Spatrick     if (NeedsWinCFI && !IsFunclet) {
200209467b48Spatrick       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
200309467b48Spatrick       HasWinCFI = true;
200409467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
200509467b48Spatrick           .addImm(FramePtr)
200609467b48Spatrick           .addImm(SEHFrameOffset)
200709467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
200809467b48Spatrick       if (isAsynchronousEHPersonality(Personality))
200909467b48Spatrick         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
201009467b48Spatrick     }
201109467b48Spatrick   } else if (IsFunclet && STI.is32Bit()) {
201209467b48Spatrick     // Reset EBP / ESI to something good for funclets.
201309467b48Spatrick     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
201409467b48Spatrick     // If we're a catch funclet, we can be returned to via catchret. Save ESP
201509467b48Spatrick     // into the registration node so that the runtime will restore it for us.
201609467b48Spatrick     if (!MBB.isCleanupFuncletEntry()) {
201709467b48Spatrick       assert(Personality == EHPersonality::MSVC_CXX);
2018097a140dSpatrick       Register FrameReg;
201909467b48Spatrick       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
2020a0747c9fSpatrick       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
202109467b48Spatrick       // ESP is the first field, so no extra displacement is needed.
202209467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
202309467b48Spatrick                    false, EHRegOffset)
202409467b48Spatrick           .addReg(X86::ESP);
202509467b48Spatrick     }
202609467b48Spatrick   }
202709467b48Spatrick 
202809467b48Spatrick   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
202909467b48Spatrick     const MachineInstr &FrameInstr = *MBBI;
203009467b48Spatrick     ++MBBI;
203109467b48Spatrick 
203209467b48Spatrick     if (NeedsWinCFI) {
203309467b48Spatrick       int FI;
203409467b48Spatrick       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
203509467b48Spatrick         if (X86::FR64RegClass.contains(Reg)) {
203609467b48Spatrick           int Offset;
2037097a140dSpatrick           Register IgnoredFrameReg;
203809467b48Spatrick           if (IsWin64Prologue && IsFunclet)
203909467b48Spatrick             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
204009467b48Spatrick           else
2041a0747c9fSpatrick             Offset =
2042a0747c9fSpatrick                 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
204309467b48Spatrick                 SEHFrameOffset;
204409467b48Spatrick 
204509467b48Spatrick           HasWinCFI = true;
204609467b48Spatrick           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
204709467b48Spatrick           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
204809467b48Spatrick               .addImm(Reg)
204909467b48Spatrick               .addImm(Offset)
205009467b48Spatrick               .setMIFlag(MachineInstr::FrameSetup);
205109467b48Spatrick         }
205209467b48Spatrick       }
205309467b48Spatrick     }
205409467b48Spatrick   }
205509467b48Spatrick 
205609467b48Spatrick   if (NeedsWinCFI && HasWinCFI)
205709467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
205809467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
205909467b48Spatrick 
206009467b48Spatrick   if (FnHasClrFunclet && !IsFunclet) {
206109467b48Spatrick     // Save the so-called Initial-SP (i.e. the value of the stack pointer
206209467b48Spatrick     // immediately after the prolog)  into the PSPSlot so that funclets
206309467b48Spatrick     // and the GC can recover it.
206409467b48Spatrick     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
206509467b48Spatrick     auto PSPInfo = MachinePointerInfo::getFixedStack(
206609467b48Spatrick         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
206709467b48Spatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
206809467b48Spatrick                  PSPSlotOffset)
206909467b48Spatrick         .addReg(StackPtr)
207009467b48Spatrick         .addMemOperand(MF.getMachineMemOperand(
207109467b48Spatrick             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
2072097a140dSpatrick             SlotSize, Align(SlotSize)));
207309467b48Spatrick   }
207409467b48Spatrick 
207509467b48Spatrick   // Realign stack after we spilled callee-saved registers (so that we'll be
207609467b48Spatrick   // able to calculate their offsets from the frame pointer).
207709467b48Spatrick   // Win64 requires aligning the stack after the prologue.
2078a0747c9fSpatrick   if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
207909467b48Spatrick     assert(HasFP && "There should be a frame pointer if stack is realigned.");
208009467b48Spatrick     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
208109467b48Spatrick   }
208209467b48Spatrick 
208309467b48Spatrick   // We already dealt with stack realignment and funclets above.
208409467b48Spatrick   if (IsFunclet && STI.is32Bit())
208509467b48Spatrick     return;
208609467b48Spatrick 
208709467b48Spatrick   // If we need a base pointer, set it up here. It's whatever the value
208809467b48Spatrick   // of the stack pointer is at this point. Any variable size objects
208909467b48Spatrick   // will be allocated after this, so we can still use the base pointer
209009467b48Spatrick   // to reference locals.
209109467b48Spatrick   if (TRI->hasBasePointer(MF)) {
209209467b48Spatrick     // Update the base pointer with the current stack pointer.
209309467b48Spatrick     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
209409467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
209509467b48Spatrick       .addReg(SPOrEstablisher)
209609467b48Spatrick       .setMIFlag(MachineInstr::FrameSetup);
209709467b48Spatrick     if (X86FI->getRestoreBasePointer()) {
209809467b48Spatrick       // Stash value of base pointer.  Saving RSP instead of EBP shortens
209909467b48Spatrick       // dependence chain. Used by SjLj EH.
210009467b48Spatrick       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
210109467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
210209467b48Spatrick                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
210309467b48Spatrick         .addReg(SPOrEstablisher)
210409467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
210509467b48Spatrick     }
210609467b48Spatrick 
210709467b48Spatrick     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
210809467b48Spatrick       // Stash the value of the frame pointer relative to the base pointer for
210909467b48Spatrick       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
211009467b48Spatrick       // it recovers the frame pointer from the base pointer rather than the
211109467b48Spatrick       // other way around.
211209467b48Spatrick       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2113097a140dSpatrick       Register UsedReg;
211409467b48Spatrick       int Offset =
2115a0747c9fSpatrick           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2116a0747c9fSpatrick               .getFixed();
211709467b48Spatrick       assert(UsedReg == BasePtr);
211809467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
211909467b48Spatrick           .addReg(FramePtr)
212009467b48Spatrick           .setMIFlag(MachineInstr::FrameSetup);
212109467b48Spatrick     }
212209467b48Spatrick   }
212309467b48Spatrick 
212409467b48Spatrick   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
212509467b48Spatrick     // Mark end of stack pointer adjustment.
212609467b48Spatrick     if (!HasFP && NumBytes) {
212709467b48Spatrick       // Define the current CFA rule to use the provided offset.
212809467b48Spatrick       assert(StackSize);
2129097a140dSpatrick       BuildCFI(
2130097a140dSpatrick           MBB, MBBI, DL,
2131*a96b3639Srobert           MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
2132*a96b3639Srobert           MachineInstr::FrameSetup);
213309467b48Spatrick     }
213409467b48Spatrick 
213509467b48Spatrick     // Emit DWARF info specifying the offsets of the callee-saved registers.
2136097a140dSpatrick     emitCalleeSavedFrameMoves(MBB, MBBI, DL, true);
213709467b48Spatrick   }
213809467b48Spatrick 
213909467b48Spatrick   // X86 Interrupt handling function cannot assume anything about the direction
214009467b48Spatrick   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
214109467b48Spatrick   // in each prologue of interrupt handler function.
214209467b48Spatrick   //
214309467b48Spatrick   // FIXME: Create "cld" instruction only in these cases:
214409467b48Spatrick   // 1. The interrupt handling function uses any of the "rep" instructions.
214509467b48Spatrick   // 2. Interrupt handling function calls another function.
214609467b48Spatrick   //
214709467b48Spatrick   if (Fn.getCallingConv() == CallingConv::X86_INTR)
214809467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
214909467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
215009467b48Spatrick 
215109467b48Spatrick   // At this point we know if the function has WinCFI or not.
215209467b48Spatrick   MF.setHasWinCFI(HasWinCFI);
215309467b48Spatrick }
215409467b48Spatrick 
canUseLEAForSPInEpilogue(const MachineFunction & MF) const215509467b48Spatrick bool X86FrameLowering::canUseLEAForSPInEpilogue(
215609467b48Spatrick     const MachineFunction &MF) const {
215709467b48Spatrick   // We can't use LEA instructions for adjusting the stack pointer if we don't
215809467b48Spatrick   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
215909467b48Spatrick   // to deallocate the stack.
216009467b48Spatrick   // This means that we can use LEA for SP in two situations:
216109467b48Spatrick   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
216209467b48Spatrick   // 2. We *have* a frame pointer which means we are permitted to use LEA.
216309467b48Spatrick   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
216409467b48Spatrick }
216509467b48Spatrick 
isFuncletReturnInstr(MachineInstr & MI)216609467b48Spatrick static bool isFuncletReturnInstr(MachineInstr &MI) {
216709467b48Spatrick   switch (MI.getOpcode()) {
216809467b48Spatrick   case X86::CATCHRET:
216909467b48Spatrick   case X86::CLEANUPRET:
217009467b48Spatrick     return true;
217109467b48Spatrick   default:
217209467b48Spatrick     return false;
217309467b48Spatrick   }
217409467b48Spatrick   llvm_unreachable("impossible");
217509467b48Spatrick }
217609467b48Spatrick 
217709467b48Spatrick // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
217809467b48Spatrick // stack. It holds a pointer to the bottom of the root function frame.  The
217909467b48Spatrick // establisher frame pointer passed to a nested funclet may point to the
218009467b48Spatrick // (mostly empty) frame of its parent funclet, but it will need to find
218109467b48Spatrick // the frame of the root function to access locals.  To facilitate this,
218209467b48Spatrick // every funclet copies the pointer to the bottom of the root function
218309467b48Spatrick // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
218409467b48Spatrick // same offset for the PSPSym in the root function frame that's used in the
218509467b48Spatrick // funclets' frames allows each funclet to dynamically accept any ancestor
218609467b48Spatrick // frame as its establisher argument (the runtime doesn't guarantee the
218709467b48Spatrick // immediate parent for some reason lost to history), and also allows the GC,
218809467b48Spatrick // which uses the PSPSym for some bookkeeping, to find it in any funclet's
218909467b48Spatrick // frame with only a single offset reported for the entire method.
219009467b48Spatrick unsigned
getPSPSlotOffsetFromSP(const MachineFunction & MF) const219109467b48Spatrick X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
219209467b48Spatrick   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
2193097a140dSpatrick   Register SPReg;
219409467b48Spatrick   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2195a0747c9fSpatrick                                               /*IgnoreSPUpdates*/ true)
2196a0747c9fSpatrick                    .getFixed();
219709467b48Spatrick   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
219809467b48Spatrick   return static_cast<unsigned>(Offset);
219909467b48Spatrick }
220009467b48Spatrick 
220109467b48Spatrick unsigned
getWinEHFuncletFrameSize(const MachineFunction & MF) const220209467b48Spatrick X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
220309467b48Spatrick   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
220409467b48Spatrick   // This is the size of the pushed CSRs.
220509467b48Spatrick   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
220609467b48Spatrick   // This is the size of callee saved XMMs.
220709467b48Spatrick   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
220809467b48Spatrick   unsigned XMMSize = WinEHXMMSlotInfo.size() *
220909467b48Spatrick                      TRI->getSpillSize(X86::VR128RegClass);
221009467b48Spatrick   // This is the amount of stack a funclet needs to allocate.
221109467b48Spatrick   unsigned UsedSize;
221209467b48Spatrick   EHPersonality Personality =
221309467b48Spatrick       classifyEHPersonality(MF.getFunction().getPersonalityFn());
221409467b48Spatrick   if (Personality == EHPersonality::CoreCLR) {
221509467b48Spatrick     // CLR funclets need to hold enough space to include the PSPSym, at the
221609467b48Spatrick     // same offset from the stack pointer (immediately after the prolog) as it
221709467b48Spatrick     // resides at in the main function.
221809467b48Spatrick     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
221909467b48Spatrick   } else {
222009467b48Spatrick     // Other funclets just need enough stack for outgoing call arguments.
222109467b48Spatrick     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
222209467b48Spatrick   }
222309467b48Spatrick   // RBP is not included in the callee saved register block. After pushing RBP,
222409467b48Spatrick   // everything is 16 byte aligned. Everything we allocate before an outgoing
222509467b48Spatrick   // call must also be 16 byte aligned.
2226097a140dSpatrick   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
222709467b48Spatrick   // Subtract out the size of the callee saved registers. This is how much stack
222809467b48Spatrick   // each funclet will allocate.
222909467b48Spatrick   return FrameSizeMinusRBP + XMMSize - CSSize;
223009467b48Spatrick }
223109467b48Spatrick 
isTailCallOpcode(unsigned Opc)223209467b48Spatrick static bool isTailCallOpcode(unsigned Opc) {
223309467b48Spatrick     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
223409467b48Spatrick         Opc == X86::TCRETURNmi ||
223509467b48Spatrick         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
223609467b48Spatrick         Opc == X86::TCRETURNmi64;
223709467b48Spatrick }
223809467b48Spatrick 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const223909467b48Spatrick void X86FrameLowering::emitEpilogue(MachineFunction &MF,
224009467b48Spatrick                                     MachineBasicBlock &MBB) const {
224109467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
224209467b48Spatrick   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
224309467b48Spatrick   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
224409467b48Spatrick   MachineBasicBlock::iterator MBBI = Terminator;
224509467b48Spatrick   DebugLoc DL;
224609467b48Spatrick   if (MBBI != MBB.end())
224709467b48Spatrick     DL = MBBI->getDebugLoc();
224809467b48Spatrick   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
224909467b48Spatrick   const bool Is64BitILP32 = STI.isTarget64BitILP32();
225009467b48Spatrick   Register FramePtr = TRI->getFrameRegister(MF);
2251a0747c9fSpatrick   Register MachineFramePtr =
225209467b48Spatrick       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
225309467b48Spatrick 
225409467b48Spatrick   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
225509467b48Spatrick   bool NeedsWin64CFI =
225609467b48Spatrick       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
225709467b48Spatrick   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
225809467b48Spatrick 
225909467b48Spatrick   // Get the number of bytes to allocate from the FrameInfo.
226009467b48Spatrick   uint64_t StackSize = MFI.getStackSize();
226109467b48Spatrick   uint64_t MaxAlign = calculateMaxStackAlign(MF);
226209467b48Spatrick   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2263*a96b3639Srobert   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
226409467b48Spatrick   bool HasFP = hasFP(MF);
226509467b48Spatrick   uint64_t NumBytes = 0;
226609467b48Spatrick 
226709467b48Spatrick   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
226809467b48Spatrick                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
226909467b48Spatrick                        MF.needsFrameMoves();
227009467b48Spatrick 
227109467b48Spatrick   if (IsFunclet) {
227209467b48Spatrick     assert(HasFP && "EH funclets without FP not yet implemented");
227309467b48Spatrick     NumBytes = getWinEHFuncletFrameSize(MF);
227409467b48Spatrick   } else if (HasFP) {
227509467b48Spatrick     // Calculate required stack adjustment.
227609467b48Spatrick     uint64_t FrameSize = StackSize - SlotSize;
2277*a96b3639Srobert     NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
227809467b48Spatrick 
227909467b48Spatrick     // Callee-saved registers were pushed on stack before the stack was
228009467b48Spatrick     // realigned.
2281a0747c9fSpatrick     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
228209467b48Spatrick       NumBytes = alignTo(FrameSize, MaxAlign);
228309467b48Spatrick   } else {
2284*a96b3639Srobert     NumBytes = StackSize - CSSize - TailCallArgReserveSize;
228509467b48Spatrick   }
228609467b48Spatrick   uint64_t SEHStackAllocAmt = NumBytes;
228709467b48Spatrick 
2288097a140dSpatrick   // AfterPop is the position to insert .cfi_restore.
2289097a140dSpatrick   MachineBasicBlock::iterator AfterPop = MBBI;
2290097a140dSpatrick   if (HasFP) {
2291a0747c9fSpatrick     if (X86FI->hasSwiftAsyncContext()) {
2292a0747c9fSpatrick       // Discard the context.
2293a0747c9fSpatrick       int Offset = 16 + mergeSPUpdates(MBB, MBBI, true);
2294a0747c9fSpatrick       emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/true);
2295a0747c9fSpatrick     }
2296a0747c9fSpatrick 
2297adae0cfdSpatrick     if (X86FI->getSaveArgSize()) {
2298adae0cfdSpatrick       // LEAVE is effectively mov rbp,rsp; pop rbp
2299adae0cfdSpatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::LEAVE64))
2300adae0cfdSpatrick         .setMIFlag(MachineInstr::FrameDestroy);
2301adae0cfdSpatrick     } else {
2302097a140dSpatrick       // Pop EBP.
2303097a140dSpatrick       BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
2304097a140dSpatrick             MachineFramePtr)
2305097a140dSpatrick         .setMIFlag(MachineInstr::FrameDestroy);
2306adae0cfdSpatrick     }
2307a0747c9fSpatrick 
2308a0747c9fSpatrick     // We need to reset FP to its untagged state on return. Bit 60 is currently
2309a0747c9fSpatrick     // used to show the presence of an extended frame.
2310a0747c9fSpatrick     if (X86FI->hasSwiftAsyncContext()) {
2311a0747c9fSpatrick       BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8),
2312a0747c9fSpatrick               MachineFramePtr)
2313a0747c9fSpatrick           .addUse(MachineFramePtr)
2314a0747c9fSpatrick           .addImm(60)
2315a0747c9fSpatrick           .setMIFlag(MachineInstr::FrameDestroy);
2316a0747c9fSpatrick     }
2317a0747c9fSpatrick 
2318097a140dSpatrick     if (NeedsDwarfCFI) {
2319097a140dSpatrick       unsigned DwarfStackPtr =
2320097a140dSpatrick           TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
2321097a140dSpatrick       BuildCFI(MBB, MBBI, DL,
2322*a96b3639Srobert                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
2323*a96b3639Srobert                MachineInstr::FrameDestroy);
2324097a140dSpatrick       if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
2325097a140dSpatrick         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
2326097a140dSpatrick         BuildCFI(MBB, AfterPop, DL,
2327*a96b3639Srobert                  MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
2328*a96b3639Srobert                  MachineInstr::FrameDestroy);
2329097a140dSpatrick         --MBBI;
2330097a140dSpatrick         --AfterPop;
2331097a140dSpatrick       }
2332097a140dSpatrick       --MBBI;
2333097a140dSpatrick     }
2334097a140dSpatrick   }
2335097a140dSpatrick 
233609467b48Spatrick   MachineBasicBlock::iterator FirstCSPop = MBBI;
233709467b48Spatrick   // Skip the callee-saved pop instructions.
233809467b48Spatrick   while (MBBI != MBB.begin()) {
233909467b48Spatrick     MachineBasicBlock::iterator PI = std::prev(MBBI);
234009467b48Spatrick     unsigned Opc = PI->getOpcode();
234109467b48Spatrick 
234209467b48Spatrick     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
234309467b48Spatrick       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2344adae0cfdSpatrick           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2345a0747c9fSpatrick           (Opc != X86::LEAVE64 || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2346a0747c9fSpatrick           (Opc != X86::BTR64ri8 || !PI->getFlag(MachineInstr::FrameDestroy)) &&
2347a0747c9fSpatrick           (Opc != X86::ADD64ri8 || !PI->getFlag(MachineInstr::FrameDestroy)))
234809467b48Spatrick         break;
234909467b48Spatrick       FirstCSPop = PI;
235009467b48Spatrick     }
235109467b48Spatrick 
235209467b48Spatrick     --MBBI;
235309467b48Spatrick   }
235409467b48Spatrick   MBBI = FirstCSPop;
235509467b48Spatrick 
235609467b48Spatrick   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
235709467b48Spatrick     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
235809467b48Spatrick 
235909467b48Spatrick   if (MBBI != MBB.end())
236009467b48Spatrick     DL = MBBI->getDebugLoc();
236109467b48Spatrick   // If there is an ADD32ri or SUB32ri of ESP immediately before this
236209467b48Spatrick   // instruction, merge the two instructions.
236309467b48Spatrick   if (NumBytes || MFI.hasVarSizedObjects())
236409467b48Spatrick     NumBytes += mergeSPUpdates(MBB, MBBI, true);
236509467b48Spatrick 
236609467b48Spatrick   // If dynamic alloca is used, then reset esp to point to the last callee-saved
236709467b48Spatrick   // slot before popping them off! Same applies for the case, when stack was
236809467b48Spatrick   // realigned. Don't do this if this was a funclet epilogue, since the funclets
236909467b48Spatrick   // will not do realignment or dynamic stack allocation.
2370a0747c9fSpatrick   if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
237109467b48Spatrick       !IsFunclet) {
2372a0747c9fSpatrick     if (TRI->hasStackRealignment(MF))
237309467b48Spatrick       MBBI = FirstCSPop;
237409467b48Spatrick     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
237509467b48Spatrick     uint64_t LEAAmount =
237609467b48Spatrick         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
237709467b48Spatrick 
2378a0747c9fSpatrick     if (X86FI->hasSwiftAsyncContext())
2379a0747c9fSpatrick       LEAAmount -= 16;
2380a0747c9fSpatrick 
238109467b48Spatrick     // There are only two legal forms of epilogue:
238209467b48Spatrick     // - add SEHAllocationSize, %rsp
238309467b48Spatrick     // - lea SEHAllocationSize(%FramePtr), %rsp
238409467b48Spatrick     //
238509467b48Spatrick     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
238609467b48Spatrick     // However, we may use this sequence if we have a frame pointer because the
238709467b48Spatrick     // effects of the prologue can safely be undone.
238809467b48Spatrick     if (LEAAmount != 0) {
238909467b48Spatrick       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
239009467b48Spatrick       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
239109467b48Spatrick                    FramePtr, false, LEAAmount);
239209467b48Spatrick       --MBBI;
239309467b48Spatrick     } else {
239409467b48Spatrick       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
239509467b48Spatrick       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
239609467b48Spatrick         .addReg(FramePtr);
239709467b48Spatrick       --MBBI;
239809467b48Spatrick     }
239909467b48Spatrick   } else if (NumBytes) {
240009467b48Spatrick     // Adjust stack pointer back: ESP += numbytes.
240109467b48Spatrick     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2402*a96b3639Srobert     if (!HasFP && NeedsDwarfCFI) {
240309467b48Spatrick       // Define the current CFA rule to use the provided offset.
2404097a140dSpatrick       BuildCFI(MBB, MBBI, DL,
2405*a96b3639Srobert                MCCFIInstruction::cfiDefCfaOffset(
2406*a96b3639Srobert                    nullptr, CSSize + TailCallArgReserveSize + SlotSize),
2407*a96b3639Srobert                MachineInstr::FrameDestroy);
240809467b48Spatrick     }
240909467b48Spatrick     --MBBI;
241009467b48Spatrick   }
241109467b48Spatrick 
241209467b48Spatrick   // Windows unwinder will not invoke function's exception handler if IP is
241309467b48Spatrick   // either in prologue or in epilogue.  This behavior causes a problem when a
241409467b48Spatrick   // call immediately precedes an epilogue, because the return address points
241509467b48Spatrick   // into the epilogue.  To cope with that, we insert an epilogue marker here,
241609467b48Spatrick   // then replace it with a 'nop' if it ends up immediately after a CALL in the
241709467b48Spatrick   // final emitted code.
241809467b48Spatrick   if (NeedsWin64CFI && MF.hasWinCFI())
241909467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
242009467b48Spatrick 
2421*a96b3639Srobert   if (!HasFP && NeedsDwarfCFI) {
242209467b48Spatrick     MBBI = FirstCSPop;
242309467b48Spatrick     int64_t Offset = -CSSize - SlotSize;
242409467b48Spatrick     // Mark callee-saved pop instruction.
242509467b48Spatrick     // Define the current CFA rule to use the provided offset.
242609467b48Spatrick     while (MBBI != MBB.end()) {
242709467b48Spatrick       MachineBasicBlock::iterator PI = MBBI;
242809467b48Spatrick       unsigned Opc = PI->getOpcode();
242909467b48Spatrick       ++MBBI;
243009467b48Spatrick       if (Opc == X86::POP32r || Opc == X86::POP64r) {
243109467b48Spatrick         Offset += SlotSize;
243209467b48Spatrick         BuildCFI(MBB, MBBI, DL,
2433*a96b3639Srobert                  MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset),
2434*a96b3639Srobert                  MachineInstr::FrameDestroy);
243509467b48Spatrick       }
243609467b48Spatrick     }
243709467b48Spatrick   }
243809467b48Spatrick 
2439097a140dSpatrick   // Emit DWARF info specifying the restores of the callee-saved registers.
2440097a140dSpatrick   // For epilogue with return inside or being other block without successor,
2441097a140dSpatrick   // no need to generate .cfi_restore for callee-saved registers.
2442*a96b3639Srobert   if (NeedsDwarfCFI && !MBB.succ_empty())
2443097a140dSpatrick     emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
2444097a140dSpatrick 
244509467b48Spatrick   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
244609467b48Spatrick     // Add the return addr area delta back since we are not tail calling.
244709467b48Spatrick     int Offset = -1 * X86FI->getTCReturnAddrDelta();
244809467b48Spatrick     assert(Offset >= 0 && "TCDelta should never be positive");
244909467b48Spatrick     if (Offset) {
245009467b48Spatrick       // Check for possible merge with preceding ADD instruction.
245109467b48Spatrick       Offset += mergeSPUpdates(MBB, Terminator, true);
245209467b48Spatrick       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
245309467b48Spatrick     }
245409467b48Spatrick   }
2455a0747c9fSpatrick 
2456a0747c9fSpatrick   // Emit tilerelease for AMX kernel.
2457*a96b3639Srobert   if (X86FI->hasVirtualTileReg())
2458a0747c9fSpatrick     BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
245909467b48Spatrick }
246009467b48Spatrick 
getFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg) const2461a0747c9fSpatrick StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF,
2462a0747c9fSpatrick                                                      int FI,
2463097a140dSpatrick                                                      Register &FrameReg) const {
246409467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
246509467b48Spatrick 
246609467b48Spatrick   bool IsFixed = MFI.isFixedObjectIndex(FI);
246709467b48Spatrick   // We can't calculate offset from frame pointer if the stack is realigned,
246809467b48Spatrick   // so enforce usage of stack/base pointer.  The base pointer is used when we
246909467b48Spatrick   // have dynamic allocas in addition to dynamic realignment.
247009467b48Spatrick   if (TRI->hasBasePointer(MF))
247109467b48Spatrick     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2472a0747c9fSpatrick   else if (TRI->hasStackRealignment(MF))
247309467b48Spatrick     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
247409467b48Spatrick   else
247509467b48Spatrick     FrameReg = TRI->getFrameRegister(MF);
247609467b48Spatrick 
247709467b48Spatrick   // Offset will hold the offset from the stack pointer at function entry to the
247809467b48Spatrick   // object.
247909467b48Spatrick   // We need to factor in additional offsets applied during the prologue to the
248009467b48Spatrick   // frame, base, and stack pointer depending on which is used.
248109467b48Spatrick   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
248209467b48Spatrick   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
248309467b48Spatrick   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
248409467b48Spatrick   uint64_t StackSize = MFI.getStackSize();
248509467b48Spatrick   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
248609467b48Spatrick   int64_t FPDelta = 0;
248709467b48Spatrick 
248809467b48Spatrick   // In an x86 interrupt, remove the offset we added to account for the return
248909467b48Spatrick   // address from any stack object allocated in the caller's frame. Interrupts
249009467b48Spatrick   // do not have a standard return address. Fixed objects in the current frame,
249109467b48Spatrick   // such as SSE register spills, should not get this treatment.
249209467b48Spatrick   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
249309467b48Spatrick       Offset >= 0) {
249409467b48Spatrick     Offset += getOffsetOfLocalArea();
249509467b48Spatrick   }
249609467b48Spatrick 
249709467b48Spatrick   if (IsWin64Prologue) {
249809467b48Spatrick     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
249909467b48Spatrick 
250009467b48Spatrick     // Calculate required stack adjustment.
250109467b48Spatrick     uint64_t FrameSize = StackSize - SlotSize;
250209467b48Spatrick     // If required, include space for extra hidden slot for stashing base pointer.
250309467b48Spatrick     if (X86FI->getRestoreBasePointer())
250409467b48Spatrick       FrameSize += SlotSize;
250509467b48Spatrick     uint64_t NumBytes = FrameSize - CSSize;
250609467b48Spatrick 
250709467b48Spatrick     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
250809467b48Spatrick     if (FI && FI == X86FI->getFAIndex())
2509a0747c9fSpatrick       return StackOffset::getFixed(-SEHFrameOffset);
251009467b48Spatrick 
251109467b48Spatrick     // FPDelta is the offset from the "traditional" FP location of the old base
251209467b48Spatrick     // pointer followed by return address and the location required by the
251309467b48Spatrick     // restricted Win64 prologue.
251409467b48Spatrick     // Add FPDelta to all offsets below that go through the frame pointer.
251509467b48Spatrick     FPDelta = FrameSize - SEHFrameOffset;
251609467b48Spatrick     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
251709467b48Spatrick            "FPDelta isn't aligned per the Win64 ABI!");
251809467b48Spatrick   }
251909467b48Spatrick 
2520adae0cfdSpatrick   if (FI >= 0)
2521adae0cfdSpatrick     Offset -= X86FI->getSaveArgSize();
252209467b48Spatrick 
2523*a96b3639Srobert   if (FrameReg == TRI->getFramePtr()) {
2524*a96b3639Srobert     // Skip saved EBP/RBP
252509467b48Spatrick     Offset += SlotSize;
252609467b48Spatrick 
2527*a96b3639Srobert     // Account for restricted Windows prologue.
2528*a96b3639Srobert     Offset += FPDelta;
2529*a96b3639Srobert 
253009467b48Spatrick     // Skip the RETADDR move area
253109467b48Spatrick     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
253209467b48Spatrick     if (TailCallReturnAddrDelta < 0)
253309467b48Spatrick       Offset -= TailCallReturnAddrDelta;
2534*a96b3639Srobert 
2535*a96b3639Srobert     return StackOffset::getFixed(Offset);
253609467b48Spatrick   }
253709467b48Spatrick 
2538*a96b3639Srobert   // FrameReg is either the stack pointer or a base pointer. But the base is
2539*a96b3639Srobert   // located at the end of the statically known StackSize so the distinction
2540*a96b3639Srobert   // doesn't really matter.
2541*a96b3639Srobert   if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
2542*a96b3639Srobert     assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2543*a96b3639Srobert   return StackOffset::getFixed(Offset + StackSize);
254409467b48Spatrick }
254509467b48Spatrick 
getWin64EHFrameIndexRef(const MachineFunction & MF,int FI,Register & FrameReg) const2546097a140dSpatrick int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI,
2547097a140dSpatrick                                               Register &FrameReg) const {
254809467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
254909467b48Spatrick   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
255009467b48Spatrick   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
255109467b48Spatrick   const auto it = WinEHXMMSlotInfo.find(FI);
255209467b48Spatrick 
255309467b48Spatrick   if (it == WinEHXMMSlotInfo.end())
2554a0747c9fSpatrick     return getFrameIndexReference(MF, FI, FrameReg).getFixed();
255509467b48Spatrick 
255609467b48Spatrick   FrameReg = TRI->getStackRegister();
2557097a140dSpatrick   return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
2558097a140dSpatrick          it->second;
255909467b48Spatrick }
256009467b48Spatrick 
2561a0747c9fSpatrick StackOffset
getFrameIndexReferenceSP(const MachineFunction & MF,int FI,Register & FrameReg,int Adjustment) const2562a0747c9fSpatrick X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI,
2563a0747c9fSpatrick                                            Register &FrameReg,
256409467b48Spatrick                                            int Adjustment) const {
256509467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
256609467b48Spatrick   FrameReg = TRI->getStackRegister();
2567a0747c9fSpatrick   return StackOffset::getFixed(MFI.getObjectOffset(FI) -
2568a0747c9fSpatrick                                getOffsetOfLocalArea() + Adjustment);
256909467b48Spatrick }
257009467b48Spatrick 
2571a0747c9fSpatrick StackOffset
getFrameIndexReferencePreferSP(const MachineFunction & MF,int FI,Register & FrameReg,bool IgnoreSPUpdates) const2572a0747c9fSpatrick X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2573a0747c9fSpatrick                                                  int FI, Register &FrameReg,
257409467b48Spatrick                                                  bool IgnoreSPUpdates) const {
257509467b48Spatrick 
257609467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
257709467b48Spatrick   // Does not include any dynamic realign.
257809467b48Spatrick   const uint64_t StackSize = MFI.getStackSize();
257909467b48Spatrick   // LLVM arranges the stack as follows:
258009467b48Spatrick   //   ...
258109467b48Spatrick   //   ARG2
258209467b48Spatrick   //   ARG1
258309467b48Spatrick   //   RETADDR
258409467b48Spatrick   //   PUSH RBP   <-- RBP points here
258509467b48Spatrick   //   PUSH CSRs
258609467b48Spatrick   //   ~~~~~~~    <-- possible stack realignment (non-win64)
258709467b48Spatrick   //   ...
258809467b48Spatrick   //   STACK OBJECTS
258909467b48Spatrick   //   ...        <-- RSP after prologue points here
259009467b48Spatrick   //   ~~~~~~~    <-- possible stack realignment (win64)
259109467b48Spatrick   //
259209467b48Spatrick   // if (hasVarSizedObjects()):
259309467b48Spatrick   //   ...        <-- "base pointer" (ESI/RBX) points here
259409467b48Spatrick   //   DYNAMIC ALLOCAS
259509467b48Spatrick   //   ...        <-- RSP points here
259609467b48Spatrick   //
259709467b48Spatrick   // Case 1: In the simple case of no stack realignment and no dynamic
259809467b48Spatrick   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
259909467b48Spatrick   // with fixed offsets from RSP.
260009467b48Spatrick   //
260109467b48Spatrick   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
260209467b48Spatrick   // stack objects are addressed with RBP and regular stack objects with RSP.
260309467b48Spatrick   //
260409467b48Spatrick   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
260509467b48Spatrick   // to address stack arguments for outgoing calls and nothing else. The "base
260609467b48Spatrick   // pointer" points to local variables, and RBP points to fixed objects.
260709467b48Spatrick   //
260809467b48Spatrick   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
260909467b48Spatrick   // answer we give is relative to the SP after the prologue, and not the
261009467b48Spatrick   // SP in the middle of the function.
261109467b48Spatrick 
2612a0747c9fSpatrick   if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
261309467b48Spatrick       !STI.isTargetWin64())
261409467b48Spatrick     return getFrameIndexReference(MF, FI, FrameReg);
261509467b48Spatrick 
261609467b48Spatrick   // If !hasReservedCallFrame the function might have SP adjustement in the
261709467b48Spatrick   // body.  So, even though the offset is statically known, it depends on where
261809467b48Spatrick   // we are in the function.
261909467b48Spatrick   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
262009467b48Spatrick     return getFrameIndexReference(MF, FI, FrameReg);
262109467b48Spatrick 
262209467b48Spatrick   // We don't handle tail calls, and shouldn't be seeing them either.
262309467b48Spatrick   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
262409467b48Spatrick          "we don't handle this case!");
262509467b48Spatrick 
262609467b48Spatrick   // This is how the math works out:
262709467b48Spatrick   //
262809467b48Spatrick   //  %rsp grows (i.e. gets lower) left to right. Each box below is
262909467b48Spatrick   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
263009467b48Spatrick   //  get to.
263109467b48Spatrick   //
263209467b48Spatrick   //    ----------------------------------
263309467b48Spatrick   //    | BP | Obj0 | Obj1 | ... | ObjN |
263409467b48Spatrick   //    ----------------------------------
263509467b48Spatrick   //    ^    ^      ^                   ^
263609467b48Spatrick   //    A    B      C                   E
263709467b48Spatrick   //
263809467b48Spatrick   // A is the incoming stack pointer.
263909467b48Spatrick   // (B - A) is the local area offset (-8 for x86-64) [1]
264009467b48Spatrick   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
264109467b48Spatrick   //
264209467b48Spatrick   // |(E - B)| is the StackSize (absolute value, positive).  For a
264309467b48Spatrick   // stack that grown down, this works out to be (B - E). [3]
264409467b48Spatrick   //
264509467b48Spatrick   // E is also the value of %rsp after stack has been set up, and we
264609467b48Spatrick   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
264709467b48Spatrick   // (C - E) == (C - A) - (B - A) + (B - E)
264809467b48Spatrick   //            { Using [1], [2] and [3] above }
264909467b48Spatrick   //         == getObjectOffset - LocalAreaOffset + StackSize
265009467b48Spatrick 
265109467b48Spatrick   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
265209467b48Spatrick }
265309467b48Spatrick 
assignCalleeSavedSpillSlots(MachineFunction & MF,const TargetRegisterInfo * TRI,std::vector<CalleeSavedInfo> & CSI) const265409467b48Spatrick bool X86FrameLowering::assignCalleeSavedSpillSlots(
265509467b48Spatrick     MachineFunction &MF, const TargetRegisterInfo *TRI,
265609467b48Spatrick     std::vector<CalleeSavedInfo> &CSI) const {
265709467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
265809467b48Spatrick   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
265909467b48Spatrick 
266009467b48Spatrick   unsigned CalleeSavedFrameSize = 0;
266109467b48Spatrick   unsigned XMMCalleeSavedFrameSize = 0;
266209467b48Spatrick   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
266309467b48Spatrick   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
266409467b48Spatrick 
266509467b48Spatrick   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
266609467b48Spatrick 
266709467b48Spatrick   if (TailCallReturnAddrDelta < 0) {
266809467b48Spatrick     // create RETURNADDR area
266909467b48Spatrick     //   arg
267009467b48Spatrick     //   arg
267109467b48Spatrick     //   RETADDR
267209467b48Spatrick     //   { ...
267309467b48Spatrick     //     RETADDR area
267409467b48Spatrick     //     ...
267509467b48Spatrick     //   }
267609467b48Spatrick     //   [EBP]
267709467b48Spatrick     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
267809467b48Spatrick                            TailCallReturnAddrDelta - SlotSize, true);
267909467b48Spatrick   }
268009467b48Spatrick 
268109467b48Spatrick   // Spill the BasePtr if it's used.
268209467b48Spatrick   if (this->TRI->hasBasePointer(MF)) {
268309467b48Spatrick     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
268409467b48Spatrick     if (MF.hasEHFunclets()) {
2685097a140dSpatrick       int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize));
268609467b48Spatrick       X86FI->setHasSEHFramePtrSave(true);
268709467b48Spatrick       X86FI->setSEHFramePtrSaveIndex(FI);
268809467b48Spatrick     }
268909467b48Spatrick   }
269009467b48Spatrick 
269109467b48Spatrick   if (hasFP(MF)) {
269209467b48Spatrick     // emitPrologue always spills frame register the first thing.
269309467b48Spatrick     SpillSlotOffset -= SlotSize;
269409467b48Spatrick     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
269509467b48Spatrick 
2696a0747c9fSpatrick     // The async context lives directly before the frame pointer, and we
2697a0747c9fSpatrick     // allocate a second slot to preserve stack alignment.
2698a0747c9fSpatrick     if (X86FI->hasSwiftAsyncContext()) {
2699a0747c9fSpatrick       SpillSlotOffset -= SlotSize;
2700a0747c9fSpatrick       MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2701a0747c9fSpatrick       SpillSlotOffset -= SlotSize;
2702a0747c9fSpatrick     }
2703a0747c9fSpatrick 
270409467b48Spatrick     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
270509467b48Spatrick     // the frame register, we can delete it from CSI list and not have to worry
270609467b48Spatrick     // about avoiding it later.
270709467b48Spatrick     Register FPReg = TRI->getFrameRegister(MF);
270809467b48Spatrick     for (unsigned i = 0; i < CSI.size(); ++i) {
270909467b48Spatrick       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
271009467b48Spatrick         CSI.erase(CSI.begin() + i);
271109467b48Spatrick         break;
271209467b48Spatrick       }
271309467b48Spatrick     }
271409467b48Spatrick   }
271509467b48Spatrick 
271609467b48Spatrick   // Assign slots for GPRs. It increases frame size.
2717*a96b3639Srobert   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
2718*a96b3639Srobert     Register Reg = I.getReg();
271909467b48Spatrick 
272009467b48Spatrick     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
272109467b48Spatrick       continue;
272209467b48Spatrick 
272309467b48Spatrick     SpillSlotOffset -= SlotSize;
272409467b48Spatrick     CalleeSavedFrameSize += SlotSize;
272509467b48Spatrick 
272609467b48Spatrick     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2727*a96b3639Srobert     I.setFrameIdx(SlotIndex);
272809467b48Spatrick   }
272909467b48Spatrick 
273009467b48Spatrick   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
273109467b48Spatrick   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
273209467b48Spatrick 
273309467b48Spatrick   // Assign slots for XMMs.
2734*a96b3639Srobert   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
2735*a96b3639Srobert     Register Reg = I.getReg();
273609467b48Spatrick     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
273709467b48Spatrick       continue;
273809467b48Spatrick 
273909467b48Spatrick     // If this is k-register make sure we lookup via the largest legal type.
274009467b48Spatrick     MVT VT = MVT::Other;
274109467b48Spatrick     if (X86::VK16RegClass.contains(Reg))
274209467b48Spatrick       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
274309467b48Spatrick 
274409467b48Spatrick     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
274509467b48Spatrick     unsigned Size = TRI->getSpillSize(*RC);
2746097a140dSpatrick     Align Alignment = TRI->getSpillAlign(*RC);
274709467b48Spatrick     // ensure alignment
274809467b48Spatrick     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
2749097a140dSpatrick     SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
275009467b48Spatrick 
275109467b48Spatrick     // spill into slot
275209467b48Spatrick     SpillSlotOffset -= Size;
275309467b48Spatrick     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
2754*a96b3639Srobert     I.setFrameIdx(SlotIndex);
2755097a140dSpatrick     MFI.ensureMaxAlignment(Alignment);
275609467b48Spatrick 
275709467b48Spatrick     // Save the start offset and size of XMM in stack frame for funclets.
275809467b48Spatrick     if (X86::VR128RegClass.contains(Reg)) {
275909467b48Spatrick       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
276009467b48Spatrick       XMMCalleeSavedFrameSize += Size;
276109467b48Spatrick     }
276209467b48Spatrick   }
276309467b48Spatrick 
276409467b48Spatrick   return true;
276509467b48Spatrick }
276609467b48Spatrick 
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const276709467b48Spatrick bool X86FrameLowering::spillCalleeSavedRegisters(
276809467b48Spatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2769097a140dSpatrick     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
277009467b48Spatrick   DebugLoc DL = MBB.findDebugLoc(MI);
277109467b48Spatrick 
277209467b48Spatrick   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
277309467b48Spatrick   // for us, and there are no XMM CSRs on Win32.
277409467b48Spatrick   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
277509467b48Spatrick     return true;
277609467b48Spatrick 
277709467b48Spatrick   // Push GPRs. It increases frame size.
277809467b48Spatrick   const MachineFunction &MF = *MBB.getParent();
277909467b48Spatrick   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
2780*a96b3639Srobert   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
2781*a96b3639Srobert     Register Reg = I.getReg();
278209467b48Spatrick 
278309467b48Spatrick     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
278409467b48Spatrick       continue;
278509467b48Spatrick 
278609467b48Spatrick     const MachineRegisterInfo &MRI = MF.getRegInfo();
278709467b48Spatrick     bool isLiveIn = MRI.isLiveIn(Reg);
278809467b48Spatrick     if (!isLiveIn)
278909467b48Spatrick       MBB.addLiveIn(Reg);
279009467b48Spatrick 
279109467b48Spatrick     // Decide whether we can add a kill flag to the use.
279209467b48Spatrick     bool CanKill = !isLiveIn;
279309467b48Spatrick     // Check if any subregister is live-in
279409467b48Spatrick     if (CanKill) {
279509467b48Spatrick       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
279609467b48Spatrick         if (MRI.isLiveIn(*AReg)) {
279709467b48Spatrick           CanKill = false;
279809467b48Spatrick           break;
279909467b48Spatrick         }
280009467b48Spatrick       }
280109467b48Spatrick     }
280209467b48Spatrick 
280309467b48Spatrick     // Do not set a kill flag on values that are also marked as live-in. This
280409467b48Spatrick     // happens with the @llvm-returnaddress intrinsic and with arguments
280509467b48Spatrick     // passed in callee saved registers.
280609467b48Spatrick     // Omitting the kill flags is conservatively correct even if the live-in
280709467b48Spatrick     // is not used after all.
280809467b48Spatrick     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
280909467b48Spatrick       .setMIFlag(MachineInstr::FrameSetup);
281009467b48Spatrick   }
281109467b48Spatrick 
281209467b48Spatrick   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
281309467b48Spatrick   // It can be done by spilling XMMs to stack frame.
2814*a96b3639Srobert   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
2815*a96b3639Srobert     Register Reg = I.getReg();
281609467b48Spatrick     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
281709467b48Spatrick       continue;
281809467b48Spatrick 
281909467b48Spatrick     // If this is k-register make sure we lookup via the largest legal type.
282009467b48Spatrick     MVT VT = MVT::Other;
282109467b48Spatrick     if (X86::VK16RegClass.contains(Reg))
282209467b48Spatrick       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
282309467b48Spatrick 
282409467b48Spatrick     // Add the callee-saved register as live-in. It's killed at the spill.
282509467b48Spatrick     MBB.addLiveIn(Reg);
282609467b48Spatrick     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
282709467b48Spatrick 
2828*a96b3639Srobert     TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, TRI,
2829*a96b3639Srobert                             Register());
283009467b48Spatrick     --MI;
283109467b48Spatrick     MI->setFlag(MachineInstr::FrameSetup);
283209467b48Spatrick     ++MI;
283309467b48Spatrick   }
283409467b48Spatrick 
283509467b48Spatrick   return true;
283609467b48Spatrick }
283709467b48Spatrick 
emitCatchRetReturnValue(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,MachineInstr * CatchRet) const283809467b48Spatrick void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
283909467b48Spatrick                                                MachineBasicBlock::iterator MBBI,
284009467b48Spatrick                                                MachineInstr *CatchRet) const {
284109467b48Spatrick   // SEH shouldn't use catchret.
284209467b48Spatrick   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
284309467b48Spatrick              MBB.getParent()->getFunction().getPersonalityFn())) &&
284409467b48Spatrick          "SEH should not use CATCHRET");
2845a0747c9fSpatrick   const DebugLoc &DL = CatchRet->getDebugLoc();
284609467b48Spatrick   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
284709467b48Spatrick 
284809467b48Spatrick   // Fill EAX/RAX with the address of the target block.
284909467b48Spatrick   if (STI.is64Bit()) {
285009467b48Spatrick     // LEA64r CatchRetTarget(%rip), %rax
285109467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
285209467b48Spatrick         .addReg(X86::RIP)
285309467b48Spatrick         .addImm(0)
285409467b48Spatrick         .addReg(0)
285509467b48Spatrick         .addMBB(CatchRetTarget)
285609467b48Spatrick         .addReg(0);
285709467b48Spatrick   } else {
285809467b48Spatrick     // MOV32ri $CatchRetTarget, %eax
285909467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
286009467b48Spatrick         .addMBB(CatchRetTarget);
286109467b48Spatrick   }
286209467b48Spatrick 
286309467b48Spatrick   // Record that we've taken the address of CatchRetTarget and no longer just
286409467b48Spatrick   // reference it in a terminator.
2865*a96b3639Srobert   CatchRetTarget->setMachineBlockAddressTaken();
286609467b48Spatrick }
286709467b48Spatrick 
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,MutableArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const2868097a140dSpatrick bool X86FrameLowering::restoreCalleeSavedRegisters(
2869097a140dSpatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2870097a140dSpatrick     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
287109467b48Spatrick   if (CSI.empty())
287209467b48Spatrick     return false;
287309467b48Spatrick 
287409467b48Spatrick   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
287509467b48Spatrick     // Don't restore CSRs in 32-bit EH funclets. Matches
287609467b48Spatrick     // spillCalleeSavedRegisters.
287709467b48Spatrick     if (STI.is32Bit())
287809467b48Spatrick       return true;
287909467b48Spatrick     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
288009467b48Spatrick     // funclets. emitEpilogue transforms these to normal jumps.
288109467b48Spatrick     if (MI->getOpcode() == X86::CATCHRET) {
288209467b48Spatrick       const Function &F = MBB.getParent()->getFunction();
288309467b48Spatrick       bool IsSEH = isAsynchronousEHPersonality(
288409467b48Spatrick           classifyEHPersonality(F.getPersonalityFn()));
288509467b48Spatrick       if (IsSEH)
288609467b48Spatrick         return true;
288709467b48Spatrick     }
288809467b48Spatrick   }
288909467b48Spatrick 
289009467b48Spatrick   DebugLoc DL = MBB.findDebugLoc(MI);
289109467b48Spatrick 
289209467b48Spatrick   // Reload XMMs from stack frame.
2893*a96b3639Srobert   for (const CalleeSavedInfo &I : CSI) {
2894*a96b3639Srobert     Register Reg = I.getReg();
289509467b48Spatrick     if (X86::GR64RegClass.contains(Reg) ||
289609467b48Spatrick         X86::GR32RegClass.contains(Reg))
289709467b48Spatrick       continue;
289809467b48Spatrick 
289909467b48Spatrick     // If this is k-register make sure we lookup via the largest legal type.
290009467b48Spatrick     MVT VT = MVT::Other;
290109467b48Spatrick     if (X86::VK16RegClass.contains(Reg))
290209467b48Spatrick       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
290309467b48Spatrick 
290409467b48Spatrick     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2905*a96b3639Srobert     TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, TRI,
2906*a96b3639Srobert                              Register());
290709467b48Spatrick   }
290809467b48Spatrick 
290909467b48Spatrick   // POP GPRs.
291009467b48Spatrick   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
2911*a96b3639Srobert   for (const CalleeSavedInfo &I : CSI) {
2912*a96b3639Srobert     Register Reg = I.getReg();
291309467b48Spatrick     if (!X86::GR64RegClass.contains(Reg) &&
291409467b48Spatrick         !X86::GR32RegClass.contains(Reg))
291509467b48Spatrick       continue;
291609467b48Spatrick 
291709467b48Spatrick     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
291809467b48Spatrick         .setMIFlag(MachineInstr::FrameDestroy);
291909467b48Spatrick   }
292009467b48Spatrick   return true;
292109467b48Spatrick }
292209467b48Spatrick 
determineCalleeSaves(MachineFunction & MF,BitVector & SavedRegs,RegScavenger * RS) const292309467b48Spatrick void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
292409467b48Spatrick                                             BitVector &SavedRegs,
292509467b48Spatrick                                             RegScavenger *RS) const {
292609467b48Spatrick   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
292709467b48Spatrick 
292809467b48Spatrick   // Spill the BasePtr if it's used.
292909467b48Spatrick   if (TRI->hasBasePointer(MF)){
293009467b48Spatrick     Register BasePtr = TRI->getBaseRegister();
293109467b48Spatrick     if (STI.isTarget64BitILP32())
293209467b48Spatrick       BasePtr = getX86SubSuperRegister(BasePtr, 64);
293309467b48Spatrick     SavedRegs.set(BasePtr);
293409467b48Spatrick   }
293509467b48Spatrick }
293609467b48Spatrick 
293709467b48Spatrick static bool
HasNestArgument(const MachineFunction * MF)293809467b48Spatrick HasNestArgument(const MachineFunction *MF) {
293909467b48Spatrick   const Function &F = MF->getFunction();
294009467b48Spatrick   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
294109467b48Spatrick        I != E; I++) {
294209467b48Spatrick     if (I->hasNestAttr() && !I->use_empty())
294309467b48Spatrick       return true;
294409467b48Spatrick   }
294509467b48Spatrick   return false;
294609467b48Spatrick }
294709467b48Spatrick 
294809467b48Spatrick /// GetScratchRegister - Get a temp register for performing work in the
294909467b48Spatrick /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
295009467b48Spatrick /// and the properties of the function either one or two registers will be
295109467b48Spatrick /// needed. Set primary to true for the first register, false for the second.
295209467b48Spatrick static unsigned
GetScratchRegister(bool Is64Bit,bool IsLP64,const MachineFunction & MF,bool Primary)295309467b48Spatrick GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
295409467b48Spatrick   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
295509467b48Spatrick 
295609467b48Spatrick   // Erlang stuff.
295709467b48Spatrick   if (CallingConvention == CallingConv::HiPE) {
295809467b48Spatrick     if (Is64Bit)
295909467b48Spatrick       return Primary ? X86::R14 : X86::R13;
296009467b48Spatrick     else
296109467b48Spatrick       return Primary ? X86::EBX : X86::EDI;
296209467b48Spatrick   }
296309467b48Spatrick 
296409467b48Spatrick   if (Is64Bit) {
296509467b48Spatrick     if (IsLP64)
296609467b48Spatrick       return Primary ? X86::R11 : X86::R12;
296709467b48Spatrick     else
296809467b48Spatrick       return Primary ? X86::R11D : X86::R12D;
296909467b48Spatrick   }
297009467b48Spatrick 
297109467b48Spatrick   bool IsNested = HasNestArgument(&MF);
297209467b48Spatrick 
297309467b48Spatrick   if (CallingConvention == CallingConv::X86_FastCall ||
297409467b48Spatrick       CallingConvention == CallingConv::Fast ||
297509467b48Spatrick       CallingConvention == CallingConv::Tail) {
297609467b48Spatrick     if (IsNested)
297709467b48Spatrick       report_fatal_error("Segmented stacks does not support fastcall with "
297809467b48Spatrick                          "nested function.");
297909467b48Spatrick     return Primary ? X86::EAX : X86::ECX;
298009467b48Spatrick   }
298109467b48Spatrick   if (IsNested)
298209467b48Spatrick     return Primary ? X86::EDX : X86::EAX;
298309467b48Spatrick   return Primary ? X86::ECX : X86::EAX;
298409467b48Spatrick }
298509467b48Spatrick 
298609467b48Spatrick // The stack limit in the TCB is set to this many bytes above the actual stack
298709467b48Spatrick // limit.
298809467b48Spatrick static const uint64_t kSplitStackAvailable = 256;
298909467b48Spatrick 
adjustForSegmentedStacks(MachineFunction & MF,MachineBasicBlock & PrologueMBB) const299009467b48Spatrick void X86FrameLowering::adjustForSegmentedStacks(
299109467b48Spatrick     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
299209467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
299309467b48Spatrick   uint64_t StackSize;
299409467b48Spatrick   unsigned TlsReg, TlsOffset;
299509467b48Spatrick   DebugLoc DL;
299609467b48Spatrick 
299709467b48Spatrick   // To support shrink-wrapping we would need to insert the new blocks
299809467b48Spatrick   // at the right place and update the branches to PrologueMBB.
299909467b48Spatrick   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
300009467b48Spatrick 
300109467b48Spatrick   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
300209467b48Spatrick   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
300309467b48Spatrick          "Scratch register is live-in");
300409467b48Spatrick 
300509467b48Spatrick   if (MF.getFunction().isVarArg())
300609467b48Spatrick     report_fatal_error("Segmented stacks do not support vararg functions.");
300709467b48Spatrick   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
300809467b48Spatrick       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
300909467b48Spatrick       !STI.isTargetDragonFly())
301009467b48Spatrick     report_fatal_error("Segmented stacks not supported on this platform.");
301109467b48Spatrick 
301209467b48Spatrick   // Eventually StackSize will be calculated by a link-time pass; which will
301309467b48Spatrick   // also decide whether checking code needs to be injected into this particular
301409467b48Spatrick   // prologue.
301509467b48Spatrick   StackSize = MFI.getStackSize();
301609467b48Spatrick 
3017*a96b3639Srobert   if (!MFI.needsSplitStackProlog())
301809467b48Spatrick     return;
301909467b48Spatrick 
302009467b48Spatrick   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
302109467b48Spatrick   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
302209467b48Spatrick   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
302309467b48Spatrick   bool IsNested = false;
302409467b48Spatrick 
302509467b48Spatrick   // We need to know if the function has a nest argument only in 64 bit mode.
302609467b48Spatrick   if (Is64Bit)
302709467b48Spatrick     IsNested = HasNestArgument(&MF);
302809467b48Spatrick 
302909467b48Spatrick   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
303009467b48Spatrick   // allocMBB needs to be last (terminating) instruction.
303109467b48Spatrick 
303209467b48Spatrick   for (const auto &LI : PrologueMBB.liveins()) {
303309467b48Spatrick     allocMBB->addLiveIn(LI);
303409467b48Spatrick     checkMBB->addLiveIn(LI);
303509467b48Spatrick   }
303609467b48Spatrick 
303709467b48Spatrick   if (IsNested)
303809467b48Spatrick     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
303909467b48Spatrick 
304009467b48Spatrick   MF.push_front(allocMBB);
304109467b48Spatrick   MF.push_front(checkMBB);
304209467b48Spatrick 
304309467b48Spatrick   // When the frame size is less than 256 we just compare the stack
304409467b48Spatrick   // boundary directly to the value of the stack pointer, per gcc.
304509467b48Spatrick   bool CompareStackPointer = StackSize < kSplitStackAvailable;
304609467b48Spatrick 
304709467b48Spatrick   // Read the limit off the current stacklet off the stack_guard location.
304809467b48Spatrick   if (Is64Bit) {
304909467b48Spatrick     if (STI.isTargetLinux()) {
305009467b48Spatrick       TlsReg = X86::FS;
305109467b48Spatrick       TlsOffset = IsLP64 ? 0x70 : 0x40;
305209467b48Spatrick     } else if (STI.isTargetDarwin()) {
305309467b48Spatrick       TlsReg = X86::GS;
305409467b48Spatrick       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
305509467b48Spatrick     } else if (STI.isTargetWin64()) {
305609467b48Spatrick       TlsReg = X86::GS;
305709467b48Spatrick       TlsOffset = 0x28; // pvArbitrary, reserved for application use
305809467b48Spatrick     } else if (STI.isTargetFreeBSD()) {
305909467b48Spatrick       TlsReg = X86::FS;
306009467b48Spatrick       TlsOffset = 0x18;
306109467b48Spatrick     } else if (STI.isTargetDragonFly()) {
306209467b48Spatrick       TlsReg = X86::FS;
306309467b48Spatrick       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
306409467b48Spatrick     } else {
306509467b48Spatrick       report_fatal_error("Segmented stacks not supported on this platform.");
306609467b48Spatrick     }
306709467b48Spatrick 
306809467b48Spatrick     if (CompareStackPointer)
306909467b48Spatrick       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
307009467b48Spatrick     else
307109467b48Spatrick       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
307209467b48Spatrick         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
307309467b48Spatrick 
307409467b48Spatrick     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
307509467b48Spatrick       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
307609467b48Spatrick   } else {
307709467b48Spatrick     if (STI.isTargetLinux()) {
307809467b48Spatrick       TlsReg = X86::GS;
307909467b48Spatrick       TlsOffset = 0x30;
308009467b48Spatrick     } else if (STI.isTargetDarwin()) {
308109467b48Spatrick       TlsReg = X86::GS;
308209467b48Spatrick       TlsOffset = 0x48 + 90*4;
308309467b48Spatrick     } else if (STI.isTargetWin32()) {
308409467b48Spatrick       TlsReg = X86::FS;
308509467b48Spatrick       TlsOffset = 0x14; // pvArbitrary, reserved for application use
308609467b48Spatrick     } else if (STI.isTargetDragonFly()) {
308709467b48Spatrick       TlsReg = X86::FS;
308809467b48Spatrick       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
308909467b48Spatrick     } else if (STI.isTargetFreeBSD()) {
309009467b48Spatrick       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
309109467b48Spatrick     } else {
309209467b48Spatrick       report_fatal_error("Segmented stacks not supported on this platform.");
309309467b48Spatrick     }
309409467b48Spatrick 
309509467b48Spatrick     if (CompareStackPointer)
309609467b48Spatrick       ScratchReg = X86::ESP;
309709467b48Spatrick     else
309809467b48Spatrick       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
309909467b48Spatrick         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
310009467b48Spatrick 
310109467b48Spatrick     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
310209467b48Spatrick         STI.isTargetDragonFly()) {
310309467b48Spatrick       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
310409467b48Spatrick         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
310509467b48Spatrick     } else if (STI.isTargetDarwin()) {
310609467b48Spatrick 
310709467b48Spatrick       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
310809467b48Spatrick       unsigned ScratchReg2;
310909467b48Spatrick       bool SaveScratch2;
311009467b48Spatrick       if (CompareStackPointer) {
311109467b48Spatrick         // The primary scratch register is available for holding the TLS offset.
311209467b48Spatrick         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
311309467b48Spatrick         SaveScratch2 = false;
311409467b48Spatrick       } else {
311509467b48Spatrick         // Need to use a second register to hold the TLS offset
311609467b48Spatrick         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
311709467b48Spatrick 
311809467b48Spatrick         // Unfortunately, with fastcc the second scratch register may hold an
311909467b48Spatrick         // argument.
312009467b48Spatrick         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
312109467b48Spatrick       }
312209467b48Spatrick 
312309467b48Spatrick       // If Scratch2 is live-in then it needs to be saved.
312409467b48Spatrick       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
312509467b48Spatrick              "Scratch register is live-in and not saved");
312609467b48Spatrick 
312709467b48Spatrick       if (SaveScratch2)
312809467b48Spatrick         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
312909467b48Spatrick           .addReg(ScratchReg2, RegState::Kill);
313009467b48Spatrick 
313109467b48Spatrick       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
313209467b48Spatrick         .addImm(TlsOffset);
313309467b48Spatrick       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
313409467b48Spatrick         .addReg(ScratchReg)
313509467b48Spatrick         .addReg(ScratchReg2).addImm(1).addReg(0)
313609467b48Spatrick         .addImm(0)
313709467b48Spatrick         .addReg(TlsReg);
313809467b48Spatrick 
313909467b48Spatrick       if (SaveScratch2)
314009467b48Spatrick         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
314109467b48Spatrick     }
314209467b48Spatrick   }
314309467b48Spatrick 
314409467b48Spatrick   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
314509467b48Spatrick   // It jumps to normal execution of the function body.
314609467b48Spatrick   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
314709467b48Spatrick 
314809467b48Spatrick   // On 32 bit we first push the arguments size and then the frame size. On 64
314909467b48Spatrick   // bit, we pass the stack frame size in r10 and the argument size in r11.
315009467b48Spatrick   if (Is64Bit) {
315109467b48Spatrick     // Functions with nested arguments use R10, so it needs to be saved across
315209467b48Spatrick     // the call to _morestack
315309467b48Spatrick 
315409467b48Spatrick     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
315509467b48Spatrick     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
315609467b48Spatrick     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
315709467b48Spatrick     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
315809467b48Spatrick 
315909467b48Spatrick     if (IsNested)
316009467b48Spatrick       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
316109467b48Spatrick 
3162*a96b3639Srobert     BuildMI(allocMBB, DL, TII.get(getMOVriOpcode(IsLP64, StackSize)), Reg10)
316309467b48Spatrick         .addImm(StackSize);
3164*a96b3639Srobert     BuildMI(allocMBB, DL,
3165*a96b3639Srobert             TII.get(getMOVriOpcode(IsLP64, X86FI->getArgumentStackSize())),
3166*a96b3639Srobert             Reg11)
316709467b48Spatrick         .addImm(X86FI->getArgumentStackSize());
316809467b48Spatrick   } else {
316909467b48Spatrick     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
317009467b48Spatrick       .addImm(X86FI->getArgumentStackSize());
317109467b48Spatrick     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
317209467b48Spatrick       .addImm(StackSize);
317309467b48Spatrick   }
317409467b48Spatrick 
317509467b48Spatrick   // __morestack is in libgcc
317609467b48Spatrick   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
317709467b48Spatrick     // Under the large code model, we cannot assume that __morestack lives
317809467b48Spatrick     // within 2^31 bytes of the call site, so we cannot use pc-relative
317909467b48Spatrick     // addressing. We cannot perform the call via a temporary register,
318009467b48Spatrick     // as the rax register may be used to store the static chain, and all
318109467b48Spatrick     // other suitable registers may be either callee-save or used for
318209467b48Spatrick     // parameter passing. We cannot use the stack at this point either
318309467b48Spatrick     // because __morestack manipulates the stack directly.
318409467b48Spatrick     //
318509467b48Spatrick     // To avoid these issues, perform an indirect call via a read-only memory
318609467b48Spatrick     // location containing the address.
318709467b48Spatrick     //
318809467b48Spatrick     // This solution is not perfect, as it assumes that the .rodata section
318909467b48Spatrick     // is laid out within 2^31 bytes of each function body, but this seems
319009467b48Spatrick     // to be sufficient for JIT.
319109467b48Spatrick     // FIXME: Add retpoline support and remove the error here..
31927299aa8dSpatrick     if (STI.useIndirectThunkCalls())
319309467b48Spatrick       report_fatal_error("Emitting morestack calls on 64-bit with the large "
31947299aa8dSpatrick                          "code model and thunks not yet implemented.");
319509467b48Spatrick     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
319609467b48Spatrick         .addReg(X86::RIP)
319709467b48Spatrick         .addImm(0)
319809467b48Spatrick         .addReg(0)
319909467b48Spatrick         .addExternalSymbol("__morestack_addr")
320009467b48Spatrick         .addReg(0);
320109467b48Spatrick   } else {
320209467b48Spatrick     if (Is64Bit)
320309467b48Spatrick       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
320409467b48Spatrick         .addExternalSymbol("__morestack");
320509467b48Spatrick     else
320609467b48Spatrick       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
320709467b48Spatrick         .addExternalSymbol("__morestack");
320809467b48Spatrick   }
320909467b48Spatrick 
321009467b48Spatrick   if (IsNested)
321109467b48Spatrick     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
321209467b48Spatrick   else
321309467b48Spatrick     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
321409467b48Spatrick 
321509467b48Spatrick   allocMBB->addSuccessor(&PrologueMBB);
321609467b48Spatrick 
321709467b48Spatrick   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
321809467b48Spatrick   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
321909467b48Spatrick 
322009467b48Spatrick #ifdef EXPENSIVE_CHECKS
322109467b48Spatrick   MF.verify();
322209467b48Spatrick #endif
322309467b48Spatrick }
322409467b48Spatrick 
322509467b48Spatrick /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
322609467b48Spatrick /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
322709467b48Spatrick /// to fields it needs, through a named metadata node "hipe.literals" containing
322809467b48Spatrick /// name-value pairs.
getHiPELiteral(NamedMDNode * HiPELiteralsMD,const StringRef LiteralName)322909467b48Spatrick static unsigned getHiPELiteral(
323009467b48Spatrick     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
323109467b48Spatrick   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
323209467b48Spatrick     MDNode *Node = HiPELiteralsMD->getOperand(i);
323309467b48Spatrick     if (Node->getNumOperands() != 2) continue;
323409467b48Spatrick     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
323509467b48Spatrick     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
323609467b48Spatrick     if (!NodeName || !NodeVal) continue;
323709467b48Spatrick     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
323809467b48Spatrick     if (ValConst && NodeName->getString() == LiteralName) {
323909467b48Spatrick       return ValConst->getZExtValue();
324009467b48Spatrick     }
324109467b48Spatrick   }
324209467b48Spatrick 
324309467b48Spatrick   report_fatal_error("HiPE literal " + LiteralName
324409467b48Spatrick                      + " required but not provided");
324509467b48Spatrick }
324609467b48Spatrick 
324709467b48Spatrick // Return true if there are no non-ehpad successors to MBB and there are no
324809467b48Spatrick // non-meta instructions between MBBI and MBB.end().
blockEndIsUnreachable(const MachineBasicBlock & MBB,MachineBasicBlock::const_iterator MBBI)324909467b48Spatrick static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
325009467b48Spatrick                                   MachineBasicBlock::const_iterator MBBI) {
3251a0747c9fSpatrick   return llvm::all_of(
3252a0747c9fSpatrick              MBB.successors(),
325309467b48Spatrick              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
325409467b48Spatrick          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
325509467b48Spatrick            return MI.isMetaInstruction();
325609467b48Spatrick          });
325709467b48Spatrick }
325809467b48Spatrick 
325909467b48Spatrick /// Erlang programs may need a special prologue to handle the stack size they
326009467b48Spatrick /// might need at runtime. That is because Erlang/OTP does not implement a C
326109467b48Spatrick /// stack but uses a custom implementation of hybrid stack/heap architecture.
326209467b48Spatrick /// (for more information see Eric Stenman's Ph.D. thesis:
326309467b48Spatrick /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
326409467b48Spatrick ///
326509467b48Spatrick /// CheckStack:
326609467b48Spatrick ///       temp0 = sp - MaxStack
326709467b48Spatrick ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
326809467b48Spatrick /// OldStart:
326909467b48Spatrick ///       ...
327009467b48Spatrick /// IncStack:
327109467b48Spatrick ///       call inc_stack   # doubles the stack space
327209467b48Spatrick ///       temp0 = sp - MaxStack
327309467b48Spatrick ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
adjustForHiPEPrologue(MachineFunction & MF,MachineBasicBlock & PrologueMBB) const327409467b48Spatrick void X86FrameLowering::adjustForHiPEPrologue(
327509467b48Spatrick     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
327609467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
327709467b48Spatrick   DebugLoc DL;
327809467b48Spatrick 
327909467b48Spatrick   // To support shrink-wrapping we would need to insert the new blocks
328009467b48Spatrick   // at the right place and update the branches to PrologueMBB.
328109467b48Spatrick   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
328209467b48Spatrick 
328309467b48Spatrick   // HiPE-specific values
328409467b48Spatrick   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
328509467b48Spatrick     ->getNamedMetadata("hipe.literals");
328609467b48Spatrick   if (!HiPELiteralsMD)
328709467b48Spatrick     report_fatal_error(
328809467b48Spatrick         "Can't generate HiPE prologue without runtime parameters");
328909467b48Spatrick   const unsigned HipeLeafWords
329009467b48Spatrick     = getHiPELiteral(HiPELiteralsMD,
329109467b48Spatrick                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
329209467b48Spatrick   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
329309467b48Spatrick   const unsigned Guaranteed = HipeLeafWords * SlotSize;
329409467b48Spatrick   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
329509467b48Spatrick                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
329609467b48Spatrick   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
329709467b48Spatrick 
329809467b48Spatrick   assert(STI.isTargetLinux() &&
329909467b48Spatrick          "HiPE prologue is only supported on Linux operating systems.");
330009467b48Spatrick 
330109467b48Spatrick   // Compute the largest caller's frame that is needed to fit the callees'
330209467b48Spatrick   // frames. This 'MaxStack' is computed from:
330309467b48Spatrick   //
330409467b48Spatrick   // a) the fixed frame size, which is the space needed for all spilled temps,
330509467b48Spatrick   // b) outgoing on-stack parameter areas, and
330609467b48Spatrick   // c) the minimum stack space this function needs to make available for the
330709467b48Spatrick   //    functions it calls (a tunable ABI property).
330809467b48Spatrick   if (MFI.hasCalls()) {
330909467b48Spatrick     unsigned MoreStackForCalls = 0;
331009467b48Spatrick 
331109467b48Spatrick     for (auto &MBB : MF) {
331209467b48Spatrick       for (auto &MI : MBB) {
331309467b48Spatrick         if (!MI.isCall())
331409467b48Spatrick           continue;
331509467b48Spatrick 
331609467b48Spatrick         // Get callee operand.
331709467b48Spatrick         const MachineOperand &MO = MI.getOperand(0);
331809467b48Spatrick 
331909467b48Spatrick         // Only take account of global function calls (no closures etc.).
332009467b48Spatrick         if (!MO.isGlobal())
332109467b48Spatrick           continue;
332209467b48Spatrick 
332309467b48Spatrick         const Function *F = dyn_cast<Function>(MO.getGlobal());
332409467b48Spatrick         if (!F)
332509467b48Spatrick           continue;
332609467b48Spatrick 
332709467b48Spatrick         // Do not update 'MaxStack' for primitive and built-in functions
332809467b48Spatrick         // (encoded with names either starting with "erlang."/"bif_" or not
332909467b48Spatrick         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
333009467b48Spatrick         // "_", such as the BIF "suspend_0") as they are executed on another
333109467b48Spatrick         // stack.
3332*a96b3639Srobert         if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
333309467b48Spatrick             F->getName().find_first_of("._") == StringRef::npos)
333409467b48Spatrick           continue;
333509467b48Spatrick 
333609467b48Spatrick         unsigned CalleeStkArity =
333709467b48Spatrick           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
333809467b48Spatrick         if (HipeLeafWords - 1 > CalleeStkArity)
333909467b48Spatrick           MoreStackForCalls = std::max(MoreStackForCalls,
334009467b48Spatrick                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
334109467b48Spatrick       }
334209467b48Spatrick     }
334309467b48Spatrick     MaxStack += MoreStackForCalls;
334409467b48Spatrick   }
334509467b48Spatrick 
334609467b48Spatrick   // If the stack frame needed is larger than the guaranteed then runtime checks
334709467b48Spatrick   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
334809467b48Spatrick   if (MaxStack > Guaranteed) {
334909467b48Spatrick     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
335009467b48Spatrick     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
335109467b48Spatrick 
335209467b48Spatrick     for (const auto &LI : PrologueMBB.liveins()) {
335309467b48Spatrick       stackCheckMBB->addLiveIn(LI);
335409467b48Spatrick       incStackMBB->addLiveIn(LI);
335509467b48Spatrick     }
335609467b48Spatrick 
335709467b48Spatrick     MF.push_front(incStackMBB);
335809467b48Spatrick     MF.push_front(stackCheckMBB);
335909467b48Spatrick 
336009467b48Spatrick     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
336109467b48Spatrick     unsigned LEAop, CMPop, CALLop;
336209467b48Spatrick     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
336309467b48Spatrick     if (Is64Bit) {
336409467b48Spatrick       SPReg = X86::RSP;
336509467b48Spatrick       PReg  = X86::RBP;
336609467b48Spatrick       LEAop = X86::LEA64r;
336709467b48Spatrick       CMPop = X86::CMP64rm;
336809467b48Spatrick       CALLop = X86::CALL64pcrel32;
336909467b48Spatrick     } else {
337009467b48Spatrick       SPReg = X86::ESP;
337109467b48Spatrick       PReg  = X86::EBP;
337209467b48Spatrick       LEAop = X86::LEA32r;
337309467b48Spatrick       CMPop = X86::CMP32rm;
337409467b48Spatrick       CALLop = X86::CALLpcrel32;
337509467b48Spatrick     }
337609467b48Spatrick 
337709467b48Spatrick     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
337809467b48Spatrick     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
337909467b48Spatrick            "HiPE prologue scratch register is live-in");
338009467b48Spatrick 
338109467b48Spatrick     // Create new MBB for StackCheck:
338209467b48Spatrick     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
338309467b48Spatrick                  SPReg, false, -MaxStack);
338409467b48Spatrick     // SPLimitOffset is in a fixed heap location (pointed by BP).
338509467b48Spatrick     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
338609467b48Spatrick                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
338709467b48Spatrick     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
338809467b48Spatrick 
338909467b48Spatrick     // Create new MBB for IncStack:
339009467b48Spatrick     BuildMI(incStackMBB, DL, TII.get(CALLop)).
339109467b48Spatrick       addExternalSymbol("inc_stack_0");
339209467b48Spatrick     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
339309467b48Spatrick                  SPReg, false, -MaxStack);
339409467b48Spatrick     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
339509467b48Spatrick                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
339609467b48Spatrick     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
339709467b48Spatrick 
339809467b48Spatrick     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
339909467b48Spatrick     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
340009467b48Spatrick     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
340109467b48Spatrick     incStackMBB->addSuccessor(incStackMBB, {1, 100});
340209467b48Spatrick   }
340309467b48Spatrick #ifdef EXPENSIVE_CHECKS
340409467b48Spatrick   MF.verify();
340509467b48Spatrick #endif
340609467b48Spatrick }
340709467b48Spatrick 
adjustStackWithPops(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,int Offset) const340809467b48Spatrick bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
340909467b48Spatrick                                            MachineBasicBlock::iterator MBBI,
341009467b48Spatrick                                            const DebugLoc &DL,
341109467b48Spatrick                                            int Offset) const {
341209467b48Spatrick   if (Offset <= 0)
341309467b48Spatrick     return false;
341409467b48Spatrick 
341509467b48Spatrick   if (Offset % SlotSize)
341609467b48Spatrick     return false;
341709467b48Spatrick 
341809467b48Spatrick   int NumPops = Offset / SlotSize;
341909467b48Spatrick   // This is only worth it if we have at most 2 pops.
342009467b48Spatrick   if (NumPops != 1 && NumPops != 2)
342109467b48Spatrick     return false;
342209467b48Spatrick 
342309467b48Spatrick   // Handle only the trivial case where the adjustment directly follows
342409467b48Spatrick   // a call. This is the most common one, anyway.
342509467b48Spatrick   if (MBBI == MBB.begin())
342609467b48Spatrick     return false;
342709467b48Spatrick   MachineBasicBlock::iterator Prev = std::prev(MBBI);
342809467b48Spatrick   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
342909467b48Spatrick     return false;
343009467b48Spatrick 
343109467b48Spatrick   unsigned Regs[2];
343209467b48Spatrick   unsigned FoundRegs = 0;
343309467b48Spatrick 
3434a0747c9fSpatrick   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3435a0747c9fSpatrick   const MachineOperand &RegMask = Prev->getOperand(1);
343609467b48Spatrick 
343709467b48Spatrick   auto &RegClass =
343809467b48Spatrick       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
343909467b48Spatrick   // Try to find up to NumPops free registers.
344009467b48Spatrick   for (auto Candidate : RegClass) {
344109467b48Spatrick     // Poor man's liveness:
344209467b48Spatrick     // Since we're immediately after a call, any register that is clobbered
344309467b48Spatrick     // by the call and not defined by it can be considered dead.
344409467b48Spatrick     if (!RegMask.clobbersPhysReg(Candidate))
344509467b48Spatrick       continue;
344609467b48Spatrick 
344709467b48Spatrick     // Don't clobber reserved registers
344809467b48Spatrick     if (MRI.isReserved(Candidate))
344909467b48Spatrick       continue;
345009467b48Spatrick 
345109467b48Spatrick     bool IsDef = false;
345209467b48Spatrick     for (const MachineOperand &MO : Prev->implicit_operands()) {
345309467b48Spatrick       if (MO.isReg() && MO.isDef() &&
345409467b48Spatrick           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
345509467b48Spatrick         IsDef = true;
345609467b48Spatrick         break;
345709467b48Spatrick       }
345809467b48Spatrick     }
345909467b48Spatrick 
346009467b48Spatrick     if (IsDef)
346109467b48Spatrick       continue;
346209467b48Spatrick 
346309467b48Spatrick     Regs[FoundRegs++] = Candidate;
346409467b48Spatrick     if (FoundRegs == (unsigned)NumPops)
346509467b48Spatrick       break;
346609467b48Spatrick   }
346709467b48Spatrick 
346809467b48Spatrick   if (FoundRegs == 0)
346909467b48Spatrick     return false;
347009467b48Spatrick 
347109467b48Spatrick   // If we found only one free register, but need two, reuse the same one twice.
347209467b48Spatrick   while (FoundRegs < (unsigned)NumPops)
347309467b48Spatrick     Regs[FoundRegs++] = Regs[0];
347409467b48Spatrick 
347509467b48Spatrick   for (int i = 0; i < NumPops; ++i)
347609467b48Spatrick     BuildMI(MBB, MBBI, DL,
347709467b48Spatrick             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
347809467b48Spatrick 
347909467b48Spatrick   return true;
348009467b48Spatrick }
348109467b48Spatrick 
348209467b48Spatrick MachineBasicBlock::iterator X86FrameLowering::
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const348309467b48Spatrick eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
348409467b48Spatrick                               MachineBasicBlock::iterator I) const {
348509467b48Spatrick   bool reserveCallFrame = hasReservedCallFrame(MF);
348609467b48Spatrick   unsigned Opcode = I->getOpcode();
348709467b48Spatrick   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
3488a0747c9fSpatrick   DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
348909467b48Spatrick   uint64_t Amount = TII.getFrameSize(*I);
349009467b48Spatrick   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
349109467b48Spatrick   I = MBB.erase(I);
349209467b48Spatrick   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
349309467b48Spatrick 
3494097a140dSpatrick   // Try to avoid emitting dead SP adjustments if the block end is unreachable,
3495097a140dSpatrick   // typically because the function is marked noreturn (abort, throw,
3496097a140dSpatrick   // assert_fail, etc).
3497097a140dSpatrick   if (isDestroy && blockEndIsUnreachable(MBB, I))
3498097a140dSpatrick     return I;
3499097a140dSpatrick 
350009467b48Spatrick   if (!reserveCallFrame) {
350109467b48Spatrick     // If the stack pointer can be changed after prologue, turn the
350209467b48Spatrick     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
350309467b48Spatrick     // adjcallstackdown instruction into 'add ESP, <amt>'
350409467b48Spatrick 
350509467b48Spatrick     // We need to keep the stack aligned properly.  To do this, we round the
350609467b48Spatrick     // amount of space needed for the outgoing arguments up to the next
350709467b48Spatrick     // alignment boundary.
3508097a140dSpatrick     Amount = alignTo(Amount, getStackAlign());
350909467b48Spatrick 
351009467b48Spatrick     const Function &F = MF.getFunction();
351109467b48Spatrick     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
351209467b48Spatrick     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
351309467b48Spatrick 
351409467b48Spatrick     // If we have any exception handlers in this function, and we adjust
351509467b48Spatrick     // the SP before calls, we may need to indicate this to the unwinder
351609467b48Spatrick     // using GNU_ARGS_SIZE. Note that this may be necessary even when
351709467b48Spatrick     // Amount == 0, because the preceding function may have set a non-0
351809467b48Spatrick     // GNU_ARGS_SIZE.
351909467b48Spatrick     // TODO: We don't need to reset this between subsequent functions,
352009467b48Spatrick     // if it didn't change.
352109467b48Spatrick     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
352209467b48Spatrick 
352309467b48Spatrick     if (HasDwarfEHHandlers && !isDestroy &&
352409467b48Spatrick         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
352509467b48Spatrick       BuildCFI(MBB, InsertPos, DL,
352609467b48Spatrick                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
352709467b48Spatrick 
352809467b48Spatrick     if (Amount == 0)
352909467b48Spatrick       return I;
353009467b48Spatrick 
353109467b48Spatrick     // Factor out the amount that gets handled inside the sequence
353209467b48Spatrick     // (Pushes of argument for frame setup, callee pops for frame destroy)
353309467b48Spatrick     Amount -= InternalAmt;
353409467b48Spatrick 
353509467b48Spatrick     // TODO: This is needed only if we require precise CFA.
353609467b48Spatrick     // If this is a callee-pop calling convention, emit a CFA adjust for
353709467b48Spatrick     // the amount the callee popped.
353809467b48Spatrick     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
353909467b48Spatrick       BuildCFI(MBB, InsertPos, DL,
354009467b48Spatrick                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
354109467b48Spatrick 
354209467b48Spatrick     // Add Amount to SP to destroy a frame, or subtract to setup.
354309467b48Spatrick     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
354409467b48Spatrick 
354509467b48Spatrick     if (StackAdjustment) {
354609467b48Spatrick       // Merge with any previous or following adjustment instruction. Note: the
354709467b48Spatrick       // instructions merged with here do not have CFI, so their stack
354809467b48Spatrick       // adjustments do not feed into CfaAdjustment.
354909467b48Spatrick       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
355009467b48Spatrick       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
355109467b48Spatrick 
355209467b48Spatrick       if (StackAdjustment) {
355309467b48Spatrick         if (!(F.hasMinSize() &&
355409467b48Spatrick               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
355509467b48Spatrick           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
355609467b48Spatrick                                /*InEpilogue=*/false);
355709467b48Spatrick       }
355809467b48Spatrick     }
355909467b48Spatrick 
356009467b48Spatrick     if (DwarfCFI && !hasFP(MF)) {
356109467b48Spatrick       // If we don't have FP, but need to generate unwind information,
356209467b48Spatrick       // we need to set the correct CFA offset after the stack adjustment.
356309467b48Spatrick       // How much we adjust the CFA offset depends on whether we're emitting
356409467b48Spatrick       // CFI only for EH purposes or for debugging. EH only requires the CFA
356509467b48Spatrick       // offset to be correct at each call site, while for debugging we want
356609467b48Spatrick       // it to be more precise.
356709467b48Spatrick 
356809467b48Spatrick       int64_t CfaAdjustment = -StackAdjustment;
356909467b48Spatrick       // TODO: When not using precise CFA, we also need to adjust for the
357009467b48Spatrick       // InternalAmt here.
357109467b48Spatrick       if (CfaAdjustment) {
357209467b48Spatrick         BuildCFI(MBB, InsertPos, DL,
357309467b48Spatrick                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
357409467b48Spatrick                                                          CfaAdjustment));
357509467b48Spatrick       }
357609467b48Spatrick     }
357709467b48Spatrick 
357809467b48Spatrick     return I;
357909467b48Spatrick   }
358009467b48Spatrick 
3581097a140dSpatrick   if (InternalAmt) {
358209467b48Spatrick     MachineBasicBlock::iterator CI = I;
358309467b48Spatrick     MachineBasicBlock::iterator B = MBB.begin();
358409467b48Spatrick     while (CI != B && !std::prev(CI)->isCall())
358509467b48Spatrick       --CI;
358609467b48Spatrick     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
358709467b48Spatrick   }
358809467b48Spatrick 
358909467b48Spatrick   return I;
359009467b48Spatrick }
359109467b48Spatrick 
canUseAsPrologue(const MachineBasicBlock & MBB) const359209467b48Spatrick bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
359309467b48Spatrick   assert(MBB.getParent() && "Block is not attached to a function!");
359409467b48Spatrick   const MachineFunction &MF = *MBB.getParent();
3595a0747c9fSpatrick   if (!MBB.isLiveIn(X86::EFLAGS))
3596a0747c9fSpatrick     return true;
3597a0747c9fSpatrick 
3598*a96b3639Srobert   // If stack probes have to loop inline or call, that will clobber EFLAGS.
3599*a96b3639Srobert   // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
3600*a96b3639Srobert   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
3601*a96b3639Srobert   const X86TargetLowering &TLI = *STI.getTargetLowering();
3602*a96b3639Srobert   if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
3603*a96b3639Srobert     return false;
3604*a96b3639Srobert 
3605a0747c9fSpatrick   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3606a0747c9fSpatrick   return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
360709467b48Spatrick }
360809467b48Spatrick 
canUseAsEpilogue(const MachineBasicBlock & MBB) const360909467b48Spatrick bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
361009467b48Spatrick   assert(MBB.getParent() && "Block is not attached to a function!");
361109467b48Spatrick 
361209467b48Spatrick   // Win64 has strict requirements in terms of epilogue and we are
361309467b48Spatrick   // not taking a chance at messing with them.
361409467b48Spatrick   // I.e., unless this block is already an exit block, we can't use
361509467b48Spatrick   // it as an epilogue.
361609467b48Spatrick   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
361709467b48Spatrick     return false;
361809467b48Spatrick 
3619a0747c9fSpatrick   // Swift async context epilogue has a BTR instruction that clobbers parts of
3620a0747c9fSpatrick   // EFLAGS.
3621a0747c9fSpatrick   const MachineFunction &MF = *MBB.getParent();
3622a0747c9fSpatrick   if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext())
3623a0747c9fSpatrick     return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
3624a0747c9fSpatrick 
362509467b48Spatrick   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
362609467b48Spatrick     return true;
362709467b48Spatrick 
362809467b48Spatrick   // If we cannot use LEA to adjust SP, we may need to use ADD, which
362909467b48Spatrick   // clobbers the EFLAGS. Check that we do not need to preserve it,
363009467b48Spatrick   // otherwise, conservatively assume this is not
363109467b48Spatrick   // safe to insert the epilogue here.
363209467b48Spatrick   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
363309467b48Spatrick }
363409467b48Spatrick 
enableShrinkWrapping(const MachineFunction & MF) const363509467b48Spatrick bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
363609467b48Spatrick   // If we may need to emit frameless compact unwind information, give
363709467b48Spatrick   // up as this is currently broken: PR25614.
3638a0747c9fSpatrick   bool CompactUnwind =
3639a0747c9fSpatrick       MF.getMMI().getContext().getObjectFileInfo()->getCompactUnwindSection() !=
3640a0747c9fSpatrick       nullptr;
3641a0747c9fSpatrick   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
3642a0747c9fSpatrick           !CompactUnwind) &&
3643a0747c9fSpatrick          // The lowering of segmented stack and HiPE only support entry
3644a0747c9fSpatrick          // blocks as prologue blocks: PR26107. This limitation may be
3645a0747c9fSpatrick          // lifted if we fix:
364609467b48Spatrick          // - adjustForSegmentedStacks
364709467b48Spatrick          // - adjustForHiPEPrologue
364809467b48Spatrick          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
364909467b48Spatrick          !MF.shouldSplitStack();
365009467b48Spatrick }
365109467b48Spatrick 
restoreWin32EHStackPointers(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool RestoreSP) const365209467b48Spatrick MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
365309467b48Spatrick     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
365409467b48Spatrick     const DebugLoc &DL, bool RestoreSP) const {
365509467b48Spatrick   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
365609467b48Spatrick   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
365709467b48Spatrick   assert(STI.is32Bit() && !Uses64BitFramePtr &&
365809467b48Spatrick          "restoring EBP/ESI on non-32-bit target");
365909467b48Spatrick 
366009467b48Spatrick   MachineFunction &MF = *MBB.getParent();
366109467b48Spatrick   Register FramePtr = TRI->getFrameRegister(MF);
366209467b48Spatrick   Register BasePtr = TRI->getBaseRegister();
366309467b48Spatrick   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
366409467b48Spatrick   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
366509467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
366609467b48Spatrick 
366709467b48Spatrick   // FIXME: Don't set FrameSetup flag in catchret case.
366809467b48Spatrick 
366909467b48Spatrick   int FI = FuncInfo.EHRegNodeFrameIndex;
367009467b48Spatrick   int EHRegSize = MFI.getObjectSize(FI);
367109467b48Spatrick 
367209467b48Spatrick   if (RestoreSP) {
367309467b48Spatrick     // MOV32rm -EHRegSize(%ebp), %esp
367409467b48Spatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
367509467b48Spatrick                  X86::EBP, true, -EHRegSize)
367609467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
367709467b48Spatrick   }
367809467b48Spatrick 
3679097a140dSpatrick   Register UsedReg;
3680a0747c9fSpatrick   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
368109467b48Spatrick   int EndOffset = -EHRegOffset - EHRegSize;
368209467b48Spatrick   FuncInfo.EHRegNodeEndOffset = EndOffset;
368309467b48Spatrick 
368409467b48Spatrick   if (UsedReg == FramePtr) {
368509467b48Spatrick     // ADD $offset, %ebp
368609467b48Spatrick     unsigned ADDri = getADDriOpcode(false, EndOffset);
368709467b48Spatrick     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
368809467b48Spatrick         .addReg(FramePtr)
368909467b48Spatrick         .addImm(EndOffset)
369009467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup)
369109467b48Spatrick         ->getOperand(3)
369209467b48Spatrick         .setIsDead();
369309467b48Spatrick     assert(EndOffset >= 0 &&
369409467b48Spatrick            "end of registration object above normal EBP position!");
369509467b48Spatrick   } else if (UsedReg == BasePtr) {
369609467b48Spatrick     // LEA offset(%ebp), %esi
369709467b48Spatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
369809467b48Spatrick                  FramePtr, false, EndOffset)
369909467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
370009467b48Spatrick     // MOV32rm SavedEBPOffset(%esi), %ebp
370109467b48Spatrick     assert(X86FI->getHasSEHFramePtrSave());
370209467b48Spatrick     int Offset =
3703a0747c9fSpatrick         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
3704a0747c9fSpatrick             .getFixed();
370509467b48Spatrick     assert(UsedReg == BasePtr);
370609467b48Spatrick     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
370709467b48Spatrick                  UsedReg, true, Offset)
370809467b48Spatrick         .setMIFlag(MachineInstr::FrameSetup);
370909467b48Spatrick   } else {
371009467b48Spatrick     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
371109467b48Spatrick   }
371209467b48Spatrick   return MBBI;
371309467b48Spatrick }
371409467b48Spatrick 
getInitialCFAOffset(const MachineFunction & MF) const371509467b48Spatrick int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
371609467b48Spatrick   return TRI->getSlotSize();
371709467b48Spatrick }
371809467b48Spatrick 
3719097a140dSpatrick Register
getInitialCFARegister(const MachineFunction & MF) const3720097a140dSpatrick X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const {
372109467b48Spatrick   return TRI->getDwarfRegNum(StackPtr, true);
372209467b48Spatrick }
372309467b48Spatrick 
372409467b48Spatrick namespace {
372509467b48Spatrick // Struct used by orderFrameObjects to help sort the stack objects.
372609467b48Spatrick struct X86FrameSortingObject {
372709467b48Spatrick   bool IsValid = false;         // true if we care about this Object.
372809467b48Spatrick   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
372909467b48Spatrick   unsigned ObjectSize = 0;      // Size of Object in bytes.
3730097a140dSpatrick   Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
373109467b48Spatrick   unsigned ObjectNumUses = 0;   // Object static number of uses.
373209467b48Spatrick };
373309467b48Spatrick 
373409467b48Spatrick // The comparison function we use for std::sort to order our local
373509467b48Spatrick // stack symbols. The current algorithm is to use an estimated
373609467b48Spatrick // "density". This takes into consideration the size and number of
373709467b48Spatrick // uses each object has in order to roughly minimize code size.
373809467b48Spatrick // So, for example, an object of size 16B that is referenced 5 times
373909467b48Spatrick // will get higher priority than 4 4B objects referenced 1 time each.
374009467b48Spatrick // It's not perfect and we may be able to squeeze a few more bytes out of
374109467b48Spatrick // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
374209467b48Spatrick // fringe end can have special consideration, given their size is less
374309467b48Spatrick // important, etc.), but the algorithmic complexity grows too much to be
374409467b48Spatrick // worth the extra gains we get. This gets us pretty close.
374509467b48Spatrick // The final order leaves us with objects with highest priority going
374609467b48Spatrick // at the end of our list.
374709467b48Spatrick struct X86FrameSortingComparator {
operator ()__anonffc28aca0411::X86FrameSortingComparator374809467b48Spatrick   inline bool operator()(const X86FrameSortingObject &A,
3749a0747c9fSpatrick                          const X86FrameSortingObject &B) const {
375009467b48Spatrick     uint64_t DensityAScaled, DensityBScaled;
375109467b48Spatrick 
375209467b48Spatrick     // For consistency in our comparison, all invalid objects are placed
375309467b48Spatrick     // at the end. This also allows us to stop walking when we hit the
375409467b48Spatrick     // first invalid item after it's all sorted.
375509467b48Spatrick     if (!A.IsValid)
375609467b48Spatrick       return false;
375709467b48Spatrick     if (!B.IsValid)
375809467b48Spatrick       return true;
375909467b48Spatrick 
376009467b48Spatrick     // The density is calculated by doing :
376109467b48Spatrick     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
376209467b48Spatrick     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
376309467b48Spatrick     // Since this approach may cause inconsistencies in
376409467b48Spatrick     // the floating point <, >, == comparisons, depending on the floating
376509467b48Spatrick     // point model with which the compiler was built, we're going
376609467b48Spatrick     // to scale both sides by multiplying with
376709467b48Spatrick     // A.ObjectSize * B.ObjectSize. This ends up factoring away
376809467b48Spatrick     // the division and, with it, the need for any floating point
376909467b48Spatrick     // arithmetic.
377009467b48Spatrick     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
377109467b48Spatrick       static_cast<uint64_t>(B.ObjectSize);
377209467b48Spatrick     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
377309467b48Spatrick       static_cast<uint64_t>(A.ObjectSize);
377409467b48Spatrick 
377509467b48Spatrick     // If the two densities are equal, prioritize highest alignment
377609467b48Spatrick     // objects. This allows for similar alignment objects
377709467b48Spatrick     // to be packed together (given the same density).
377809467b48Spatrick     // There's room for improvement here, also, since we can pack
377909467b48Spatrick     // similar alignment (different density) objects next to each
378009467b48Spatrick     // other to save padding. This will also require further
378109467b48Spatrick     // complexity/iterations, and the overall gain isn't worth it,
378209467b48Spatrick     // in general. Something to keep in mind, though.
378309467b48Spatrick     if (DensityAScaled == DensityBScaled)
378409467b48Spatrick       return A.ObjectAlignment < B.ObjectAlignment;
378509467b48Spatrick 
378609467b48Spatrick     return DensityAScaled < DensityBScaled;
378709467b48Spatrick   }
378809467b48Spatrick };
378909467b48Spatrick } // namespace
379009467b48Spatrick 
379109467b48Spatrick // Order the symbols in the local stack.
379209467b48Spatrick // We want to place the local stack objects in some sort of sensible order.
379309467b48Spatrick // The heuristic we use is to try and pack them according to static number
379409467b48Spatrick // of uses and size of object in order to minimize code size.
orderFrameObjects(const MachineFunction & MF,SmallVectorImpl<int> & ObjectsToAllocate) const379509467b48Spatrick void X86FrameLowering::orderFrameObjects(
379609467b48Spatrick     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
379709467b48Spatrick   const MachineFrameInfo &MFI = MF.getFrameInfo();
379809467b48Spatrick 
379909467b48Spatrick   // Don't waste time if there's nothing to do.
380009467b48Spatrick   if (ObjectsToAllocate.empty())
380109467b48Spatrick     return;
380209467b48Spatrick 
380309467b48Spatrick   // Create an array of all MFI objects. We won't need all of these
380409467b48Spatrick   // objects, but we're going to create a full array of them to make
380509467b48Spatrick   // it easier to index into when we're counting "uses" down below.
380609467b48Spatrick   // We want to be able to easily/cheaply access an object by simply
380709467b48Spatrick   // indexing into it, instead of having to search for it every time.
380809467b48Spatrick   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
380909467b48Spatrick 
381009467b48Spatrick   // Walk the objects we care about and mark them as such in our working
381109467b48Spatrick   // struct.
381209467b48Spatrick   for (auto &Obj : ObjectsToAllocate) {
381309467b48Spatrick     SortingObjects[Obj].IsValid = true;
381409467b48Spatrick     SortingObjects[Obj].ObjectIndex = Obj;
3815097a140dSpatrick     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
381609467b48Spatrick     // Set the size.
381709467b48Spatrick     int ObjectSize = MFI.getObjectSize(Obj);
381809467b48Spatrick     if (ObjectSize == 0)
381909467b48Spatrick       // Variable size. Just use 4.
382009467b48Spatrick       SortingObjects[Obj].ObjectSize = 4;
382109467b48Spatrick     else
382209467b48Spatrick       SortingObjects[Obj].ObjectSize = ObjectSize;
382309467b48Spatrick   }
382409467b48Spatrick 
382509467b48Spatrick   // Count the number of uses for each object.
382609467b48Spatrick   for (auto &MBB : MF) {
382709467b48Spatrick     for (auto &MI : MBB) {
382809467b48Spatrick       if (MI.isDebugInstr())
382909467b48Spatrick         continue;
383009467b48Spatrick       for (const MachineOperand &MO : MI.operands()) {
383109467b48Spatrick         // Check to see if it's a local stack symbol.
383209467b48Spatrick         if (!MO.isFI())
383309467b48Spatrick           continue;
383409467b48Spatrick         int Index = MO.getIndex();
383509467b48Spatrick         // Check to see if it falls within our range, and is tagged
383609467b48Spatrick         // to require ordering.
383709467b48Spatrick         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
383809467b48Spatrick             SortingObjects[Index].IsValid)
383909467b48Spatrick           SortingObjects[Index].ObjectNumUses++;
384009467b48Spatrick       }
384109467b48Spatrick     }
384209467b48Spatrick   }
384309467b48Spatrick 
384409467b48Spatrick   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
384509467b48Spatrick   // info).
384609467b48Spatrick   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
384709467b48Spatrick 
384809467b48Spatrick   // Now modify the original list to represent the final order that
384909467b48Spatrick   // we want. The order will depend on whether we're going to access them
385009467b48Spatrick   // from the stack pointer or the frame pointer. For SP, the list should
385109467b48Spatrick   // end up with the END containing objects that we want with smaller offsets.
385209467b48Spatrick   // For FP, it should be flipped.
385309467b48Spatrick   int i = 0;
385409467b48Spatrick   for (auto &Obj : SortingObjects) {
385509467b48Spatrick     // All invalid items are sorted at the end, so it's safe to stop.
385609467b48Spatrick     if (!Obj.IsValid)
385709467b48Spatrick       break;
385809467b48Spatrick     ObjectsToAllocate[i++] = Obj.ObjectIndex;
385909467b48Spatrick   }
386009467b48Spatrick 
386109467b48Spatrick   // Flip it if we're accessing off of the FP.
3862a0747c9fSpatrick   if (!TRI->hasStackRealignment(MF) && hasFP(MF))
386309467b48Spatrick     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
386409467b48Spatrick }
386509467b48Spatrick 
386609467b48Spatrick 
getWinEHParentFrameOffset(const MachineFunction & MF) const386709467b48Spatrick unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
386809467b48Spatrick   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
386909467b48Spatrick   unsigned Offset = 16;
387009467b48Spatrick   // RBP is immediately pushed.
387109467b48Spatrick   Offset += SlotSize;
387209467b48Spatrick   // All callee-saved registers are then pushed.
387309467b48Spatrick   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
387409467b48Spatrick   // Every funclet allocates enough stack space for the largest outgoing call.
387509467b48Spatrick   Offset += getWinEHFuncletFrameSize(MF);
387609467b48Spatrick   return Offset;
387709467b48Spatrick }
387809467b48Spatrick 
processFunctionBeforeFrameFinalized(MachineFunction & MF,RegScavenger * RS) const387909467b48Spatrick void X86FrameLowering::processFunctionBeforeFrameFinalized(
388009467b48Spatrick     MachineFunction &MF, RegScavenger *RS) const {
388109467b48Spatrick   // Mark the function as not having WinCFI. We will set it back to true in
388209467b48Spatrick   // emitPrologue if it gets called and emits CFI.
388309467b48Spatrick   MF.setHasWinCFI(false);
388409467b48Spatrick 
3885a0747c9fSpatrick   // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
3886a0747c9fSpatrick   // aligned. The format doesn't support misaligned stack adjustments.
3887a0747c9fSpatrick   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
3888a0747c9fSpatrick     MF.getFrameInfo().ensureMaxAlignment(Align(SlotSize));
3889a0747c9fSpatrick 
389009467b48Spatrick   // If this function isn't doing Win64-style C++ EH, we don't need to do
389109467b48Spatrick   // anything.
3892a0747c9fSpatrick   if (STI.is64Bit() && MF.hasEHFunclets() &&
3893a0747c9fSpatrick       classifyEHPersonality(MF.getFunction().getPersonalityFn()) ==
3894a0747c9fSpatrick           EHPersonality::MSVC_CXX) {
3895a0747c9fSpatrick     adjustFrameForMsvcCxxEh(MF);
3896a0747c9fSpatrick   }
3897a0747c9fSpatrick }
389809467b48Spatrick 
adjustFrameForMsvcCxxEh(MachineFunction & MF) const3899a0747c9fSpatrick void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
390009467b48Spatrick   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
390109467b48Spatrick   // relative to RSP after the prologue.  Find the offset of the last fixed
390209467b48Spatrick   // object, so that we can allocate a slot immediately following it. If there
390309467b48Spatrick   // were no fixed objects, use offset -SlotSize, which is immediately after the
390409467b48Spatrick   // return address. Fixed objects have negative frame indices.
390509467b48Spatrick   MachineFrameInfo &MFI = MF.getFrameInfo();
390609467b48Spatrick   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
390709467b48Spatrick   int64_t MinFixedObjOffset = -SlotSize;
390809467b48Spatrick   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
390909467b48Spatrick     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
391009467b48Spatrick 
391109467b48Spatrick   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
391209467b48Spatrick     for (WinEHHandlerType &H : TBME.HandlerArray) {
391309467b48Spatrick       int FrameIndex = H.CatchObj.FrameIndex;
391409467b48Spatrick       if (FrameIndex != INT_MAX) {
391509467b48Spatrick         // Ensure alignment.
3916097a140dSpatrick         unsigned Align = MFI.getObjectAlign(FrameIndex).value();
391709467b48Spatrick         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
391809467b48Spatrick         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
391909467b48Spatrick         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
392009467b48Spatrick       }
392109467b48Spatrick     }
392209467b48Spatrick   }
392309467b48Spatrick 
392409467b48Spatrick   // Ensure alignment.
392509467b48Spatrick   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
392609467b48Spatrick   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
392709467b48Spatrick   int UnwindHelpFI =
392809467b48Spatrick       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
392909467b48Spatrick   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
393009467b48Spatrick 
393109467b48Spatrick   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
393209467b48Spatrick   // other frame setup instructions.
393309467b48Spatrick   MachineBasicBlock &MBB = MF.front();
393409467b48Spatrick   auto MBBI = MBB.begin();
393509467b48Spatrick   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
393609467b48Spatrick     ++MBBI;
393709467b48Spatrick 
393809467b48Spatrick   DebugLoc DL = MBB.findDebugLoc(MBBI);
393909467b48Spatrick   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
394009467b48Spatrick                     UnwindHelpFI)
394109467b48Spatrick       .addImm(-2);
394209467b48Spatrick }
394309467b48Spatrick 
getReturnProtector() const3944adae0cfdSpatrick const ReturnProtectorLowering *X86FrameLowering::getReturnProtector() const {
3945adae0cfdSpatrick   return &RPL;
3946adae0cfdSpatrick }
3947adae0cfdSpatrick 
processFunctionBeforeFrameIndicesReplaced(MachineFunction & MF,RegScavenger * RS) const3948097a140dSpatrick void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3949097a140dSpatrick     MachineFunction &MF, RegScavenger *RS) const {
3950097a140dSpatrick   if (STI.is32Bit() && MF.hasEHFunclets())
3951097a140dSpatrick     restoreWinEHStackPointersInParent(MF);
3952097a140dSpatrick }
3953097a140dSpatrick 
restoreWinEHStackPointersInParent(MachineFunction & MF) const3954097a140dSpatrick void X86FrameLowering::restoreWinEHStackPointersInParent(
3955097a140dSpatrick     MachineFunction &MF) const {
3956097a140dSpatrick   // 32-bit functions have to restore stack pointers when control is transferred
3957097a140dSpatrick   // back to the parent function. These blocks are identified as eh pads that
3958097a140dSpatrick   // are not funclet entries.
3959097a140dSpatrick   bool IsSEH = isAsynchronousEHPersonality(
3960097a140dSpatrick       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
3961097a140dSpatrick   for (MachineBasicBlock &MBB : MF) {
3962097a140dSpatrick     bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
3963097a140dSpatrick     if (NeedsRestore)
3964097a140dSpatrick       restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(),
3965097a140dSpatrick                                   /*RestoreSP=*/IsSEH);
3966097a140dSpatrick   }
396709467b48Spatrick }
3968