10b57cec5SDimitry Andric //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file contains the X86 implementation of TargetFrameLowering class. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "X86FrameLowering.h" 1481ad6265SDimitry Andric #include "MCTargetDesc/X86MCTargetDesc.h" 150b57cec5SDimitry Andric #include "X86InstrBuilder.h" 160b57cec5SDimitry Andric #include "X86InstrInfo.h" 170b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h" 180b57cec5SDimitry Andric #include "X86Subtarget.h" 190b57cec5SDimitry Andric #include "X86TargetMachine.h" 205ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h" 2181ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h" 220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h" 230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h" 260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 270b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h" 280b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 2906c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h" 300b57cec5SDimitry Andric #include "llvm/IR/Function.h" 310b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h" 32e8d8bef9SDimitry Andric #include "llvm/MC/MCObjectFileInfo.h" 330b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h" 340b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 3506c3fb27SDimitry Andric #include "llvm/Support/LEB128.h" 360b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h" 370b57cec5SDimitry Andric #include <cstdlib> 380b57cec5SDimitry Andric 395ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-fl" 405ffd83dbSDimitry Andric 415ffd83dbSDimitry Andric STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue"); 425ffd83dbSDimitry Andric STATISTIC(NumFrameExtraProbe, 435ffd83dbSDimitry Andric "Number of extra stack probes generated in prologue"); 44*5f757f3fSDimitry Andric STATISTIC(NumFunctionUsingPush2Pop2, "Number of funtions using push2/pop2"); 455ffd83dbSDimitry Andric 460b57cec5SDimitry Andric using namespace llvm; 470b57cec5SDimitry Andric 480b57cec5SDimitry Andric X86FrameLowering::X86FrameLowering(const X86Subtarget &STI, 498bcb0991SDimitry Andric MaybeAlign StackAlignOverride) 508bcb0991SDimitry Andric : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(), 510b57cec5SDimitry Andric STI.is64Bit() ? -8 : -4), 520b57cec5SDimitry Andric STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) { 530b57cec5SDimitry Andric // Cache a bunch of frame-related predicates for this subtarget. 540b57cec5SDimitry Andric SlotSize = TRI->getSlotSize(); 550b57cec5SDimitry Andric Is64Bit = STI.is64Bit(); 560b57cec5SDimitry Andric IsLP64 = STI.isTarget64BitLP64(); 570b57cec5SDimitry Andric // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. 580b57cec5SDimitry Andric Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64(); 590b57cec5SDimitry Andric StackPtr = TRI->getStackRegister(); 600b57cec5SDimitry Andric } 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 630b57cec5SDimitry Andric return !MF.getFrameInfo().hasVarSizedObjects() && 645ffd83dbSDimitry Andric !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() && 655ffd83dbSDimitry Andric !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall(); 660b57cec5SDimitry Andric } 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 690b57cec5SDimitry Andric /// call frame pseudos can be simplified. Having a FP, as in the default 700b57cec5SDimitry Andric /// implementation, is not sufficient here since we can't always use it. 710b57cec5SDimitry Andric /// Use a more nuanced condition. 72*5f757f3fSDimitry Andric bool X86FrameLowering::canSimplifyCallFramePseudos( 73*5f757f3fSDimitry Andric const MachineFunction &MF) const { 740b57cec5SDimitry Andric return hasReservedCallFrame(MF) || 755ffd83dbSDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() || 76fe6060f1SDimitry Andric (hasFP(MF) && !TRI->hasStackRealignment(MF)) || 770b57cec5SDimitry Andric TRI->hasBasePointer(MF); 780b57cec5SDimitry Andric } 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric // needsFrameIndexResolution - Do we need to perform FI resolution for 810b57cec5SDimitry Andric // this function. Normally, this is required only when the function 820b57cec5SDimitry Andric // has any stack objects. However, FI resolution actually has another job, 830b57cec5SDimitry Andric // not apparent from the title - it resolves callframesetup/destroy 840b57cec5SDimitry Andric // that were not simplified earlier. 850b57cec5SDimitry Andric // So, this is required for x86 functions that have push sequences even 860b57cec5SDimitry Andric // when there are no stack objects. 87*5f757f3fSDimitry Andric bool X86FrameLowering::needsFrameIndexResolution( 88*5f757f3fSDimitry Andric const MachineFunction &MF) const { 890b57cec5SDimitry Andric return MF.getFrameInfo().hasStackObjects() || 900b57cec5SDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences(); 910b57cec5SDimitry Andric } 920b57cec5SDimitry Andric 930b57cec5SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame 940b57cec5SDimitry Andric /// pointer register. This is true if the function has variable sized allocas 950b57cec5SDimitry Andric /// or if frame pointer elimination is disabled. 960b57cec5SDimitry Andric bool X86FrameLowering::hasFP(const MachineFunction &MF) const { 970b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 980b57cec5SDimitry Andric return (MF.getTarget().Options.DisableFramePointerElim(MF) || 99fe6060f1SDimitry Andric TRI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() || 1000b57cec5SDimitry Andric MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() || 1010b57cec5SDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() || 1025ffd83dbSDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() || 1030b57cec5SDimitry Andric MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() || 1040b57cec5SDimitry Andric MFI.hasStackMap() || MFI.hasPatchPoint() || 105d56accc7SDimitry Andric (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment())); 1060b57cec5SDimitry Andric } 1070b57cec5SDimitry Andric 10806c3fb27SDimitry Andric static unsigned getSUBriOpcode(bool IsLP64) { 10906c3fb27SDimitry Andric return IsLP64 ? X86::SUB64ri32 : X86::SUB32ri; 1100b57cec5SDimitry Andric } 1110b57cec5SDimitry Andric 11206c3fb27SDimitry Andric static unsigned getADDriOpcode(bool IsLP64) { 11306c3fb27SDimitry Andric return IsLP64 ? X86::ADD64ri32 : X86::ADD32ri; 1140b57cec5SDimitry Andric } 1150b57cec5SDimitry Andric 116480093f4SDimitry Andric static unsigned getSUBrrOpcode(bool IsLP64) { 117480093f4SDimitry Andric return IsLP64 ? X86::SUB64rr : X86::SUB32rr; 1180b57cec5SDimitry Andric } 1190b57cec5SDimitry Andric 120480093f4SDimitry Andric static unsigned getADDrrOpcode(bool IsLP64) { 121480093f4SDimitry Andric return IsLP64 ? X86::ADD64rr : X86::ADD32rr; 1220b57cec5SDimitry Andric } 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) { 12506c3fb27SDimitry Andric return IsLP64 ? X86::AND64ri32 : X86::AND32ri; 1260b57cec5SDimitry Andric } 1270b57cec5SDimitry Andric 128480093f4SDimitry Andric static unsigned getLEArOpcode(bool IsLP64) { 1290b57cec5SDimitry Andric return IsLP64 ? X86::LEA64r : X86::LEA32r; 1300b57cec5SDimitry Andric } 1310b57cec5SDimitry Andric 13204eeddc0SDimitry Andric static unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm) { 13304eeddc0SDimitry Andric if (Use64BitReg) { 13404eeddc0SDimitry Andric if (isUInt<32>(Imm)) 13504eeddc0SDimitry Andric return X86::MOV32ri64; 13604eeddc0SDimitry Andric if (isInt<32>(Imm)) 13704eeddc0SDimitry Andric return X86::MOV64ri32; 13804eeddc0SDimitry Andric return X86::MOV64ri; 13904eeddc0SDimitry Andric } 14004eeddc0SDimitry Andric return X86::MOV32ri; 14104eeddc0SDimitry Andric } 14204eeddc0SDimitry Andric 143*5f757f3fSDimitry Andric // Push-Pop Acceleration (PPX) hint is used to indicate that the POP reads the 144*5f757f3fSDimitry Andric // value written by the PUSH from the stack. The processor tracks these marked 145*5f757f3fSDimitry Andric // instructions internally and fast-forwards register data between matching PUSH 146*5f757f3fSDimitry Andric // and POP instructions, without going through memory or through the training 147*5f757f3fSDimitry Andric // loop of the Fast Store Forwarding Predictor (FSFP). Instead, a more efficient 148*5f757f3fSDimitry Andric // memory-renaming optimization can be used. 149*5f757f3fSDimitry Andric // 150*5f757f3fSDimitry Andric // The PPX hint is purely a performance hint. Instructions with this hint have 151*5f757f3fSDimitry Andric // the same functional semantics as those without. PPX hints set by the 152*5f757f3fSDimitry Andric // compiler that violate the balancing rule may turn off the PPX optimization, 153*5f757f3fSDimitry Andric // but they will not affect program semantics. 154*5f757f3fSDimitry Andric // 155*5f757f3fSDimitry Andric // Hence, PPX is used for balanced spill/reloads (Exceptions and setjmp/longjmp 156*5f757f3fSDimitry Andric // are not considered). 157*5f757f3fSDimitry Andric // 158*5f757f3fSDimitry Andric // PUSH2 and POP2 are instructions for (respectively) pushing/popping 2 159*5f757f3fSDimitry Andric // GPRs at a time to/from the stack. 160*5f757f3fSDimitry Andric static unsigned getPUSHOpcode(const X86Subtarget &ST) { 161*5f757f3fSDimitry Andric return ST.is64Bit() ? (ST.hasPPX() ? X86::PUSHP64r : X86::PUSH64r) 162*5f757f3fSDimitry Andric : X86::PUSH32r; 163*5f757f3fSDimitry Andric } 164*5f757f3fSDimitry Andric static unsigned getPOPOpcode(const X86Subtarget &ST) { 165*5f757f3fSDimitry Andric return ST.is64Bit() ? (ST.hasPPX() ? X86::POPP64r : X86::POP64r) 166*5f757f3fSDimitry Andric : X86::POP32r; 167*5f757f3fSDimitry Andric } 168*5f757f3fSDimitry Andric static unsigned getPUSH2Opcode(const X86Subtarget &ST) { 169*5f757f3fSDimitry Andric return ST.hasPPX() ? X86::PUSH2P : X86::PUSH2; 170*5f757f3fSDimitry Andric } 171*5f757f3fSDimitry Andric static unsigned getPOP2Opcode(const X86Subtarget &ST) { 172*5f757f3fSDimitry Andric return ST.hasPPX() ? X86::POP2P : X86::POP2; 173*5f757f3fSDimitry Andric } 174*5f757f3fSDimitry Andric 1750b57cec5SDimitry Andric static bool isEAXLiveIn(MachineBasicBlock &MBB) { 1760b57cec5SDimitry Andric for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) { 1770b57cec5SDimitry Andric unsigned Reg = RegMask.PhysReg; 1780b57cec5SDimitry Andric 1790b57cec5SDimitry Andric if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX || 1800b57cec5SDimitry Andric Reg == X86::AH || Reg == X86::AL) 1810b57cec5SDimitry Andric return true; 1820b57cec5SDimitry Andric } 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric return false; 1850b57cec5SDimitry Andric } 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric /// Check if the flags need to be preserved before the terminators. 1880b57cec5SDimitry Andric /// This would be the case, if the eflags is live-in of the region 1890b57cec5SDimitry Andric /// composed by the terminators or live-out of that region, without 1900b57cec5SDimitry Andric /// being defined by a terminator. 1910b57cec5SDimitry Andric static bool 1920b57cec5SDimitry Andric flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) { 1930b57cec5SDimitry Andric for (const MachineInstr &MI : MBB.terminators()) { 1940b57cec5SDimitry Andric bool BreakNext = false; 1950b57cec5SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1960b57cec5SDimitry Andric if (!MO.isReg()) 1970b57cec5SDimitry Andric continue; 1988bcb0991SDimitry Andric Register Reg = MO.getReg(); 1990b57cec5SDimitry Andric if (Reg != X86::EFLAGS) 2000b57cec5SDimitry Andric continue; 2010b57cec5SDimitry Andric 2020b57cec5SDimitry Andric // This terminator needs an eflags that is not defined 2030b57cec5SDimitry Andric // by a previous another terminator: 2040b57cec5SDimitry Andric // EFLAGS is live-in of the region composed by the terminators. 2050b57cec5SDimitry Andric if (!MO.isDef()) 2060b57cec5SDimitry Andric return true; 2070b57cec5SDimitry Andric // This terminator defines the eflags, i.e., we don't need to preserve it. 2080b57cec5SDimitry Andric // However, we still need to check this specific terminator does not 2090b57cec5SDimitry Andric // read a live-in value. 2100b57cec5SDimitry Andric BreakNext = true; 2110b57cec5SDimitry Andric } 2120b57cec5SDimitry Andric // We found a definition of the eflags, no need to preserve them. 2130b57cec5SDimitry Andric if (BreakNext) 2140b57cec5SDimitry Andric return false; 2150b57cec5SDimitry Andric } 2160b57cec5SDimitry Andric 2170b57cec5SDimitry Andric // None of the terminators use or define the eflags. 2180b57cec5SDimitry Andric // Check if they are live-out, that would imply we need to preserve them. 2190b57cec5SDimitry Andric for (const MachineBasicBlock *Succ : MBB.successors()) 2200b57cec5SDimitry Andric if (Succ->isLiveIn(X86::EFLAGS)) 2210b57cec5SDimitry Andric return true; 2220b57cec5SDimitry Andric 2230b57cec5SDimitry Andric return false; 2240b57cec5SDimitry Andric } 2250b57cec5SDimitry Andric 2260b57cec5SDimitry Andric /// emitSPUpdate - Emit a series of instructions to increment / decrement the 2270b57cec5SDimitry Andric /// stack pointer by a constant value. 2280b57cec5SDimitry Andric void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB, 2290b57cec5SDimitry Andric MachineBasicBlock::iterator &MBBI, 230*5f757f3fSDimitry Andric const DebugLoc &DL, int64_t NumBytes, 231*5f757f3fSDimitry Andric bool InEpilogue) const { 2320b57cec5SDimitry Andric bool isSub = NumBytes < 0; 2330b57cec5SDimitry Andric uint64_t Offset = isSub ? -NumBytes : NumBytes; 2340b57cec5SDimitry Andric MachineInstr::MIFlag Flag = 2350b57cec5SDimitry Andric isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy; 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric uint64_t Chunk = (1LL << 31) - 1; 2380b57cec5SDimitry Andric 2395ffd83dbSDimitry Andric MachineFunction &MF = *MBB.getParent(); 2405ffd83dbSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 2415ffd83dbSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 2425ffd83dbSDimitry Andric const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF); 2435ffd83dbSDimitry Andric 2445ffd83dbSDimitry Andric // It's ok to not take into account large chunks when probing, as the 2455ffd83dbSDimitry Andric // allocation is split in smaller chunks anyway. 2465ffd83dbSDimitry Andric if (EmitInlineStackProbe && !InEpilogue) { 2475ffd83dbSDimitry Andric 2485ffd83dbSDimitry Andric // This pseudo-instruction is going to be expanded, potentially using a 2495ffd83dbSDimitry Andric // loop, by inlineStackProbe(). 2505ffd83dbSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset); 2515ffd83dbSDimitry Andric return; 2525ffd83dbSDimitry Andric } else if (Offset > Chunk) { 2530b57cec5SDimitry Andric // Rather than emit a long series of instructions for large offsets, 2540b57cec5SDimitry Andric // load the offset into a register and do one sub/add 2550b57cec5SDimitry Andric unsigned Reg = 0; 2560b57cec5SDimitry Andric unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX); 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric if (isSub && !isEAXLiveIn(MBB)) 2590b57cec5SDimitry Andric Reg = Rax; 2600b57cec5SDimitry Andric else 261e8d8bef9SDimitry Andric Reg = TRI->findDeadCallerSavedReg(MBB, MBBI); 2620b57cec5SDimitry Andric 2630b57cec5SDimitry Andric unsigned AddSubRROpc = 2640b57cec5SDimitry Andric isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit); 2650b57cec5SDimitry Andric if (Reg) { 26604eeddc0SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Reg) 2670b57cec5SDimitry Andric .addImm(Offset) 2680b57cec5SDimitry Andric .setMIFlag(Flag); 2690b57cec5SDimitry Andric MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr) 2700b57cec5SDimitry Andric .addReg(StackPtr) 2710b57cec5SDimitry Andric .addReg(Reg); 2720b57cec5SDimitry Andric MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 2730b57cec5SDimitry Andric return; 2740b57cec5SDimitry Andric } else if (Offset > 8 * Chunk) { 2750b57cec5SDimitry Andric // If we would need more than 8 add or sub instructions (a >16GB stack 2760b57cec5SDimitry Andric // frame), it's worth spilling RAX to materialize this immediate. 2770b57cec5SDimitry Andric // pushq %rax 2780b57cec5SDimitry Andric // movabsq +-$Offset+-SlotSize, %rax 2790b57cec5SDimitry Andric // addq %rsp, %rax 2800b57cec5SDimitry Andric // xchg %rax, (%rsp) 2810b57cec5SDimitry Andric // movq (%rsp), %rsp 2820b57cec5SDimitry Andric assert(Is64Bit && "can't have 32-bit 16GB stack frame"); 2830b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 2840b57cec5SDimitry Andric .addReg(Rax, RegState::Kill) 2850b57cec5SDimitry Andric .setMIFlag(Flag); 2860b57cec5SDimitry Andric // Subtract is not commutative, so negate the offset and always use add. 2870b57cec5SDimitry Andric // Subtract 8 less and add 8 more to account for the PUSH we just did. 2880b57cec5SDimitry Andric if (isSub) 2890b57cec5SDimitry Andric Offset = -(Offset - SlotSize); 2900b57cec5SDimitry Andric else 2910b57cec5SDimitry Andric Offset = Offset + SlotSize; 29204eeddc0SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Rax) 2930b57cec5SDimitry Andric .addImm(Offset) 2940b57cec5SDimitry Andric .setMIFlag(Flag); 2950b57cec5SDimitry Andric MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax) 2960b57cec5SDimitry Andric .addReg(Rax) 2970b57cec5SDimitry Andric .addReg(StackPtr); 2980b57cec5SDimitry Andric MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 2990b57cec5SDimitry Andric // Exchange the new SP in RAX with the top of the stack. 3000b57cec5SDimitry Andric addRegOffset( 3010b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax), 3020b57cec5SDimitry Andric StackPtr, false, 0); 3030b57cec5SDimitry Andric // Load new SP from the top of the stack into RSP. 3040b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr), 3050b57cec5SDimitry Andric StackPtr, false, 0); 3060b57cec5SDimitry Andric return; 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric } 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric while (Offset) { 3110b57cec5SDimitry Andric uint64_t ThisVal = std::min(Offset, Chunk); 3120b57cec5SDimitry Andric if (ThisVal == SlotSize) { 3130b57cec5SDimitry Andric // Use push / pop for slot sized adjustments as a size optimization. We 3140b57cec5SDimitry Andric // need to find a dead register when using pop. 315*5f757f3fSDimitry Andric unsigned Reg = isSub ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX) 316e8d8bef9SDimitry Andric : TRI->findDeadCallerSavedReg(MBB, MBBI); 3170b57cec5SDimitry Andric if (Reg) { 318*5f757f3fSDimitry Andric unsigned Opc = isSub ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r) 3190b57cec5SDimitry Andric : (Is64Bit ? X86::POP64r : X86::POP32r); 3200b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Opc)) 3210b57cec5SDimitry Andric .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub)) 3220b57cec5SDimitry Andric .setMIFlag(Flag); 3230b57cec5SDimitry Andric Offset -= ThisVal; 3240b57cec5SDimitry Andric continue; 3250b57cec5SDimitry Andric } 3260b57cec5SDimitry Andric } 3270b57cec5SDimitry Andric 3280b57cec5SDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue) 3290b57cec5SDimitry Andric .setMIFlag(Flag); 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric Offset -= ThisVal; 3320b57cec5SDimitry Andric } 3330b57cec5SDimitry Andric } 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric MachineInstrBuilder X86FrameLowering::BuildStackAdjustment( 3360b57cec5SDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 3370b57cec5SDimitry Andric const DebugLoc &DL, int64_t Offset, bool InEpilogue) const { 3380b57cec5SDimitry Andric assert(Offset != 0 && "zero offset stack adjustment requested"); 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue 3410b57cec5SDimitry Andric // is tricky. 3420b57cec5SDimitry Andric bool UseLEA; 3430b57cec5SDimitry Andric if (!InEpilogue) { 3440b57cec5SDimitry Andric // Check if inserting the prologue at the beginning 3450b57cec5SDimitry Andric // of MBB would require to use LEA operations. 3460b57cec5SDimitry Andric // We need to use LEA operations if EFLAGS is live in, because 3470b57cec5SDimitry Andric // it means an instruction will read it before it gets defined. 3480b57cec5SDimitry Andric UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS); 3490b57cec5SDimitry Andric } else { 3500b57cec5SDimitry Andric // If we can use LEA for SP but we shouldn't, check that none 3510b57cec5SDimitry Andric // of the terminators uses the eflags. Otherwise we will insert 3520b57cec5SDimitry Andric // a ADD that will redefine the eflags and break the condition. 3530b57cec5SDimitry Andric // Alternatively, we could move the ADD, but this may not be possible 3540b57cec5SDimitry Andric // and is an optimization anyway. 3550b57cec5SDimitry Andric UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent()); 3560b57cec5SDimitry Andric if (UseLEA && !STI.useLeaForSP()) 3570b57cec5SDimitry Andric UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB); 3580b57cec5SDimitry Andric // If that assert breaks, that means we do not do the right thing 3590b57cec5SDimitry Andric // in canUseAsEpilogue. 3600b57cec5SDimitry Andric assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) && 3610b57cec5SDimitry Andric "We shouldn't have allowed this insertion point"); 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric MachineInstrBuilder MI; 3650b57cec5SDimitry Andric if (UseLEA) { 3660b57cec5SDimitry Andric MI = addRegOffset(BuildMI(MBB, MBBI, DL, 3670b57cec5SDimitry Andric TII.get(getLEArOpcode(Uses64BitFramePtr)), 3680b57cec5SDimitry Andric StackPtr), 3690b57cec5SDimitry Andric StackPtr, false, Offset); 3700b57cec5SDimitry Andric } else { 3710b57cec5SDimitry Andric bool IsSub = Offset < 0; 3720b57cec5SDimitry Andric uint64_t AbsOffset = IsSub ? -Offset : Offset; 37306c3fb27SDimitry Andric const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr) 37406c3fb27SDimitry Andric : getADDriOpcode(Uses64BitFramePtr); 3750b57cec5SDimitry Andric MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr) 3760b57cec5SDimitry Andric .addReg(StackPtr) 3770b57cec5SDimitry Andric .addImm(AbsOffset); 3780b57cec5SDimitry Andric MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 3790b57cec5SDimitry Andric } 3800b57cec5SDimitry Andric return MI; 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB, 3840b57cec5SDimitry Andric MachineBasicBlock::iterator &MBBI, 3850b57cec5SDimitry Andric bool doMergeWithPrevious) const { 3860b57cec5SDimitry Andric if ((doMergeWithPrevious && MBBI == MBB.begin()) || 3870b57cec5SDimitry Andric (!doMergeWithPrevious && MBBI == MBB.end())) 3880b57cec5SDimitry Andric return 0; 3890b57cec5SDimitry Andric 3900b57cec5SDimitry Andric MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI; 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric PI = skipDebugInstructionsBackward(PI, MBB.begin()); 3930b57cec5SDimitry Andric // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI 3940b57cec5SDimitry Andric // instruction, and that there are no DBG_VALUE or other instructions between 3950b57cec5SDimitry Andric // ADD/SUB/LEA and its corresponding CFI instruction. 3960b57cec5SDimitry Andric /* TODO: Add support for the case where there are multiple CFI instructions 3970b57cec5SDimitry Andric below the ADD/SUB/LEA, e.g.: 3980b57cec5SDimitry Andric ... 3990b57cec5SDimitry Andric add 4000b57cec5SDimitry Andric cfi_def_cfa_offset 4010b57cec5SDimitry Andric cfi_offset 4020b57cec5SDimitry Andric ... 4030b57cec5SDimitry Andric */ 4040b57cec5SDimitry Andric if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction()) 4050b57cec5SDimitry Andric PI = std::prev(PI); 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric unsigned Opc = PI->getOpcode(); 4080b57cec5SDimitry Andric int Offset = 0; 4090b57cec5SDimitry Andric 41006c3fb27SDimitry Andric if ((Opc == X86::ADD64ri32 || Opc == X86::ADD32ri) && 4110b57cec5SDimitry Andric PI->getOperand(0).getReg() == StackPtr) { 4120b57cec5SDimitry Andric assert(PI->getOperand(1).getReg() == StackPtr); 4130b57cec5SDimitry Andric Offset = PI->getOperand(2).getImm(); 4140b57cec5SDimitry Andric } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) && 4150b57cec5SDimitry Andric PI->getOperand(0).getReg() == StackPtr && 4160b57cec5SDimitry Andric PI->getOperand(1).getReg() == StackPtr && 4170b57cec5SDimitry Andric PI->getOperand(2).getImm() == 1 && 4180b57cec5SDimitry Andric PI->getOperand(3).getReg() == X86::NoRegister && 4190b57cec5SDimitry Andric PI->getOperand(5).getReg() == X86::NoRegister) { 4200b57cec5SDimitry Andric // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg. 4210b57cec5SDimitry Andric Offset = PI->getOperand(4).getImm(); 42206c3fb27SDimitry Andric } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB32ri) && 4230b57cec5SDimitry Andric PI->getOperand(0).getReg() == StackPtr) { 4240b57cec5SDimitry Andric assert(PI->getOperand(1).getReg() == StackPtr); 4250b57cec5SDimitry Andric Offset = -PI->getOperand(2).getImm(); 4260b57cec5SDimitry Andric } else 4270b57cec5SDimitry Andric return 0; 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric PI = MBB.erase(PI); 430fe6060f1SDimitry Andric if (PI != MBB.end() && PI->isCFIInstruction()) { 431fe6060f1SDimitry Andric auto CIs = MBB.getParent()->getFrameInstructions(); 432fe6060f1SDimitry Andric MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()]; 433fe6060f1SDimitry Andric if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset || 434fe6060f1SDimitry Andric CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset) 435fe6060f1SDimitry Andric PI = MBB.erase(PI); 436fe6060f1SDimitry Andric } 4370b57cec5SDimitry Andric if (!doMergeWithPrevious) 4380b57cec5SDimitry Andric MBBI = skipDebugInstructionsForward(PI, MBB.end()); 4390b57cec5SDimitry Andric 4400b57cec5SDimitry Andric return Offset; 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB, 4440b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI, 4450b57cec5SDimitry Andric const DebugLoc &DL, 44681ad6265SDimitry Andric const MCCFIInstruction &CFIInst, 44781ad6265SDimitry Andric MachineInstr::MIFlag Flag) const { 4480b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 4490b57cec5SDimitry Andric unsigned CFIIndex = MF.addFrameInst(CFIInst); 45006c3fb27SDimitry Andric 45106c3fb27SDimitry Andric if (CFIInst.getOperation() == MCCFIInstruction::OpAdjustCfaOffset) 45206c3fb27SDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true); 45306c3fb27SDimitry Andric 4540b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 45581ad6265SDimitry Andric .addCFIIndex(CFIIndex) 45681ad6265SDimitry Andric .setMIFlag(Flag); 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4595ffd83dbSDimitry Andric /// Emits Dwarf Info specifying offsets of callee saved registers and 4605ffd83dbSDimitry Andric /// frame pointer. This is called only when basic block sections are enabled. 46104eeddc0SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA( 4625ffd83dbSDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 4635ffd83dbSDimitry Andric MachineFunction &MF = *MBB.getParent(); 4645ffd83dbSDimitry Andric if (!hasFP(MF)) { 4655ffd83dbSDimitry Andric emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true); 4665ffd83dbSDimitry Andric return; 4675ffd83dbSDimitry Andric } 4685ffd83dbSDimitry Andric const MachineModuleInfo &MMI = MF.getMMI(); 4695ffd83dbSDimitry Andric const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo(); 470e8d8bef9SDimitry Andric const Register FramePtr = TRI->getFrameRegister(MF); 471e8d8bef9SDimitry Andric const Register MachineFramePtr = 472e8d8bef9SDimitry Andric STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64)) 4735ffd83dbSDimitry Andric : FramePtr; 4745ffd83dbSDimitry Andric unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true); 4755ffd83dbSDimitry Andric // Offset = space for return address + size of the frame pointer itself. 4765ffd83dbSDimitry Andric unsigned Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4); 4775ffd83dbSDimitry Andric BuildCFI(MBB, MBBI, DebugLoc{}, 4785ffd83dbSDimitry Andric MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset)); 4795ffd83dbSDimitry Andric emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true); 4805ffd83dbSDimitry Andric } 4815ffd83dbSDimitry Andric 4820b57cec5SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMoves( 4830b57cec5SDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 4845ffd83dbSDimitry Andric const DebugLoc &DL, bool IsPrologue) const { 4850b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 4860b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 4870b57cec5SDimitry Andric MachineModuleInfo &MMI = MF.getMMI(); 4880b57cec5SDimitry Andric const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo(); 48906c3fb27SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 4900b57cec5SDimitry Andric 4910b57cec5SDimitry Andric // Add callee saved registers to move list. 4920b57cec5SDimitry Andric const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 4930b57cec5SDimitry Andric 4940b57cec5SDimitry Andric // Calculate offsets. 4954824e7fdSDimitry Andric for (const CalleeSavedInfo &I : CSI) { 4964824e7fdSDimitry Andric int64_t Offset = MFI.getObjectOffset(I.getFrameIdx()); 49704eeddc0SDimitry Andric Register Reg = I.getReg(); 4980b57cec5SDimitry Andric unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 4995ffd83dbSDimitry Andric 5005ffd83dbSDimitry Andric if (IsPrologue) { 50106c3fb27SDimitry Andric if (X86FI->getStackPtrSaveMI()) { 50206c3fb27SDimitry Andric // +2*SlotSize because there is return address and ebp at the bottom 50306c3fb27SDimitry Andric // of the stack. 50406c3fb27SDimitry Andric // | retaddr | 50506c3fb27SDimitry Andric // | ebp | 50606c3fb27SDimitry Andric // | |<--ebp 50706c3fb27SDimitry Andric Offset += 2 * SlotSize; 50806c3fb27SDimitry Andric SmallString<64> CfaExpr; 50906c3fb27SDimitry Andric CfaExpr.push_back(dwarf::DW_CFA_expression); 51006c3fb27SDimitry Andric uint8_t buffer[16]; 51106c3fb27SDimitry Andric CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer)); 51206c3fb27SDimitry Andric CfaExpr.push_back(2); 51306c3fb27SDimitry Andric Register FramePtr = TRI->getFrameRegister(MF); 51406c3fb27SDimitry Andric const Register MachineFramePtr = 51506c3fb27SDimitry Andric STI.isTarget64BitILP32() 51606c3fb27SDimitry Andric ? Register(getX86SubSuperRegister(FramePtr, 64)) 51706c3fb27SDimitry Andric : FramePtr; 51806c3fb27SDimitry Andric unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true); 51906c3fb27SDimitry Andric CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr)); 52006c3fb27SDimitry Andric CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer)); 52106c3fb27SDimitry Andric BuildCFI(MBB, MBBI, DL, 52206c3fb27SDimitry Andric MCCFIInstruction::createEscape(nullptr, CfaExpr.str()), 52306c3fb27SDimitry Andric MachineInstr::FrameSetup); 52406c3fb27SDimitry Andric } else { 5250b57cec5SDimitry Andric BuildCFI(MBB, MBBI, DL, 5260b57cec5SDimitry Andric MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 52706c3fb27SDimitry Andric } 5285ffd83dbSDimitry Andric } else { 5295ffd83dbSDimitry Andric BuildCFI(MBB, MBBI, DL, 5305ffd83dbSDimitry Andric MCCFIInstruction::createRestore(nullptr, DwarfReg)); 5315ffd83dbSDimitry Andric } 5320b57cec5SDimitry Andric } 53306c3fb27SDimitry Andric if (auto *MI = X86FI->getStackPtrSaveMI()) { 53406c3fb27SDimitry Andric int FI = MI->getOperand(1).getIndex(); 53506c3fb27SDimitry Andric int64_t Offset = MFI.getObjectOffset(FI) + 2 * SlotSize; 53606c3fb27SDimitry Andric SmallString<64> CfaExpr; 53706c3fb27SDimitry Andric Register FramePtr = TRI->getFrameRegister(MF); 53806c3fb27SDimitry Andric const Register MachineFramePtr = 53906c3fb27SDimitry Andric STI.isTarget64BitILP32() 54006c3fb27SDimitry Andric ? Register(getX86SubSuperRegister(FramePtr, 64)) 54106c3fb27SDimitry Andric : FramePtr; 54206c3fb27SDimitry Andric unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true); 54306c3fb27SDimitry Andric CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr)); 54406c3fb27SDimitry Andric uint8_t buffer[16]; 54506c3fb27SDimitry Andric CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer)); 54606c3fb27SDimitry Andric CfaExpr.push_back(dwarf::DW_OP_deref); 54706c3fb27SDimitry Andric 54806c3fb27SDimitry Andric SmallString<64> DefCfaExpr; 54906c3fb27SDimitry Andric DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression); 55006c3fb27SDimitry Andric DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer)); 55106c3fb27SDimitry Andric DefCfaExpr.append(CfaExpr.str()); 55206c3fb27SDimitry Andric // DW_CFA_def_cfa_expression: DW_OP_breg5 offset, DW_OP_deref 55306c3fb27SDimitry Andric BuildCFI(MBB, MBBI, DL, 55406c3fb27SDimitry Andric MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()), 55506c3fb27SDimitry Andric MachineInstr::FrameSetup); 55606c3fb27SDimitry Andric } 5570b57cec5SDimitry Andric } 5580b57cec5SDimitry Andric 55981ad6265SDimitry Andric void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero, 56081ad6265SDimitry Andric MachineBasicBlock &MBB) const { 56181ad6265SDimitry Andric const MachineFunction &MF = *MBB.getParent(); 56281ad6265SDimitry Andric 56381ad6265SDimitry Andric // Insertion point. 56481ad6265SDimitry Andric MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); 56581ad6265SDimitry Andric 56681ad6265SDimitry Andric // Fake a debug loc. 56781ad6265SDimitry Andric DebugLoc DL; 56881ad6265SDimitry Andric if (MBBI != MBB.end()) 56981ad6265SDimitry Andric DL = MBBI->getDebugLoc(); 57081ad6265SDimitry Andric 57181ad6265SDimitry Andric // Zero out FP stack if referenced. Do this outside of the loop below so that 57281ad6265SDimitry Andric // it's done only once. 57381ad6265SDimitry Andric const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>(); 57481ad6265SDimitry Andric for (MCRegister Reg : RegsToZero.set_bits()) { 57581ad6265SDimitry Andric if (!X86::RFP80RegClass.contains(Reg)) 57681ad6265SDimitry Andric continue; 57781ad6265SDimitry Andric 57881ad6265SDimitry Andric unsigned NumFPRegs = ST.is64Bit() ? 8 : 7; 57981ad6265SDimitry Andric for (unsigned i = 0; i != NumFPRegs; ++i) 58081ad6265SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0)); 58181ad6265SDimitry Andric 58281ad6265SDimitry Andric for (unsigned i = 0; i != NumFPRegs; ++i) 58381ad6265SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0); 58481ad6265SDimitry Andric break; 58581ad6265SDimitry Andric } 58681ad6265SDimitry Andric 58781ad6265SDimitry Andric // For GPRs, we only care to clear out the 32-bit register. 58881ad6265SDimitry Andric BitVector GPRsToZero(TRI->getNumRegs()); 58981ad6265SDimitry Andric for (MCRegister Reg : RegsToZero.set_bits()) 59081ad6265SDimitry Andric if (TRI->isGeneralPurposeRegister(MF, Reg)) { 59106c3fb27SDimitry Andric GPRsToZero.set(getX86SubSuperRegister(Reg, 32)); 59281ad6265SDimitry Andric RegsToZero.reset(Reg); 59381ad6265SDimitry Andric } 59481ad6265SDimitry Andric 595*5f757f3fSDimitry Andric // Zero out the GPRs first. 59681ad6265SDimitry Andric for (MCRegister Reg : GPRsToZero.set_bits()) 597*5f757f3fSDimitry Andric TII.buildClearRegister(Reg, MBB, MBBI, DL); 59881ad6265SDimitry Andric 599*5f757f3fSDimitry Andric // Zero out the remaining registers. 600*5f757f3fSDimitry Andric for (MCRegister Reg : RegsToZero.set_bits()) 601*5f757f3fSDimitry Andric TII.buildClearRegister(Reg, MBB, MBBI, DL); 60281ad6265SDimitry Andric } 60381ad6265SDimitry Andric 6044824e7fdSDimitry Andric void X86FrameLowering::emitStackProbe( 6054824e7fdSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 6064824e7fdSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog, 607bdd1243dSDimitry Andric std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const { 6080b57cec5SDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 6090b57cec5SDimitry Andric if (STI.isTargetWindowsCoreCLR()) { 6100b57cec5SDimitry Andric if (InProlog) { 6115ffd83dbSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)) 6125ffd83dbSDimitry Andric .addImm(0 /* no explicit stack size */); 6130b57cec5SDimitry Andric } else { 6140b57cec5SDimitry Andric emitStackProbeInline(MF, MBB, MBBI, DL, false); 6150b57cec5SDimitry Andric } 6160b57cec5SDimitry Andric } else { 6174824e7fdSDimitry Andric emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum); 6180b57cec5SDimitry Andric } 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric 6214824e7fdSDimitry Andric bool X86FrameLowering::stackProbeFunctionModifiesSP() const { 6224824e7fdSDimitry Andric return STI.isOSWindows() && !STI.isTargetWin64(); 6234824e7fdSDimitry Andric } 6244824e7fdSDimitry Andric 6250b57cec5SDimitry Andric void X86FrameLowering::inlineStackProbe(MachineFunction &MF, 6260b57cec5SDimitry Andric MachineBasicBlock &PrologMBB) const { 6275ffd83dbSDimitry Andric auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) { 6285ffd83dbSDimitry Andric return MI.getOpcode() == X86::STACKALLOC_W_PROBING; 6295ffd83dbSDimitry Andric }); 6305ffd83dbSDimitry Andric if (Where != PrologMBB.end()) { 6315ffd83dbSDimitry Andric DebugLoc DL = PrologMBB.findDebugLoc(Where); 6325ffd83dbSDimitry Andric emitStackProbeInline(MF, PrologMBB, Where, DL, true); 6335ffd83dbSDimitry Andric Where->eraseFromParent(); 6340b57cec5SDimitry Andric } 6350b57cec5SDimitry Andric } 6360b57cec5SDimitry Andric 6370b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInline(MachineFunction &MF, 6380b57cec5SDimitry Andric MachineBasicBlock &MBB, 6390b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI, 6400b57cec5SDimitry Andric const DebugLoc &DL, 6410b57cec5SDimitry Andric bool InProlog) const { 6420b57cec5SDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 6435ffd83dbSDimitry Andric if (STI.isTargetWindowsCoreCLR() && STI.is64Bit()) 6445ffd83dbSDimitry Andric emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog); 6455ffd83dbSDimitry Andric else 6465ffd83dbSDimitry Andric emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog); 6475ffd83dbSDimitry Andric } 6485ffd83dbSDimitry Andric 6495ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGeneric( 6505ffd83dbSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 6515ffd83dbSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const { 6525ffd83dbSDimitry Andric MachineInstr &AllocWithProbe = *MBBI; 6535ffd83dbSDimitry Andric uint64_t Offset = AllocWithProbe.getOperand(0).getImm(); 6545ffd83dbSDimitry Andric 6555ffd83dbSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 6565ffd83dbSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 6575ffd83dbSDimitry Andric assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) && 6585ffd83dbSDimitry Andric "different expansion expected for CoreCLR 64 bit"); 6595ffd83dbSDimitry Andric 6605ffd83dbSDimitry Andric const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 6615ffd83dbSDimitry Andric uint64_t ProbeChunk = StackProbeSize * 8; 6625ffd83dbSDimitry Andric 663eaeb601bSDimitry Andric uint64_t MaxAlign = 664fe6060f1SDimitry Andric TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0; 665eaeb601bSDimitry Andric 6665ffd83dbSDimitry Andric // Synthesize a loop or unroll it, depending on the number of iterations. 667eaeb601bSDimitry Andric // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left 668eaeb601bSDimitry Andric // between the unaligned rsp and current rsp. 6695ffd83dbSDimitry Andric if (Offset > ProbeChunk) { 670eaeb601bSDimitry Andric emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset, 671eaeb601bSDimitry Andric MaxAlign % StackProbeSize); 6725ffd83dbSDimitry Andric } else { 673eaeb601bSDimitry Andric emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset, 674eaeb601bSDimitry Andric MaxAlign % StackProbeSize); 6755ffd83dbSDimitry Andric } 6765ffd83dbSDimitry Andric } 6775ffd83dbSDimitry Andric 6785ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericBlock( 6795ffd83dbSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 680eaeb601bSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset, 681eaeb601bSDimitry Andric uint64_t AlignOffset) const { 6825ffd83dbSDimitry Andric 683fe6060f1SDimitry Andric const bool NeedsDwarfCFI = needsDwarfCFI(MF); 684fe6060f1SDimitry Andric const bool HasFP = hasFP(MF); 6855ffd83dbSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 6865ffd83dbSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 6875ffd83dbSDimitry Andric const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi; 6885ffd83dbSDimitry Andric const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 6895ffd83dbSDimitry Andric 690eaeb601bSDimitry Andric uint64_t CurrentOffset = 0; 691eaeb601bSDimitry Andric 692eaeb601bSDimitry Andric assert(AlignOffset < StackProbeSize); 693eaeb601bSDimitry Andric 694eaeb601bSDimitry Andric // If the offset is so small it fits within a page, there's nothing to do. 695eaeb601bSDimitry Andric if (StackProbeSize < Offset + AlignOffset) { 696eaeb601bSDimitry Andric 697bdd1243dSDimitry Andric uint64_t StackAdjustment = StackProbeSize - AlignOffset; 698bdd1243dSDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false) 699eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 700fe6060f1SDimitry Andric if (!HasFP && NeedsDwarfCFI) { 701bdd1243dSDimitry Andric BuildCFI( 702bdd1243dSDimitry Andric MBB, MBBI, DL, 703bdd1243dSDimitry Andric MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment)); 704fe6060f1SDimitry Andric } 705eaeb601bSDimitry Andric 706eaeb601bSDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc)) 707eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 708eaeb601bSDimitry Andric StackPtr, false, 0) 709eaeb601bSDimitry Andric .addImm(0) 710eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 711eaeb601bSDimitry Andric NumFrameExtraProbe++; 712eaeb601bSDimitry Andric CurrentOffset = StackProbeSize - AlignOffset; 713eaeb601bSDimitry Andric } 714eaeb601bSDimitry Andric 715eaeb601bSDimitry Andric // For the next N - 1 pages, just probe. I tried to take advantage of 7165ffd83dbSDimitry Andric // natural probes but it implies much more logic and there was very few 7175ffd83dbSDimitry Andric // interesting natural probes to interleave. 7185ffd83dbSDimitry Andric while (CurrentOffset + StackProbeSize < Offset) { 719bdd1243dSDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false) 7205ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 7215ffd83dbSDimitry Andric 722fe6060f1SDimitry Andric if (!HasFP && NeedsDwarfCFI) { 723fe6060f1SDimitry Andric BuildCFI( 724fe6060f1SDimitry Andric MBB, MBBI, DL, 725fe6060f1SDimitry Andric MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize)); 726fe6060f1SDimitry Andric } 7275ffd83dbSDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc)) 7285ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 7295ffd83dbSDimitry Andric StackPtr, false, 0) 7305ffd83dbSDimitry Andric .addImm(0) 7315ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 7325ffd83dbSDimitry Andric NumFrameExtraProbe++; 7335ffd83dbSDimitry Andric CurrentOffset += StackProbeSize; 7345ffd83dbSDimitry Andric } 7355ffd83dbSDimitry Andric 736eaeb601bSDimitry Andric // No need to probe the tail, it is smaller than a Page. 7375ffd83dbSDimitry Andric uint64_t ChunkSize = Offset - CurrentOffset; 738bdd1243dSDimitry Andric if (ChunkSize == SlotSize) { 739bdd1243dSDimitry Andric // Use push for slot sized adjustments as a size optimization, 740bdd1243dSDimitry Andric // like emitSPUpdate does when not probing. 741bdd1243dSDimitry Andric unsigned Reg = Is64Bit ? X86::RAX : X86::EAX; 742bdd1243dSDimitry Andric unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r; 743bdd1243dSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Opc)) 744bdd1243dSDimitry Andric .addReg(Reg, RegState::Undef) 7455ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 746bdd1243dSDimitry Andric } else { 747bdd1243dSDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false) 748bdd1243dSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 749bdd1243dSDimitry Andric } 750fe6060f1SDimitry Andric // No need to adjust Dwarf CFA offset here, the last position of the stack has 751fe6060f1SDimitry Andric // been defined 7525ffd83dbSDimitry Andric } 7535ffd83dbSDimitry Andric 7545ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericLoop( 7555ffd83dbSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 756eaeb601bSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset, 757eaeb601bSDimitry Andric uint64_t AlignOffset) const { 7585ffd83dbSDimitry Andric assert(Offset && "null offset"); 7595ffd83dbSDimitry Andric 760bdd1243dSDimitry Andric assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) != 761bdd1243dSDimitry Andric MachineBasicBlock::LQR_Live && 762bdd1243dSDimitry Andric "Inline stack probe loop will clobber live EFLAGS."); 763bdd1243dSDimitry Andric 76404eeddc0SDimitry Andric const bool NeedsDwarfCFI = needsDwarfCFI(MF); 76504eeddc0SDimitry Andric const bool HasFP = hasFP(MF); 7665ffd83dbSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 7675ffd83dbSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 7685ffd83dbSDimitry Andric const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi; 7695ffd83dbSDimitry Andric const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 7705ffd83dbSDimitry Andric 771eaeb601bSDimitry Andric if (AlignOffset) { 772eaeb601bSDimitry Andric if (AlignOffset < StackProbeSize) { 773eaeb601bSDimitry Andric // Perform a first smaller allocation followed by a probe. 774bdd1243dSDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false) 775eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 776eaeb601bSDimitry Andric 777eaeb601bSDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc)) 778eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 779eaeb601bSDimitry Andric StackPtr, false, 0) 780eaeb601bSDimitry Andric .addImm(0) 781eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 782eaeb601bSDimitry Andric NumFrameExtraProbe++; 783eaeb601bSDimitry Andric Offset -= AlignOffset; 784eaeb601bSDimitry Andric } 785eaeb601bSDimitry Andric } 786eaeb601bSDimitry Andric 7875ffd83dbSDimitry Andric // Synthesize a loop 7885ffd83dbSDimitry Andric NumFrameLoopProbe++; 7895ffd83dbSDimitry Andric const BasicBlock *LLVM_BB = MBB.getBasicBlock(); 7905ffd83dbSDimitry Andric 7915ffd83dbSDimitry Andric MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7925ffd83dbSDimitry Andric MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7935ffd83dbSDimitry Andric 7945ffd83dbSDimitry Andric MachineFunction::iterator MBBIter = ++MBB.getIterator(); 7955ffd83dbSDimitry Andric MF.insert(MBBIter, testMBB); 7965ffd83dbSDimitry Andric MF.insert(MBBIter, tailMBB); 7975ffd83dbSDimitry Andric 7988c6f6c0cSDimitry Andric Register FinalStackProbed = Uses64BitFramePtr ? X86::R11 7998c6f6c0cSDimitry Andric : Is64Bit ? X86::R11D 8008c6f6c0cSDimitry Andric : X86::EAX; 80104eeddc0SDimitry Andric 8025ffd83dbSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed) 8035ffd83dbSDimitry Andric .addReg(StackPtr) 8045ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8055ffd83dbSDimitry Andric 8065ffd83dbSDimitry Andric // save loop bound 8075ffd83dbSDimitry Andric { 80804eeddc0SDimitry Andric const unsigned BoundOffset = alignDown(Offset, StackProbeSize); 80906c3fb27SDimitry Andric const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr); 810eaeb601bSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed) 8115ffd83dbSDimitry Andric .addReg(FinalStackProbed) 81204eeddc0SDimitry Andric .addImm(BoundOffset) 8135ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 81404eeddc0SDimitry Andric 81504eeddc0SDimitry Andric // while in the loop, use loop-invariant reg for CFI, 81604eeddc0SDimitry Andric // instead of the stack pointer, which changes during the loop 81704eeddc0SDimitry Andric if (!HasFP && NeedsDwarfCFI) { 81804eeddc0SDimitry Andric // x32 uses the same DWARF register numbers as x86-64, 81904eeddc0SDimitry Andric // so there isn't a register number for r11d, we must use r11 instead 82004eeddc0SDimitry Andric const Register DwarfFinalStackProbed = 82104eeddc0SDimitry Andric STI.isTarget64BitILP32() 82204eeddc0SDimitry Andric ? Register(getX86SubSuperRegister(FinalStackProbed, 64)) 82304eeddc0SDimitry Andric : FinalStackProbed; 82404eeddc0SDimitry Andric 82504eeddc0SDimitry Andric BuildCFI(MBB, MBBI, DL, 82604eeddc0SDimitry Andric MCCFIInstruction::createDefCfaRegister( 82704eeddc0SDimitry Andric nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true))); 82804eeddc0SDimitry Andric BuildCFI(MBB, MBBI, DL, 82904eeddc0SDimitry Andric MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset)); 83004eeddc0SDimitry Andric } 8315ffd83dbSDimitry Andric } 8325ffd83dbSDimitry Andric 8335ffd83dbSDimitry Andric // allocate a page 834bdd1243dSDimitry Andric BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize, 835bdd1243dSDimitry Andric /*InEpilogue=*/false) 8365ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8375ffd83dbSDimitry Andric 8385ffd83dbSDimitry Andric // touch the page 8395ffd83dbSDimitry Andric addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc)) 8405ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 8415ffd83dbSDimitry Andric StackPtr, false, 0) 8425ffd83dbSDimitry Andric .addImm(0) 8435ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8445ffd83dbSDimitry Andric 8455ffd83dbSDimitry Andric // cmp with stack pointer bound 8465ffd83dbSDimitry Andric BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr)) 8475ffd83dbSDimitry Andric .addReg(StackPtr) 8485ffd83dbSDimitry Andric .addReg(FinalStackProbed) 8495ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8505ffd83dbSDimitry Andric 8515ffd83dbSDimitry Andric // jump 8525ffd83dbSDimitry Andric BuildMI(testMBB, DL, TII.get(X86::JCC_1)) 8535ffd83dbSDimitry Andric .addMBB(testMBB) 8545ffd83dbSDimitry Andric .addImm(X86::COND_NE) 8555ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8565ffd83dbSDimitry Andric testMBB->addSuccessor(testMBB); 8575ffd83dbSDimitry Andric testMBB->addSuccessor(tailMBB); 8585ffd83dbSDimitry Andric 8595ffd83dbSDimitry Andric // BB management 8605ffd83dbSDimitry Andric tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end()); 8615ffd83dbSDimitry Andric tailMBB->transferSuccessorsAndUpdatePHIs(&MBB); 8625ffd83dbSDimitry Andric MBB.addSuccessor(testMBB); 8635ffd83dbSDimitry Andric 8645ffd83dbSDimitry Andric // handle tail 865bdd1243dSDimitry Andric const uint64_t TailOffset = Offset % StackProbeSize; 86604eeddc0SDimitry Andric MachineBasicBlock::iterator TailMBBIter = tailMBB->begin(); 8675ffd83dbSDimitry Andric if (TailOffset) { 868bdd1243dSDimitry Andric BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset, 869bdd1243dSDimitry Andric /*InEpilogue=*/false) 8705ffd83dbSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 8715ffd83dbSDimitry Andric } 8725ffd83dbSDimitry Andric 87304eeddc0SDimitry Andric // after the loop, switch back to stack pointer for CFI 87404eeddc0SDimitry Andric if (!HasFP && NeedsDwarfCFI) { 87504eeddc0SDimitry Andric // x32 uses the same DWARF register numbers as x86-64, 87604eeddc0SDimitry Andric // so there isn't a register number for esp, we must use rsp instead 87704eeddc0SDimitry Andric const Register DwarfStackPtr = 87804eeddc0SDimitry Andric STI.isTarget64BitILP32() 87904eeddc0SDimitry Andric ? Register(getX86SubSuperRegister(StackPtr, 64)) 88004eeddc0SDimitry Andric : Register(StackPtr); 88104eeddc0SDimitry Andric 88204eeddc0SDimitry Andric BuildCFI(*tailMBB, TailMBBIter, DL, 88304eeddc0SDimitry Andric MCCFIInstruction::createDefCfaRegister( 88404eeddc0SDimitry Andric nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true))); 88504eeddc0SDimitry Andric } 88604eeddc0SDimitry Andric 8875ffd83dbSDimitry Andric // Update Live In information 8885ffd83dbSDimitry Andric recomputeLiveIns(*testMBB); 8895ffd83dbSDimitry Andric recomputeLiveIns(*tailMBB); 8905ffd83dbSDimitry Andric } 8915ffd83dbSDimitry Andric 8925ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64( 8935ffd83dbSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 8945ffd83dbSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const { 8955ffd83dbSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 8960b57cec5SDimitry Andric assert(STI.is64Bit() && "different expansion needed for 32 bit"); 8970b57cec5SDimitry Andric assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR"); 8980b57cec5SDimitry Andric const TargetInstrInfo &TII = *STI.getInstrInfo(); 8990b57cec5SDimitry Andric const BasicBlock *LLVM_BB = MBB.getBasicBlock(); 9000b57cec5SDimitry Andric 901bdd1243dSDimitry Andric assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) != 902bdd1243dSDimitry Andric MachineBasicBlock::LQR_Live && 903bdd1243dSDimitry Andric "Inline stack probe loop will clobber live EFLAGS."); 904bdd1243dSDimitry Andric 9050b57cec5SDimitry Andric // RAX contains the number of bytes of desired stack adjustment. 9060b57cec5SDimitry Andric // The handling here assumes this value has already been updated so as to 9070b57cec5SDimitry Andric // maintain stack alignment. 9080b57cec5SDimitry Andric // 9090b57cec5SDimitry Andric // We need to exit with RSP modified by this amount and execute suitable 9100b57cec5SDimitry Andric // page touches to notify the OS that we're growing the stack responsibly. 9110b57cec5SDimitry Andric // All stack probing must be done without modifying RSP. 9120b57cec5SDimitry Andric // 9130b57cec5SDimitry Andric // MBB: 9140b57cec5SDimitry Andric // SizeReg = RAX; 9150b57cec5SDimitry Andric // ZeroReg = 0 9160b57cec5SDimitry Andric // CopyReg = RSP 9170b57cec5SDimitry Andric // Flags, TestReg = CopyReg - SizeReg 9180b57cec5SDimitry Andric // FinalReg = !Flags.Ovf ? TestReg : ZeroReg 9190b57cec5SDimitry Andric // LimitReg = gs magic thread env access 9200b57cec5SDimitry Andric // if FinalReg >= LimitReg goto ContinueMBB 9210b57cec5SDimitry Andric // RoundBB: 9220b57cec5SDimitry Andric // RoundReg = page address of FinalReg 9230b57cec5SDimitry Andric // LoopMBB: 9240b57cec5SDimitry Andric // LoopReg = PHI(LimitReg,ProbeReg) 9250b57cec5SDimitry Andric // ProbeReg = LoopReg - PageSize 9260b57cec5SDimitry Andric // [ProbeReg] = 0 9270b57cec5SDimitry Andric // if (ProbeReg > RoundReg) goto LoopMBB 9280b57cec5SDimitry Andric // ContinueMBB: 9290b57cec5SDimitry Andric // RSP = RSP - RAX 9300b57cec5SDimitry Andric // [rest of original MBB] 9310b57cec5SDimitry Andric 9320b57cec5SDimitry Andric // Set up the new basic blocks 9330b57cec5SDimitry Andric MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9340b57cec5SDimitry Andric MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9350b57cec5SDimitry Andric MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9360b57cec5SDimitry Andric 9370b57cec5SDimitry Andric MachineFunction::iterator MBBIter = std::next(MBB.getIterator()); 9380b57cec5SDimitry Andric MF.insert(MBBIter, RoundMBB); 9390b57cec5SDimitry Andric MF.insert(MBBIter, LoopMBB); 9400b57cec5SDimitry Andric MF.insert(MBBIter, ContinueMBB); 9410b57cec5SDimitry Andric 9420b57cec5SDimitry Andric // Split MBB and move the tail portion down to ContinueMBB. 9430b57cec5SDimitry Andric MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI); 9440b57cec5SDimitry Andric ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end()); 9450b57cec5SDimitry Andric ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB); 9460b57cec5SDimitry Andric 9470b57cec5SDimitry Andric // Some useful constants 9480b57cec5SDimitry Andric const int64_t ThreadEnvironmentStackLimit = 0x10; 9490b57cec5SDimitry Andric const int64_t PageSize = 0x1000; 9500b57cec5SDimitry Andric const int64_t PageMask = ~(PageSize - 1); 9510b57cec5SDimitry Andric 9520b57cec5SDimitry Andric // Registers we need. For the normal case we use virtual 9530b57cec5SDimitry Andric // registers. For the prolog expansion we use RAX, RCX and RDX. 9540b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo(); 9550b57cec5SDimitry Andric const TargetRegisterClass *RegClass = &X86::GR64RegClass; 956*5f757f3fSDimitry Andric const Register 957*5f757f3fSDimitry Andric SizeReg = InProlog ? X86::RAX : MRI.createVirtualRegister(RegClass), 958*5f757f3fSDimitry Andric ZeroReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass), 959*5f757f3fSDimitry Andric CopyReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass), 960*5f757f3fSDimitry Andric TestReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass), 961*5f757f3fSDimitry Andric FinalReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass), 962*5f757f3fSDimitry Andric RoundedReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass), 963*5f757f3fSDimitry Andric LimitReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass), 964*5f757f3fSDimitry Andric JoinReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass), 965*5f757f3fSDimitry Andric ProbeReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass); 9660b57cec5SDimitry Andric 9670b57cec5SDimitry Andric // SP-relative offsets where we can save RCX and RDX. 9680b57cec5SDimitry Andric int64_t RCXShadowSlot = 0; 9690b57cec5SDimitry Andric int64_t RDXShadowSlot = 0; 9700b57cec5SDimitry Andric 9710b57cec5SDimitry Andric // If inlining in the prolog, save RCX and RDX. 9720b57cec5SDimitry Andric if (InProlog) { 9730b57cec5SDimitry Andric // Compute the offsets. We need to account for things already 9740b57cec5SDimitry Andric // pushed onto the stack at this point: return address, frame 9750b57cec5SDimitry Andric // pointer (if used), and callee saves. 9760b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 9770b57cec5SDimitry Andric const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize(); 9780b57cec5SDimitry Andric const bool HasFP = hasFP(MF); 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric // Check if we need to spill RCX and/or RDX. 9810b57cec5SDimitry Andric // Here we assume that no earlier prologue instruction changes RCX and/or 9820b57cec5SDimitry Andric // RDX, so checking the block live-ins is enough. 9830b57cec5SDimitry Andric const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX); 9840b57cec5SDimitry Andric const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX); 9850b57cec5SDimitry Andric int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0); 9860b57cec5SDimitry Andric // Assign the initial slot to both registers, then change RDX's slot if both 9870b57cec5SDimitry Andric // need to be spilled. 9880b57cec5SDimitry Andric if (IsRCXLiveIn) 9890b57cec5SDimitry Andric RCXShadowSlot = InitSlot; 9900b57cec5SDimitry Andric if (IsRDXLiveIn) 9910b57cec5SDimitry Andric RDXShadowSlot = InitSlot; 9920b57cec5SDimitry Andric if (IsRDXLiveIn && IsRCXLiveIn) 9930b57cec5SDimitry Andric RDXShadowSlot += 8; 9940b57cec5SDimitry Andric // Emit the saves if needed. 9950b57cec5SDimitry Andric if (IsRCXLiveIn) 9960b57cec5SDimitry Andric addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false, 9970b57cec5SDimitry Andric RCXShadowSlot) 9980b57cec5SDimitry Andric .addReg(X86::RCX); 9990b57cec5SDimitry Andric if (IsRDXLiveIn) 10000b57cec5SDimitry Andric addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false, 10010b57cec5SDimitry Andric RDXShadowSlot) 10020b57cec5SDimitry Andric .addReg(X86::RDX); 10030b57cec5SDimitry Andric } else { 10040b57cec5SDimitry Andric // Not in the prolog. Copy RAX to a virtual reg. 10050b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX); 10060b57cec5SDimitry Andric } 10070b57cec5SDimitry Andric 10080b57cec5SDimitry Andric // Add code to MBB to check for overflow and set the new target stack pointer 10090b57cec5SDimitry Andric // to zero if so. 10100b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg) 10110b57cec5SDimitry Andric .addReg(ZeroReg, RegState::Undef) 10120b57cec5SDimitry Andric .addReg(ZeroReg, RegState::Undef); 10130b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP); 10140b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg) 10150b57cec5SDimitry Andric .addReg(CopyReg) 10160b57cec5SDimitry Andric .addReg(SizeReg); 10170b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg) 10180b57cec5SDimitry Andric .addReg(TestReg) 10190b57cec5SDimitry Andric .addReg(ZeroReg) 10200b57cec5SDimitry Andric .addImm(X86::COND_B); 10210b57cec5SDimitry Andric 10220b57cec5SDimitry Andric // FinalReg now holds final stack pointer value, or zero if 10230b57cec5SDimitry Andric // allocation would overflow. Compare against the current stack 10240b57cec5SDimitry Andric // limit from the thread environment block. Note this limit is the 10250b57cec5SDimitry Andric // lowest touched page on the stack, not the point at which the OS 10260b57cec5SDimitry Andric // will cause an overflow exception, so this is just an optimization 10270b57cec5SDimitry Andric // to avoid unnecessarily touching pages that are below the current 10280b57cec5SDimitry Andric // SP but already committed to the stack by the OS. 10290b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg) 10300b57cec5SDimitry Andric .addReg(0) 10310b57cec5SDimitry Andric .addImm(1) 10320b57cec5SDimitry Andric .addReg(0) 10330b57cec5SDimitry Andric .addImm(ThreadEnvironmentStackLimit) 10340b57cec5SDimitry Andric .addReg(X86::GS); 10350b57cec5SDimitry Andric BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg); 10360b57cec5SDimitry Andric // Jump if the desired stack pointer is at or above the stack limit. 1037*5f757f3fSDimitry Andric BuildMI(&MBB, DL, TII.get(X86::JCC_1)) 1038*5f757f3fSDimitry Andric .addMBB(ContinueMBB) 1039*5f757f3fSDimitry Andric .addImm(X86::COND_AE); 10400b57cec5SDimitry Andric 10410b57cec5SDimitry Andric // Add code to roundMBB to round the final stack pointer to a page boundary. 10420b57cec5SDimitry Andric RoundMBB->addLiveIn(FinalReg); 10430b57cec5SDimitry Andric BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg) 10440b57cec5SDimitry Andric .addReg(FinalReg) 10450b57cec5SDimitry Andric .addImm(PageMask); 10460b57cec5SDimitry Andric BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB); 10470b57cec5SDimitry Andric 10480b57cec5SDimitry Andric // LimitReg now holds the current stack limit, RoundedReg page-rounded 10490b57cec5SDimitry Andric // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page 10500b57cec5SDimitry Andric // and probe until we reach RoundedReg. 10510b57cec5SDimitry Andric if (!InProlog) { 10520b57cec5SDimitry Andric BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg) 10530b57cec5SDimitry Andric .addReg(LimitReg) 10540b57cec5SDimitry Andric .addMBB(RoundMBB) 10550b57cec5SDimitry Andric .addReg(ProbeReg) 10560b57cec5SDimitry Andric .addMBB(LoopMBB); 10570b57cec5SDimitry Andric } 10580b57cec5SDimitry Andric 10590b57cec5SDimitry Andric LoopMBB->addLiveIn(JoinReg); 10600b57cec5SDimitry Andric addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg, 10610b57cec5SDimitry Andric false, -PageSize); 10620b57cec5SDimitry Andric 10630b57cec5SDimitry Andric // Probe by storing a byte onto the stack. 10640b57cec5SDimitry Andric BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi)) 10650b57cec5SDimitry Andric .addReg(ProbeReg) 10660b57cec5SDimitry Andric .addImm(1) 10670b57cec5SDimitry Andric .addReg(0) 10680b57cec5SDimitry Andric .addImm(0) 10690b57cec5SDimitry Andric .addReg(0) 10700b57cec5SDimitry Andric .addImm(0); 10710b57cec5SDimitry Andric 10720b57cec5SDimitry Andric LoopMBB->addLiveIn(RoundedReg); 10730b57cec5SDimitry Andric BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr)) 10740b57cec5SDimitry Andric .addReg(RoundedReg) 10750b57cec5SDimitry Andric .addReg(ProbeReg); 1076*5f757f3fSDimitry Andric BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)) 1077*5f757f3fSDimitry Andric .addMBB(LoopMBB) 1078*5f757f3fSDimitry Andric .addImm(X86::COND_NE); 10790b57cec5SDimitry Andric 10800b57cec5SDimitry Andric MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI(); 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric // If in prolog, restore RDX and RCX. 10830b57cec5SDimitry Andric if (InProlog) { 10840b57cec5SDimitry Andric if (RCXShadowSlot) // It means we spilled RCX in the prologue. 10850b57cec5SDimitry Andric addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, 10860b57cec5SDimitry Andric TII.get(X86::MOV64rm), X86::RCX), 10870b57cec5SDimitry Andric X86::RSP, false, RCXShadowSlot); 10880b57cec5SDimitry Andric if (RDXShadowSlot) // It means we spilled RDX in the prologue. 10890b57cec5SDimitry Andric addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, 10900b57cec5SDimitry Andric TII.get(X86::MOV64rm), X86::RDX), 10910b57cec5SDimitry Andric X86::RSP, false, RDXShadowSlot); 10920b57cec5SDimitry Andric } 10930b57cec5SDimitry Andric 10940b57cec5SDimitry Andric // Now that the probing is done, add code to continueMBB to update 10950b57cec5SDimitry Andric // the stack pointer for real. 10960b57cec5SDimitry Andric ContinueMBB->addLiveIn(SizeReg); 10970b57cec5SDimitry Andric BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP) 10980b57cec5SDimitry Andric .addReg(X86::RSP) 10990b57cec5SDimitry Andric .addReg(SizeReg); 11000b57cec5SDimitry Andric 11010b57cec5SDimitry Andric // Add the control flow edges we need. 11020b57cec5SDimitry Andric MBB.addSuccessor(ContinueMBB); 11030b57cec5SDimitry Andric MBB.addSuccessor(RoundMBB); 11040b57cec5SDimitry Andric RoundMBB->addSuccessor(LoopMBB); 11050b57cec5SDimitry Andric LoopMBB->addSuccessor(ContinueMBB); 11060b57cec5SDimitry Andric LoopMBB->addSuccessor(LoopMBB); 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric // Mark all the instructions added to the prolog as frame setup. 11090b57cec5SDimitry Andric if (InProlog) { 11100b57cec5SDimitry Andric for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) { 11110b57cec5SDimitry Andric BeforeMBBI->setFlag(MachineInstr::FrameSetup); 11120b57cec5SDimitry Andric } 11130b57cec5SDimitry Andric for (MachineInstr &MI : *RoundMBB) { 11140b57cec5SDimitry Andric MI.setFlag(MachineInstr::FrameSetup); 11150b57cec5SDimitry Andric } 11160b57cec5SDimitry Andric for (MachineInstr &MI : *LoopMBB) { 11170b57cec5SDimitry Andric MI.setFlag(MachineInstr::FrameSetup); 11180b57cec5SDimitry Andric } 1119bdd1243dSDimitry Andric for (MachineInstr &MI : 1120bdd1243dSDimitry Andric llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) { 1121bdd1243dSDimitry Andric MI.setFlag(MachineInstr::FrameSetup); 11220b57cec5SDimitry Andric } 11230b57cec5SDimitry Andric } 11240b57cec5SDimitry Andric } 11250b57cec5SDimitry Andric 11264824e7fdSDimitry Andric void X86FrameLowering::emitStackProbeCall( 11274824e7fdSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 11284824e7fdSDimitry Andric MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog, 1129bdd1243dSDimitry Andric std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const { 11300b57cec5SDimitry Andric bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large; 11310b57cec5SDimitry Andric 11320946e70aSDimitry Andric // FIXME: Add indirect thunk support and remove this. 11330946e70aSDimitry Andric if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls()) 11340b57cec5SDimitry Andric report_fatal_error("Emitting stack probe calls on 64-bit with the large " 11350946e70aSDimitry Andric "code model and indirect thunks not yet implemented."); 11360b57cec5SDimitry Andric 1137bdd1243dSDimitry Andric assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) != 1138bdd1243dSDimitry Andric MachineBasicBlock::LQR_Live && 1139bdd1243dSDimitry Andric "Stack probe calls will clobber live EFLAGS."); 1140bdd1243dSDimitry Andric 11410b57cec5SDimitry Andric unsigned CallOp; 11420b57cec5SDimitry Andric if (Is64Bit) 11430b57cec5SDimitry Andric CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32; 11440b57cec5SDimitry Andric else 11450b57cec5SDimitry Andric CallOp = X86::CALLpcrel32; 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF); 11480b57cec5SDimitry Andric 11490b57cec5SDimitry Andric MachineInstrBuilder CI; 11500b57cec5SDimitry Andric MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI); 11510b57cec5SDimitry Andric 11520b57cec5SDimitry Andric // All current stack probes take AX and SP as input, clobber flags, and 11530b57cec5SDimitry Andric // preserve all registers. x86_64 probes leave RSP unmodified. 11540b57cec5SDimitry Andric if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) { 11550b57cec5SDimitry Andric // For the large code model, we have to call through a register. Use R11, 11560b57cec5SDimitry Andric // as it is scratch in all supported calling conventions. 11570b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11) 11580b57cec5SDimitry Andric .addExternalSymbol(MF.createExternalSymbolName(Symbol)); 11590b57cec5SDimitry Andric CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11); 11600b57cec5SDimitry Andric } else { 11610b57cec5SDimitry Andric CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)) 11620b57cec5SDimitry Andric .addExternalSymbol(MF.createExternalSymbolName(Symbol)); 11630b57cec5SDimitry Andric } 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX; 11660b57cec5SDimitry Andric unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP; 11670b57cec5SDimitry Andric CI.addReg(AX, RegState::Implicit) 11680b57cec5SDimitry Andric .addReg(SP, RegState::Implicit) 11690b57cec5SDimitry Andric .addReg(AX, RegState::Define | RegState::Implicit) 11700b57cec5SDimitry Andric .addReg(SP, RegState::Define | RegState::Implicit) 11710b57cec5SDimitry Andric .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 11720b57cec5SDimitry Andric 11734824e7fdSDimitry Andric MachineInstr *ModInst = CI; 11740b57cec5SDimitry Andric if (STI.isTargetWin64() || !STI.isOSWindows()) { 11750b57cec5SDimitry Andric // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves. 11760b57cec5SDimitry Andric // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp 11770b57cec5SDimitry Andric // themselves. They also does not clobber %rax so we can reuse it when 11780b57cec5SDimitry Andric // adjusting %rsp. 11790b57cec5SDimitry Andric // All other platforms do not specify a particular ABI for the stack probe 11800b57cec5SDimitry Andric // function, so we arbitrarily define it to not adjust %esp/%rsp itself. 11814824e7fdSDimitry Andric ModInst = 11820b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP) 11830b57cec5SDimitry Andric .addReg(SP) 11840b57cec5SDimitry Andric .addReg(AX); 11850b57cec5SDimitry Andric } 11860b57cec5SDimitry Andric 11874824e7fdSDimitry Andric // DebugInfo variable locations -- if there's an instruction number for the 11884824e7fdSDimitry Andric // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that 11894824e7fdSDimitry Andric // modifies SP. 11904824e7fdSDimitry Andric if (InstrNum) { 11914824e7fdSDimitry Andric if (STI.isTargetWin64() || !STI.isOSWindows()) { 11924824e7fdSDimitry Andric // Label destination operand of the subtract. 11934824e7fdSDimitry Andric MF.makeDebugValueSubstitution(*InstrNum, 11944824e7fdSDimitry Andric {ModInst->getDebugInstrNum(), 0}); 11954824e7fdSDimitry Andric } else { 11964824e7fdSDimitry Andric // Label the call. The operand number is the penultimate operand, zero 11974824e7fdSDimitry Andric // based. 11984824e7fdSDimitry Andric unsigned SPDefOperand = ModInst->getNumOperands() - 2; 11994824e7fdSDimitry Andric MF.makeDebugValueSubstitution( 12004824e7fdSDimitry Andric *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand}); 12014824e7fdSDimitry Andric } 12024824e7fdSDimitry Andric } 12034824e7fdSDimitry Andric 12040b57cec5SDimitry Andric if (InProlog) { 12050b57cec5SDimitry Andric // Apply the frame setup flag to all inserted instrs. 12060b57cec5SDimitry Andric for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI) 12070b57cec5SDimitry Andric ExpansionMBBI->setFlag(MachineInstr::FrameSetup); 12080b57cec5SDimitry Andric } 12090b57cec5SDimitry Andric } 12100b57cec5SDimitry Andric 12110b57cec5SDimitry Andric static unsigned calculateSetFPREG(uint64_t SPAdjust) { 12120b57cec5SDimitry Andric // Win64 ABI has a less restrictive limitation of 240; 128 works equally well 12130b57cec5SDimitry Andric // and might require smaller successive adjustments. 12140b57cec5SDimitry Andric const uint64_t Win64MaxSEHOffset = 128; 12150b57cec5SDimitry Andric uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset); 12160b57cec5SDimitry Andric // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode. 12170b57cec5SDimitry Andric return SEHFrameOffset & -16; 12180b57cec5SDimitry Andric } 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric // If we're forcing a stack realignment we can't rely on just the frame 12210b57cec5SDimitry Andric // info, we need to know the ABI stack alignment as well in case we 12220b57cec5SDimitry Andric // have a call out. Otherwise just make sure we have some alignment - we'll 12230b57cec5SDimitry Andric // go with the minimum SlotSize. 1224*5f757f3fSDimitry Andric uint64_t 1225*5f757f3fSDimitry Andric X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const { 12260b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 12275ffd83dbSDimitry Andric Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment. 12285ffd83dbSDimitry Andric Align StackAlign = getStackAlign(); 122906c3fb27SDimitry Andric bool HasRealign = MF.getFunction().hasFnAttribute("stackrealign"); 123006c3fb27SDimitry Andric if (HasRealign) { 12310b57cec5SDimitry Andric if (MFI.hasCalls()) 12320b57cec5SDimitry Andric MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign; 12330b57cec5SDimitry Andric else if (MaxAlign < SlotSize) 12345ffd83dbSDimitry Andric MaxAlign = Align(SlotSize); 12350b57cec5SDimitry Andric } 123606c3fb27SDimitry Andric 123706c3fb27SDimitry Andric if (!Is64Bit && MF.getFunction().getCallingConv() == CallingConv::X86_INTR) { 123806c3fb27SDimitry Andric if (HasRealign) 123906c3fb27SDimitry Andric MaxAlign = (MaxAlign > 16) ? MaxAlign : Align(16); 124006c3fb27SDimitry Andric else 124106c3fb27SDimitry Andric MaxAlign = Align(16); 124206c3fb27SDimitry Andric } 12435ffd83dbSDimitry Andric return MaxAlign.value(); 12440b57cec5SDimitry Andric } 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB, 12470b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI, 12480b57cec5SDimitry Andric const DebugLoc &DL, unsigned Reg, 12490b57cec5SDimitry Andric uint64_t MaxAlign) const { 12500b57cec5SDimitry Andric uint64_t Val = -MaxAlign; 12510b57cec5SDimitry Andric unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val); 1252eaeb601bSDimitry Andric 1253eaeb601bSDimitry Andric MachineFunction &MF = *MBB.getParent(); 1254eaeb601bSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 1255eaeb601bSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 1256eaeb601bSDimitry Andric const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 1257eaeb601bSDimitry Andric const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF); 1258eaeb601bSDimitry Andric 1259eaeb601bSDimitry Andric // We want to make sure that (in worst case) less than StackProbeSize bytes 1260eaeb601bSDimitry Andric // are not probed after the AND. This assumption is used in 1261eaeb601bSDimitry Andric // emitStackProbeInlineGeneric. 1262eaeb601bSDimitry Andric if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) { 1263eaeb601bSDimitry Andric { 1264eaeb601bSDimitry Andric NumFrameLoopProbe++; 1265eaeb601bSDimitry Andric MachineBasicBlock *entryMBB = 1266eaeb601bSDimitry Andric MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 1267eaeb601bSDimitry Andric MachineBasicBlock *headMBB = 1268eaeb601bSDimitry Andric MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 1269eaeb601bSDimitry Andric MachineBasicBlock *bodyMBB = 1270eaeb601bSDimitry Andric MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 1271eaeb601bSDimitry Andric MachineBasicBlock *footMBB = 1272eaeb601bSDimitry Andric MF.CreateMachineBasicBlock(MBB.getBasicBlock()); 1273eaeb601bSDimitry Andric 1274eaeb601bSDimitry Andric MachineFunction::iterator MBBIter = MBB.getIterator(); 1275eaeb601bSDimitry Andric MF.insert(MBBIter, entryMBB); 1276eaeb601bSDimitry Andric MF.insert(MBBIter, headMBB); 1277eaeb601bSDimitry Andric MF.insert(MBBIter, bodyMBB); 1278eaeb601bSDimitry Andric MF.insert(MBBIter, footMBB); 1279eaeb601bSDimitry Andric const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi; 12808c6f6c0cSDimitry Andric Register FinalStackProbed = Uses64BitFramePtr ? X86::R11 12818c6f6c0cSDimitry Andric : Is64Bit ? X86::R11D 12828c6f6c0cSDimitry Andric : X86::EAX; 1283eaeb601bSDimitry Andric 1284eaeb601bSDimitry Andric // Setup entry block 1285eaeb601bSDimitry Andric { 1286eaeb601bSDimitry Andric 1287eaeb601bSDimitry Andric entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI); 1288eaeb601bSDimitry Andric BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed) 1289eaeb601bSDimitry Andric .addReg(StackPtr) 1290eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1291eaeb601bSDimitry Andric MachineInstr *MI = 1292eaeb601bSDimitry Andric BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed) 1293eaeb601bSDimitry Andric .addReg(FinalStackProbed) 1294eaeb601bSDimitry Andric .addImm(Val) 1295eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1296eaeb601bSDimitry Andric 1297eaeb601bSDimitry Andric // The EFLAGS implicit def is dead. 1298eaeb601bSDimitry Andric MI->getOperand(3).setIsDead(); 1299eaeb601bSDimitry Andric 1300eaeb601bSDimitry Andric BuildMI(entryMBB, DL, 1301eaeb601bSDimitry Andric TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr)) 1302eaeb601bSDimitry Andric .addReg(FinalStackProbed) 1303eaeb601bSDimitry Andric .addReg(StackPtr) 1304eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1305eaeb601bSDimitry Andric BuildMI(entryMBB, DL, TII.get(X86::JCC_1)) 1306eaeb601bSDimitry Andric .addMBB(&MBB) 1307eaeb601bSDimitry Andric .addImm(X86::COND_E) 1308eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1309eaeb601bSDimitry Andric entryMBB->addSuccessor(headMBB); 1310eaeb601bSDimitry Andric entryMBB->addSuccessor(&MBB); 1311eaeb601bSDimitry Andric } 1312eaeb601bSDimitry Andric 1313eaeb601bSDimitry Andric // Loop entry block 1314eaeb601bSDimitry Andric 1315eaeb601bSDimitry Andric { 1316*5f757f3fSDimitry Andric const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr); 1317eaeb601bSDimitry Andric BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr) 1318eaeb601bSDimitry Andric .addReg(StackPtr) 1319eaeb601bSDimitry Andric .addImm(StackProbeSize) 1320eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1321eaeb601bSDimitry Andric 1322eaeb601bSDimitry Andric BuildMI(headMBB, DL, 1323eaeb601bSDimitry Andric TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr)) 1324eaeb601bSDimitry Andric .addReg(StackPtr) 1325bdd1243dSDimitry Andric .addReg(FinalStackProbed) 1326eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1327eaeb601bSDimitry Andric 1328bdd1243dSDimitry Andric // jump to the footer if StackPtr < FinalStackProbed 1329eaeb601bSDimitry Andric BuildMI(headMBB, DL, TII.get(X86::JCC_1)) 1330eaeb601bSDimitry Andric .addMBB(footMBB) 1331eaeb601bSDimitry Andric .addImm(X86::COND_B) 1332eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1333eaeb601bSDimitry Andric 1334eaeb601bSDimitry Andric headMBB->addSuccessor(bodyMBB); 1335eaeb601bSDimitry Andric headMBB->addSuccessor(footMBB); 1336eaeb601bSDimitry Andric } 1337eaeb601bSDimitry Andric 1338eaeb601bSDimitry Andric // setup loop body 1339eaeb601bSDimitry Andric { 1340eaeb601bSDimitry Andric addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc)) 1341eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 1342eaeb601bSDimitry Andric StackPtr, false, 0) 1343eaeb601bSDimitry Andric .addImm(0) 1344eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1345eaeb601bSDimitry Andric 1346*5f757f3fSDimitry Andric const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr); 1347eaeb601bSDimitry Andric BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr) 1348eaeb601bSDimitry Andric .addReg(StackPtr) 1349eaeb601bSDimitry Andric .addImm(StackProbeSize) 1350eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1351eaeb601bSDimitry Andric 1352eaeb601bSDimitry Andric // cmp with stack pointer bound 1353eaeb601bSDimitry Andric BuildMI(bodyMBB, DL, 1354eaeb601bSDimitry Andric TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr)) 1355eaeb601bSDimitry Andric .addReg(FinalStackProbed) 1356eaeb601bSDimitry Andric .addReg(StackPtr) 1357eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1358eaeb601bSDimitry Andric 1359bdd1243dSDimitry Andric // jump back while FinalStackProbed < StackPtr 1360eaeb601bSDimitry Andric BuildMI(bodyMBB, DL, TII.get(X86::JCC_1)) 1361eaeb601bSDimitry Andric .addMBB(bodyMBB) 1362eaeb601bSDimitry Andric .addImm(X86::COND_B) 1363eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1364eaeb601bSDimitry Andric bodyMBB->addSuccessor(bodyMBB); 1365eaeb601bSDimitry Andric bodyMBB->addSuccessor(footMBB); 1366eaeb601bSDimitry Andric } 1367eaeb601bSDimitry Andric 1368eaeb601bSDimitry Andric // setup loop footer 1369eaeb601bSDimitry Andric { 1370eaeb601bSDimitry Andric BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr) 1371eaeb601bSDimitry Andric .addReg(FinalStackProbed) 1372eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1373eaeb601bSDimitry Andric addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc)) 1374eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup), 1375eaeb601bSDimitry Andric StackPtr, false, 0) 1376eaeb601bSDimitry Andric .addImm(0) 1377eaeb601bSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1378eaeb601bSDimitry Andric footMBB->addSuccessor(&MBB); 1379eaeb601bSDimitry Andric } 1380eaeb601bSDimitry Andric 1381eaeb601bSDimitry Andric recomputeLiveIns(*headMBB); 1382eaeb601bSDimitry Andric recomputeLiveIns(*bodyMBB); 1383eaeb601bSDimitry Andric recomputeLiveIns(*footMBB); 1384eaeb601bSDimitry Andric recomputeLiveIns(MBB); 1385eaeb601bSDimitry Andric } 1386eaeb601bSDimitry Andric } else { 13870b57cec5SDimitry Andric MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg) 13880b57cec5SDimitry Andric .addReg(Reg) 13890b57cec5SDimitry Andric .addImm(Val) 13900b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 13910b57cec5SDimitry Andric 13920b57cec5SDimitry Andric // The EFLAGS implicit def is dead. 13930b57cec5SDimitry Andric MI->getOperand(3).setIsDead(); 13940b57cec5SDimitry Andric } 1395eaeb601bSDimitry Andric } 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric bool X86FrameLowering::has128ByteRedZone(const MachineFunction &MF) const { 13980b57cec5SDimitry Andric // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be 13990b57cec5SDimitry Andric // clobbered by any interrupt handler. 14000b57cec5SDimitry Andric assert(&STI == &MF.getSubtarget<X86Subtarget>() && 14010b57cec5SDimitry Andric "MF used frame lowering for wrong subtarget"); 14020b57cec5SDimitry Andric const Function &Fn = MF.getFunction(); 14030b57cec5SDimitry Andric const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv()); 14040b57cec5SDimitry Andric return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone); 14050b57cec5SDimitry Andric } 14060b57cec5SDimitry Andric 1407d56accc7SDimitry Andric /// Return true if we need to use the restricted Windows x64 prologue and 1408d56accc7SDimitry Andric /// epilogue code patterns that can be described with WinCFI (.seh_* 1409d56accc7SDimitry Andric /// directives). 1410fe6060f1SDimitry Andric bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const { 1411fe6060f1SDimitry Andric return MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 1412fe6060f1SDimitry Andric } 1413fe6060f1SDimitry Andric 1414fe6060f1SDimitry Andric bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const { 1415fe6060f1SDimitry Andric return !isWin64Prologue(MF) && MF.needsFrameMoves(); 1416fe6060f1SDimitry Andric } 14170b57cec5SDimitry Andric 14180b57cec5SDimitry Andric /// emitPrologue - Push callee-saved registers onto the stack, which 14190b57cec5SDimitry Andric /// automatically adjust the stack pointer. Adjust the stack pointer to allocate 14200b57cec5SDimitry Andric /// space for local variables. Also emit labels used by the exception handler to 14210b57cec5SDimitry Andric /// generate the exception handling frames. 14220b57cec5SDimitry Andric 14230b57cec5SDimitry Andric /* 14240b57cec5SDimitry Andric Here's a gist of what gets emitted: 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric ; Establish frame pointer, if needed 14270b57cec5SDimitry Andric [if needs FP] 14280b57cec5SDimitry Andric push %rbp 14290b57cec5SDimitry Andric .cfi_def_cfa_offset 16 14300b57cec5SDimitry Andric .cfi_offset %rbp, -16 14310b57cec5SDimitry Andric .seh_pushreg %rpb 14320b57cec5SDimitry Andric mov %rsp, %rbp 14330b57cec5SDimitry Andric .cfi_def_cfa_register %rbp 14340b57cec5SDimitry Andric 14350b57cec5SDimitry Andric ; Spill general-purpose registers 14360b57cec5SDimitry Andric [for all callee-saved GPRs] 14370b57cec5SDimitry Andric pushq %<reg> 14380b57cec5SDimitry Andric [if not needs FP] 14390b57cec5SDimitry Andric .cfi_def_cfa_offset (offset from RETADDR) 14400b57cec5SDimitry Andric .seh_pushreg %<reg> 14410b57cec5SDimitry Andric 14420b57cec5SDimitry Andric ; If the required stack alignment > default stack alignment 14430b57cec5SDimitry Andric ; rsp needs to be re-aligned. This creates a "re-alignment gap" 14440b57cec5SDimitry Andric ; of unknown size in the stack frame. 14450b57cec5SDimitry Andric [if stack needs re-alignment] 14460b57cec5SDimitry Andric and $MASK, %rsp 14470b57cec5SDimitry Andric 14480b57cec5SDimitry Andric ; Allocate space for locals 14490b57cec5SDimitry Andric [if target is Windows and allocated space > 4096 bytes] 14500b57cec5SDimitry Andric ; Windows needs special care for allocations larger 14510b57cec5SDimitry Andric ; than one page. 14520b57cec5SDimitry Andric mov $NNN, %rax 14530b57cec5SDimitry Andric call ___chkstk_ms/___chkstk 14540b57cec5SDimitry Andric sub %rax, %rsp 14550b57cec5SDimitry Andric [else] 14560b57cec5SDimitry Andric sub $NNN, %rsp 14570b57cec5SDimitry Andric 14580b57cec5SDimitry Andric [if needs FP] 14590b57cec5SDimitry Andric .seh_stackalloc (size of XMM spill slots) 14600b57cec5SDimitry Andric .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots 14610b57cec5SDimitry Andric [else] 14620b57cec5SDimitry Andric .seh_stackalloc NNN 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric ; Spill XMMs 14650b57cec5SDimitry Andric ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved, 14660b57cec5SDimitry Andric ; they may get spilled on any platform, if the current function 14670b57cec5SDimitry Andric ; calls @llvm.eh.unwind.init 14680b57cec5SDimitry Andric [if needs FP] 14690b57cec5SDimitry Andric [for all callee-saved XMM registers] 14700b57cec5SDimitry Andric movaps %<xmm reg>, -MMM(%rbp) 14710b57cec5SDimitry Andric [for all callee-saved XMM registers] 14720b57cec5SDimitry Andric .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset) 14730b57cec5SDimitry Andric ; i.e. the offset relative to (%rbp - SEHFrameOffset) 14740b57cec5SDimitry Andric [else] 14750b57cec5SDimitry Andric [for all callee-saved XMM registers] 14760b57cec5SDimitry Andric movaps %<xmm reg>, KKK(%rsp) 14770b57cec5SDimitry Andric [for all callee-saved XMM registers] 14780b57cec5SDimitry Andric .seh_savexmm %<xmm reg>, KKK 14790b57cec5SDimitry Andric 14800b57cec5SDimitry Andric .seh_endprologue 14810b57cec5SDimitry Andric 14820b57cec5SDimitry Andric [if needs base pointer] 14830b57cec5SDimitry Andric mov %rsp, %rbx 14840b57cec5SDimitry Andric [if needs to restore base pointer] 14850b57cec5SDimitry Andric mov %rsp, -MMM(%rbp) 14860b57cec5SDimitry Andric 14870b57cec5SDimitry Andric ; Emit CFI info 14880b57cec5SDimitry Andric [if needs FP] 14890b57cec5SDimitry Andric [for all callee-saved registers] 14900b57cec5SDimitry Andric .cfi_offset %<reg>, (offset from %rbp) 14910b57cec5SDimitry Andric [else] 14920b57cec5SDimitry Andric .cfi_def_cfa_offset (offset from RETADDR) 14930b57cec5SDimitry Andric [for all callee-saved registers] 14940b57cec5SDimitry Andric .cfi_offset %<reg>, (offset from %rsp) 14950b57cec5SDimitry Andric 14960b57cec5SDimitry Andric Notes: 14970b57cec5SDimitry Andric - .seh directives are emitted only for Windows 64 ABI 14980b57cec5SDimitry Andric - .cv_fpo directives are emitted on win32 when emitting CodeView 14990b57cec5SDimitry Andric - .cfi directives are emitted for all other ABIs 15000b57cec5SDimitry Andric - for 32-bit code, substitute %e?? registers for %r?? 15010b57cec5SDimitry Andric */ 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric void X86FrameLowering::emitPrologue(MachineFunction &MF, 15040b57cec5SDimitry Andric MachineBasicBlock &MBB) const { 15050b57cec5SDimitry Andric assert(&STI == &MF.getSubtarget<X86Subtarget>() && 15060b57cec5SDimitry Andric "MF used frame lowering for wrong subtarget"); 15070b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI = MBB.begin(); 15080b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 15090b57cec5SDimitry Andric const Function &Fn = MF.getFunction(); 15100b57cec5SDimitry Andric MachineModuleInfo &MMI = MF.getMMI(); 15110b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 15120b57cec5SDimitry Andric uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment. 15130b57cec5SDimitry Andric uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate. 15140b57cec5SDimitry Andric bool IsFunclet = MBB.isEHFuncletEntry(); 15150b57cec5SDimitry Andric EHPersonality Personality = EHPersonality::Unknown; 15160b57cec5SDimitry Andric if (Fn.hasPersonalityFn()) 15170b57cec5SDimitry Andric Personality = classifyEHPersonality(Fn.getPersonalityFn()); 15180b57cec5SDimitry Andric bool FnHasClrFunclet = 15190b57cec5SDimitry Andric MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR; 15200b57cec5SDimitry Andric bool IsClrFunclet = IsFunclet && FnHasClrFunclet; 15210b57cec5SDimitry Andric bool HasFP = hasFP(MF); 1522fe6060f1SDimitry Andric bool IsWin64Prologue = isWin64Prologue(MF); 15230b57cec5SDimitry Andric bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry(); 15240b57cec5SDimitry Andric // FIXME: Emit FPO data for EH funclets. 15250b57cec5SDimitry Andric bool NeedsWinFPO = 15260b57cec5SDimitry Andric !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag(); 15270b57cec5SDimitry Andric bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO; 1528fe6060f1SDimitry Andric bool NeedsDwarfCFI = needsDwarfCFI(MF); 15298bcb0991SDimitry Andric Register FramePtr = TRI->getFrameRegister(MF); 15308bcb0991SDimitry Andric const Register MachineFramePtr = 1531*5f757f3fSDimitry Andric STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64)) 1532*5f757f3fSDimitry Andric : FramePtr; 15338bcb0991SDimitry Andric Register BasePtr = TRI->getBaseRegister(); 15340b57cec5SDimitry Andric bool HasWinCFI = false; 15350b57cec5SDimitry Andric 15360b57cec5SDimitry Andric // Debug location must be unknown since the first debug location is used 15370b57cec5SDimitry Andric // to determine the end of the prologue. 15380b57cec5SDimitry Andric DebugLoc DL; 153906c3fb27SDimitry Andric Register ArgBaseReg; 154006c3fb27SDimitry Andric 154106c3fb27SDimitry Andric // Emit extra prolog for argument stack slot reference. 154206c3fb27SDimitry Andric if (auto *MI = X86FI->getStackPtrSaveMI()) { 154306c3fb27SDimitry Andric // MI is lea instruction that created in X86ArgumentStackSlotPass. 154406c3fb27SDimitry Andric // Creat extra prolog for stack realignment. 154506c3fb27SDimitry Andric ArgBaseReg = MI->getOperand(0).getReg(); 154606c3fb27SDimitry Andric // leal 4(%esp), %basereg 154706c3fb27SDimitry Andric // .cfi_def_cfa %basereg, 0 154806c3fb27SDimitry Andric // andl $-128, %esp 154906c3fb27SDimitry Andric // pushl -4(%basereg) 155006c3fb27SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::LEA64r : X86::LEA32r), 155106c3fb27SDimitry Andric ArgBaseReg) 155206c3fb27SDimitry Andric .addUse(StackPtr) 155306c3fb27SDimitry Andric .addImm(1) 155406c3fb27SDimitry Andric .addUse(X86::NoRegister) 155506c3fb27SDimitry Andric .addImm(SlotSize) 155606c3fb27SDimitry Andric .addUse(X86::NoRegister) 155706c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 155806c3fb27SDimitry Andric if (NeedsDwarfCFI) { 155906c3fb27SDimitry Andric // .cfi_def_cfa %basereg, 0 156006c3fb27SDimitry Andric unsigned DwarfStackPtr = TRI->getDwarfRegNum(ArgBaseReg, true); 156106c3fb27SDimitry Andric BuildCFI(MBB, MBBI, DL, 156206c3fb27SDimitry Andric MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 0), 156306c3fb27SDimitry Andric MachineInstr::FrameSetup); 156406c3fb27SDimitry Andric } 156506c3fb27SDimitry Andric BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign); 156606c3fb27SDimitry Andric int64_t Offset = -(int64_t)SlotSize; 156706c3fb27SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm)) 156806c3fb27SDimitry Andric .addReg(ArgBaseReg) 156906c3fb27SDimitry Andric .addImm(1) 157006c3fb27SDimitry Andric .addReg(X86::NoRegister) 157106c3fb27SDimitry Andric .addImm(Offset) 157206c3fb27SDimitry Andric .addReg(X86::NoRegister) 157306c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 157406c3fb27SDimitry Andric } 15750b57cec5SDimitry Andric 1576349cc55cSDimitry Andric // Space reserved for stack-based arguments when making a (ABI-guaranteed) 1577349cc55cSDimitry Andric // tail call. 1578349cc55cSDimitry Andric unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta(); 1579349cc55cSDimitry Andric if (TailCallArgReserveSize && IsWin64Prologue) 15800b57cec5SDimitry Andric report_fatal_error("Can't handle guaranteed tail call under win64 yet"); 15810b57cec5SDimitry Andric 15825ffd83dbSDimitry Andric const bool EmitStackProbeCall = 15835ffd83dbSDimitry Andric STI.getTargetLowering()->hasStackProbeSymbol(MF); 15848bcb0991SDimitry Andric unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF); 15850b57cec5SDimitry Andric 1586fe6060f1SDimitry Andric if (HasFP && X86FI->hasSwiftAsyncContext()) { 1587349cc55cSDimitry Andric switch (MF.getTarget().Options.SwiftAsyncFramePointer) { 1588349cc55cSDimitry Andric case SwiftAsyncFramePointerMode::DeploymentBased: 1589349cc55cSDimitry Andric if (STI.swiftAsyncContextIsDynamicallySet()) { 1590349cc55cSDimitry Andric // The special symbol below is absolute and has a *value* suitable to be 1591349cc55cSDimitry Andric // combined with the frame pointer directly. 1592349cc55cSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr) 1593349cc55cSDimitry Andric .addUse(MachineFramePtr) 1594349cc55cSDimitry Andric .addUse(X86::RIP) 1595349cc55cSDimitry Andric .addImm(1) 1596349cc55cSDimitry Andric .addUse(X86::NoRegister) 1597349cc55cSDimitry Andric .addExternalSymbol("swift_async_extendedFramePointerFlags", 1598349cc55cSDimitry Andric X86II::MO_GOTPCREL) 1599349cc55cSDimitry Andric .addUse(X86::NoRegister); 1600349cc55cSDimitry Andric break; 1601349cc55cSDimitry Andric } 1602bdd1243dSDimitry Andric [[fallthrough]]; 1603349cc55cSDimitry Andric 1604349cc55cSDimitry Andric case SwiftAsyncFramePointerMode::Always: 1605349cc55cSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr) 1606fe6060f1SDimitry Andric .addUse(MachineFramePtr) 1607fe6060f1SDimitry Andric .addImm(60) 1608fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1609349cc55cSDimitry Andric break; 1610349cc55cSDimitry Andric 1611349cc55cSDimitry Andric case SwiftAsyncFramePointerMode::Never: 1612349cc55cSDimitry Andric break; 1613349cc55cSDimitry Andric } 1614fe6060f1SDimitry Andric } 1615fe6060f1SDimitry Andric 16160b57cec5SDimitry Andric // Re-align the stack on 64-bit if the x86-interrupt calling convention is 16170b57cec5SDimitry Andric // used and an error code was pushed, since the x86-64 ABI requires a 16-byte 16180b57cec5SDimitry Andric // stack alignment. 16190b57cec5SDimitry Andric if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit && 16200b57cec5SDimitry Andric Fn.arg_size() == 2) { 16210b57cec5SDimitry Andric StackSize += 8; 16220b57cec5SDimitry Andric MFI.setStackSize(StackSize); 1623a324c340SDimitry Andric 1624a324c340SDimitry Andric // Update the stack pointer by pushing a register. This is the instruction 1625a324c340SDimitry Andric // emitted that would be end up being emitted by a call to `emitSPUpdate`. 1626a324c340SDimitry Andric // Hard-coding the update to a push avoids emitting a second 1627a324c340SDimitry Andric // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack 1628a324c340SDimitry Andric // probing isn't needed anyways for an 8-byte update. 1629a324c340SDimitry Andric // Pushing a register leaves us in a similar situation to a regular 1630a324c340SDimitry Andric // function call where we know that the address at (rsp-8) is writeable. 1631a324c340SDimitry Andric // That way we avoid any off-by-ones with stack probing for additional 1632a324c340SDimitry Andric // stack pointer updates later on. 1633a324c340SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 1634a324c340SDimitry Andric .addReg(X86::RAX, RegState::Undef) 1635a324c340SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 16360b57cec5SDimitry Andric } 16370b57cec5SDimitry Andric 16380b57cec5SDimitry Andric // If this is x86-64 and the Red Zone is not disabled, if we are a leaf 16390b57cec5SDimitry Andric // function, and use up to 128 bytes of stack space, don't have a frame 16400b57cec5SDimitry Andric // pointer, calls, or dynamic alloca then we do not need to adjust the 16410b57cec5SDimitry Andric // stack pointer (we fit in the Red Zone). We also check that we don't 16420b57cec5SDimitry Andric // push and pop from the stack. 1643fe6060f1SDimitry Andric if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) && 16440b57cec5SDimitry Andric !MFI.hasVarSizedObjects() && // No dynamic alloca. 16450b57cec5SDimitry Andric !MFI.adjustsStack() && // No calls. 16465ffd83dbSDimitry Andric !EmitStackProbeCall && // No stack probes. 16470b57cec5SDimitry Andric !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop. 16480b57cec5SDimitry Andric !MF.shouldSplitStack()) { // Regular stack 1649349cc55cSDimitry Andric uint64_t MinSize = 1650349cc55cSDimitry Andric X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta(); 1651*5f757f3fSDimitry Andric if (HasFP) 1652*5f757f3fSDimitry Andric MinSize += SlotSize; 16530b57cec5SDimitry Andric X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0); 16540b57cec5SDimitry Andric StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0); 16550b57cec5SDimitry Andric MFI.setStackSize(StackSize); 16560b57cec5SDimitry Andric } 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // Insert stack pointer adjustment for later moving of return addr. Only 16590b57cec5SDimitry Andric // applies to tail call optimized functions where the callee argument stack 16600b57cec5SDimitry Andric // size is bigger than the callers. 1661349cc55cSDimitry Andric if (TailCallArgReserveSize != 0) { 1662349cc55cSDimitry Andric BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize, 16630b57cec5SDimitry Andric /*InEpilogue=*/false) 16640b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 16650b57cec5SDimitry Andric } 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric // Mapping for machine moves: 16680b57cec5SDimitry Andric // 16690b57cec5SDimitry Andric // DST: VirtualFP AND 16700b57cec5SDimitry Andric // SRC: VirtualFP => DW_CFA_def_cfa_offset 16710b57cec5SDimitry Andric // ELSE => DW_CFA_def_cfa 16720b57cec5SDimitry Andric // 16730b57cec5SDimitry Andric // SRC: VirtualFP AND 16740b57cec5SDimitry Andric // DST: Register => DW_CFA_def_cfa_register 16750b57cec5SDimitry Andric // 16760b57cec5SDimitry Andric // ELSE 16770b57cec5SDimitry Andric // OFFSET < 0 => DW_CFA_offset_extended_sf 16780b57cec5SDimitry Andric // REG < 64 => DW_CFA_offset + Reg 16790b57cec5SDimitry Andric // ELSE => DW_CFA_offset_extended 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric uint64_t NumBytes = 0; 16820b57cec5SDimitry Andric int stackGrowth = -SlotSize; 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric // Find the funclet establisher parameter 16858bcb0991SDimitry Andric Register Establisher = X86::NoRegister; 16860b57cec5SDimitry Andric if (IsClrFunclet) 16870b57cec5SDimitry Andric Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX; 16880b57cec5SDimitry Andric else if (IsFunclet) 16890b57cec5SDimitry Andric Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX; 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric if (IsWin64Prologue && IsFunclet && !IsClrFunclet) { 16920b57cec5SDimitry Andric // Immediately spill establisher into the home slot. 16930b57cec5SDimitry Andric // The runtime cares about this. 16940b57cec5SDimitry Andric // MOV64mr %rdx, 16(%rsp) 16950b57cec5SDimitry Andric unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 16960b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16) 16970b57cec5SDimitry Andric .addReg(Establisher) 16980b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 16990b57cec5SDimitry Andric MBB.addLiveIn(Establisher); 17000b57cec5SDimitry Andric } 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric if (HasFP) { 17030b57cec5SDimitry Andric assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved"); 17040b57cec5SDimitry Andric 17050b57cec5SDimitry Andric // Calculate required stack adjustment. 17060b57cec5SDimitry Andric uint64_t FrameSize = StackSize - SlotSize; 1707*5f757f3fSDimitry Andric NumBytes = 1708*5f757f3fSDimitry Andric FrameSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize); 17090b57cec5SDimitry Andric 17100b57cec5SDimitry Andric // Callee-saved registers are pushed on stack before the stack is realigned. 1711fe6060f1SDimitry Andric if (TRI->hasStackRealignment(MF) && !IsWin64Prologue) 17120b57cec5SDimitry Andric NumBytes = alignTo(NumBytes, MaxAlign); 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric // Save EBP/RBP into the appropriate stack slot. 1715*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, 1716*5f757f3fSDimitry Andric TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>()))) 17170b57cec5SDimitry Andric .addReg(MachineFramePtr, RegState::Kill) 17180b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 17190b57cec5SDimitry Andric 172006c3fb27SDimitry Andric if (NeedsDwarfCFI && !ArgBaseReg.isValid()) { 17210b57cec5SDimitry Andric // Mark the place where EBP/RBP was saved. 17220b57cec5SDimitry Andric // Define the current CFA rule to use the provided offset. 17230b57cec5SDimitry Andric assert(StackSize); 17240b57cec5SDimitry Andric BuildCFI(MBB, MBBI, DL, 172506c3fb27SDimitry Andric MCCFIInstruction::cfiDefCfaOffset( 172606c3fb27SDimitry Andric nullptr, -2 * stackGrowth + (int)TailCallArgReserveSize), 172781ad6265SDimitry Andric MachineInstr::FrameSetup); 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric // Change the rule for the FramePtr to be an "offset" rule. 17300b57cec5SDimitry Andric unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true); 173181ad6265SDimitry Andric BuildCFI(MBB, MBBI, DL, 173281ad6265SDimitry Andric MCCFIInstruction::createOffset(nullptr, DwarfFramePtr, 173306c3fb27SDimitry Andric 2 * stackGrowth - 173406c3fb27SDimitry Andric (int)TailCallArgReserveSize), 173581ad6265SDimitry Andric MachineInstr::FrameSetup); 17360b57cec5SDimitry Andric } 17370b57cec5SDimitry Andric 17380b57cec5SDimitry Andric if (NeedsWinCFI) { 17390b57cec5SDimitry Andric HasWinCFI = true; 17400b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 17410b57cec5SDimitry Andric .addImm(FramePtr) 17420b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 17430b57cec5SDimitry Andric } 17440b57cec5SDimitry Andric 1745fe6060f1SDimitry Andric if (!IsFunclet) { 1746fe6060f1SDimitry Andric if (X86FI->hasSwiftAsyncContext()) { 1747fe6060f1SDimitry Andric const auto &Attrs = MF.getFunction().getAttributes(); 1748fe6060f1SDimitry Andric 1749fe6060f1SDimitry Andric // Before we update the live frame pointer we have to ensure there's a 1750fe6060f1SDimitry Andric // valid (or null) asynchronous context in its slot just before FP in 1751fe6060f1SDimitry Andric // the frame record, so store it now. 1752fe6060f1SDimitry Andric if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) { 1753fe6060f1SDimitry Andric // We have an initial context in r14, store it just before the frame 1754fe6060f1SDimitry Andric // pointer. 1755fe6060f1SDimitry Andric MBB.addLiveIn(X86::R14); 1756fe6060f1SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 1757fe6060f1SDimitry Andric .addReg(X86::R14) 1758fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1759fe6060f1SDimitry Andric } else { 1760fe6060f1SDimitry Andric // No initial context, store null so that there's no pointer that 1761fe6060f1SDimitry Andric // could be misused. 176206c3fb27SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i32)) 1763fe6060f1SDimitry Andric .addImm(0) 1764fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1765fe6060f1SDimitry Andric } 1766fe6060f1SDimitry Andric 1767fe6060f1SDimitry Andric if (NeedsWinCFI) { 1768fe6060f1SDimitry Andric HasWinCFI = true; 1769fe6060f1SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 1770fe6060f1SDimitry Andric .addImm(X86::R14) 1771fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1772fe6060f1SDimitry Andric } 1773fe6060f1SDimitry Andric 1774fe6060f1SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr) 1775fe6060f1SDimitry Andric .addUse(X86::RSP) 1776fe6060f1SDimitry Andric .addImm(1) 1777fe6060f1SDimitry Andric .addUse(X86::NoRegister) 1778fe6060f1SDimitry Andric .addImm(8) 1779fe6060f1SDimitry Andric .addUse(X86::NoRegister) 1780fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 178106c3fb27SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri32), X86::RSP) 1782fe6060f1SDimitry Andric .addUse(X86::RSP) 1783fe6060f1SDimitry Andric .addImm(8) 1784fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1785fe6060f1SDimitry Andric } 1786fe6060f1SDimitry Andric 17870b57cec5SDimitry Andric if (!IsWin64Prologue && !IsFunclet) { 17880b57cec5SDimitry Andric // Update EBP with the new base value. 1789fe6060f1SDimitry Andric if (!X86FI->hasSwiftAsyncContext()) 17900b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, 17910b57cec5SDimitry Andric TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), 17920b57cec5SDimitry Andric FramePtr) 17930b57cec5SDimitry Andric .addReg(StackPtr) 17940b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric if (NeedsDwarfCFI) { 179706c3fb27SDimitry Andric if (ArgBaseReg.isValid()) { 179806c3fb27SDimitry Andric SmallString<64> CfaExpr; 179906c3fb27SDimitry Andric CfaExpr.push_back(dwarf::DW_CFA_expression); 180006c3fb27SDimitry Andric uint8_t buffer[16]; 180106c3fb27SDimitry Andric unsigned DwarfReg = TRI->getDwarfRegNum(MachineFramePtr, true); 180206c3fb27SDimitry Andric CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer)); 180306c3fb27SDimitry Andric CfaExpr.push_back(2); 180406c3fb27SDimitry Andric CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg)); 180506c3fb27SDimitry Andric CfaExpr.push_back(0); 180606c3fb27SDimitry Andric // DW_CFA_expression: reg5 DW_OP_breg5 +0 180706c3fb27SDimitry Andric BuildCFI(MBB, MBBI, DL, 180806c3fb27SDimitry Andric MCCFIInstruction::createEscape(nullptr, CfaExpr.str()), 180906c3fb27SDimitry Andric MachineInstr::FrameSetup); 181006c3fb27SDimitry Andric } else { 18110b57cec5SDimitry Andric // Mark effective beginning of when frame pointer becomes valid. 18120b57cec5SDimitry Andric // Define the current CFA to use the EBP/RBP register. 18130b57cec5SDimitry Andric unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true); 1814fe6060f1SDimitry Andric BuildCFI( 1815fe6060f1SDimitry Andric MBB, MBBI, DL, 181681ad6265SDimitry Andric MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr), 181781ad6265SDimitry Andric MachineInstr::FrameSetup); 18180b57cec5SDimitry Andric } 181906c3fb27SDimitry Andric } 18200b57cec5SDimitry Andric 18210b57cec5SDimitry Andric if (NeedsWinFPO) { 18220b57cec5SDimitry Andric // .cv_fpo_setframe $FramePtr 18230b57cec5SDimitry Andric HasWinCFI = true; 18240b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame)) 18250b57cec5SDimitry Andric .addImm(FramePtr) 18260b57cec5SDimitry Andric .addImm(0) 18270b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 18280b57cec5SDimitry Andric } 18290b57cec5SDimitry Andric } 1830fe6060f1SDimitry Andric } 18310b57cec5SDimitry Andric } else { 18320b57cec5SDimitry Andric assert(!IsFunclet && "funclets without FPs not yet implemented"); 1833*5f757f3fSDimitry Andric NumBytes = 1834*5f757f3fSDimitry Andric StackSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize); 18350b57cec5SDimitry Andric } 18360b57cec5SDimitry Andric 18370b57cec5SDimitry Andric // Update the offset adjustment, which is mainly used by codeview to translate 18380b57cec5SDimitry Andric // from ESP to VFRAME relative local variable offsets. 18390b57cec5SDimitry Andric if (!IsFunclet) { 1840fe6060f1SDimitry Andric if (HasFP && TRI->hasStackRealignment(MF)) 18410b57cec5SDimitry Andric MFI.setOffsetAdjustment(-NumBytes); 18420b57cec5SDimitry Andric else 18430b57cec5SDimitry Andric MFI.setOffsetAdjustment(-StackSize); 18440b57cec5SDimitry Andric } 18450b57cec5SDimitry Andric 18460b57cec5SDimitry Andric // For EH funclets, only allocate enough space for outgoing calls. Save the 18470b57cec5SDimitry Andric // NumBytes value that we would've used for the parent frame. 18480b57cec5SDimitry Andric unsigned ParentFrameNumBytes = NumBytes; 18490b57cec5SDimitry Andric if (IsFunclet) 18500b57cec5SDimitry Andric NumBytes = getWinEHFuncletFrameSize(MF); 18510b57cec5SDimitry Andric 18520b57cec5SDimitry Andric // Skip the callee-saved push instructions. 18530b57cec5SDimitry Andric bool PushedRegs = false; 18540b57cec5SDimitry Andric int StackOffset = 2 * stackGrowth; 1855*5f757f3fSDimitry Andric MachineBasicBlock::const_iterator LastCSPush = MBBI; 1856*5f757f3fSDimitry Andric auto IsCSPush = [&](const MachineBasicBlock::iterator &MBBI) { 1857*5f757f3fSDimitry Andric if (MBBI == MBB.end() || !MBBI->getFlag(MachineInstr::FrameSetup)) 1858*5f757f3fSDimitry Andric return false; 1859*5f757f3fSDimitry Andric unsigned Opc = MBBI->getOpcode(); 1860*5f757f3fSDimitry Andric return Opc == X86::PUSH32r || Opc == X86::PUSH64r || Opc == X86::PUSHP64r || 1861*5f757f3fSDimitry Andric Opc == X86::PUSH2 || Opc == X86::PUSH2P; 1862*5f757f3fSDimitry Andric }; 18630b57cec5SDimitry Andric 1864*5f757f3fSDimitry Andric while (IsCSPush(MBBI)) { 18650b57cec5SDimitry Andric PushedRegs = true; 18668bcb0991SDimitry Andric Register Reg = MBBI->getOperand(0).getReg(); 1867*5f757f3fSDimitry Andric LastCSPush = MBBI; 18680b57cec5SDimitry Andric ++MBBI; 1869*5f757f3fSDimitry Andric unsigned Opc = LastCSPush->getOpcode(); 18700b57cec5SDimitry Andric 18710b57cec5SDimitry Andric if (!HasFP && NeedsDwarfCFI) { 18720b57cec5SDimitry Andric // Mark callee-saved push instruction. 18730b57cec5SDimitry Andric // Define the current CFA rule to use the provided offset. 18740b57cec5SDimitry Andric assert(StackSize); 1875*5f757f3fSDimitry Andric // Compared to push, push2 introduces more stack offset (one more 1876*5f757f3fSDimitry Andric // register). 1877*5f757f3fSDimitry Andric if (Opc == X86::PUSH2 || Opc == X86::PUSH2P) 1878*5f757f3fSDimitry Andric StackOffset += stackGrowth; 18790b57cec5SDimitry Andric BuildCFI(MBB, MBBI, DL, 188081ad6265SDimitry Andric MCCFIInstruction::cfiDefCfaOffset(nullptr, -StackOffset), 188181ad6265SDimitry Andric MachineInstr::FrameSetup); 18820b57cec5SDimitry Andric StackOffset += stackGrowth; 18830b57cec5SDimitry Andric } 18840b57cec5SDimitry Andric 18850b57cec5SDimitry Andric if (NeedsWinCFI) { 18860b57cec5SDimitry Andric HasWinCFI = true; 18870b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 18880b57cec5SDimitry Andric .addImm(Reg) 18890b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 1890*5f757f3fSDimitry Andric if (Opc == X86::PUSH2 || Opc == X86::PUSH2P) 1891*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 1892*5f757f3fSDimitry Andric .addImm(LastCSPush->getOperand(1).getReg()) 1893*5f757f3fSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 18940b57cec5SDimitry Andric } 18950b57cec5SDimitry Andric } 18960b57cec5SDimitry Andric 18970b57cec5SDimitry Andric // Realign stack after we pushed callee-saved registers (so that we'll be 18980b57cec5SDimitry Andric // able to calculate their offsets from the frame pointer). 18990b57cec5SDimitry Andric // Don't do this for Win64, it needs to realign the stack after the prologue. 190006c3fb27SDimitry Andric if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) && 190106c3fb27SDimitry Andric !ArgBaseReg.isValid()) { 19020b57cec5SDimitry Andric assert(HasFP && "There should be a frame pointer if stack is realigned."); 19030b57cec5SDimitry Andric BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign); 19040b57cec5SDimitry Andric 19050b57cec5SDimitry Andric if (NeedsWinCFI) { 19060b57cec5SDimitry Andric HasWinCFI = true; 19070b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign)) 19080b57cec5SDimitry Andric .addImm(MaxAlign) 19090b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19100b57cec5SDimitry Andric } 19110b57cec5SDimitry Andric } 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric // If there is an SUB32ri of ESP immediately before this instruction, merge 19140b57cec5SDimitry Andric // the two. This can be the case when tail call elimination is enabled and 19150b57cec5SDimitry Andric // the callee has more arguments then the caller. 19160b57cec5SDimitry Andric NumBytes -= mergeSPUpdates(MBB, MBBI, true); 19170b57cec5SDimitry Andric 19180b57cec5SDimitry Andric // Adjust stack pointer: ESP -= numbytes. 19190b57cec5SDimitry Andric 19200b57cec5SDimitry Andric // Windows and cygwin/mingw require a prologue helper routine when allocating 19210b57cec5SDimitry Andric // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw 19220b57cec5SDimitry Andric // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the 19230b57cec5SDimitry Andric // stack and adjust the stack pointer in one go. The 64-bit version of 19240b57cec5SDimitry Andric // __chkstk is only responsible for probing the stack. The 64-bit prologue is 19250b57cec5SDimitry Andric // responsible for adjusting the stack pointer. Touching the stack at 4K 19260b57cec5SDimitry Andric // increments is necessary to ensure that the guard pages used by the OS 19270b57cec5SDimitry Andric // virtual memory manager are allocated in correct sequence. 19280b57cec5SDimitry Andric uint64_t AlignedNumBytes = NumBytes; 1929fe6060f1SDimitry Andric if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF)) 19300b57cec5SDimitry Andric AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign); 19315ffd83dbSDimitry Andric if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) { 19320b57cec5SDimitry Andric assert(!X86FI->getUsesRedZone() && 19330b57cec5SDimitry Andric "The Red Zone is not accounted for in stack probes"); 19340b57cec5SDimitry Andric 19350b57cec5SDimitry Andric // Check whether EAX is livein for this block. 19360b57cec5SDimitry Andric bool isEAXAlive = isEAXLiveIn(MBB); 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric if (isEAXAlive) { 19390b57cec5SDimitry Andric if (Is64Bit) { 19400b57cec5SDimitry Andric // Save RAX 19410b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 19420b57cec5SDimitry Andric .addReg(X86::RAX, RegState::Kill) 19430b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19440b57cec5SDimitry Andric } else { 19450b57cec5SDimitry Andric // Save EAX 19460b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r)) 19470b57cec5SDimitry Andric .addReg(X86::EAX, RegState::Kill) 19480b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19490b57cec5SDimitry Andric } 19500b57cec5SDimitry Andric } 19510b57cec5SDimitry Andric 19520b57cec5SDimitry Andric if (Is64Bit) { 19530b57cec5SDimitry Andric // Handle the 64-bit Windows ABI case where we need to call __chkstk. 19540b57cec5SDimitry Andric // Function prologue is responsible for adjusting the stack pointer. 1955480093f4SDimitry Andric int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes; 195604eeddc0SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Alloc)), X86::RAX) 19570b57cec5SDimitry Andric .addImm(Alloc) 19580b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19590b57cec5SDimitry Andric } else { 19600b57cec5SDimitry Andric // Allocate NumBytes-4 bytes on stack in case of isEAXAlive. 19610b57cec5SDimitry Andric // We'll also use 4 already allocated bytes for EAX. 19620b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) 19630b57cec5SDimitry Andric .addImm(isEAXAlive ? NumBytes - 4 : NumBytes) 19640b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19650b57cec5SDimitry Andric } 19660b57cec5SDimitry Andric 19670b57cec5SDimitry Andric // Call __chkstk, __chkstk_ms, or __alloca. 19680b57cec5SDimitry Andric emitStackProbe(MF, MBB, MBBI, DL, true); 19690b57cec5SDimitry Andric 19700b57cec5SDimitry Andric if (isEAXAlive) { 19710b57cec5SDimitry Andric // Restore RAX/EAX 19720b57cec5SDimitry Andric MachineInstr *MI; 19730b57cec5SDimitry Andric if (Is64Bit) 19740b57cec5SDimitry Andric MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX), 19750b57cec5SDimitry Andric StackPtr, false, NumBytes - 8); 19760b57cec5SDimitry Andric else 19770b57cec5SDimitry Andric MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX), 19780b57cec5SDimitry Andric StackPtr, false, NumBytes - 4); 19790b57cec5SDimitry Andric MI->setFlag(MachineInstr::FrameSetup); 19800b57cec5SDimitry Andric MBB.insert(MBBI, MI); 19810b57cec5SDimitry Andric } 19820b57cec5SDimitry Andric } else if (NumBytes) { 19830b57cec5SDimitry Andric emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false); 19840b57cec5SDimitry Andric } 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric if (NeedsWinCFI && NumBytes) { 19870b57cec5SDimitry Andric HasWinCFI = true; 19880b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc)) 19890b57cec5SDimitry Andric .addImm(NumBytes) 19900b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric int SEHFrameOffset = 0; 19940b57cec5SDimitry Andric unsigned SPOrEstablisher; 19950b57cec5SDimitry Andric if (IsFunclet) { 19960b57cec5SDimitry Andric if (IsClrFunclet) { 19970b57cec5SDimitry Andric // The establisher parameter passed to a CLR funclet is actually a pointer 19980b57cec5SDimitry Andric // to the (mostly empty) frame of its nearest enclosing funclet; we have 19990b57cec5SDimitry Andric // to find the root function establisher frame by loading the PSPSym from 20000b57cec5SDimitry Andric // the intermediate frame. 20010b57cec5SDimitry Andric unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF); 20020b57cec5SDimitry Andric MachinePointerInfo NoInfo; 20030b57cec5SDimitry Andric MBB.addLiveIn(Establisher); 20040b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher), 20050b57cec5SDimitry Andric Establisher, false, PSPSlotOffset) 20060b57cec5SDimitry Andric .addMemOperand(MF.getMachineMemOperand( 20075ffd83dbSDimitry Andric NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize))); 20080b57cec5SDimitry Andric ; 20090b57cec5SDimitry Andric // Save the root establisher back into the current funclet's (mostly 20100b57cec5SDimitry Andric // empty) frame, in case a sub-funclet or the GC needs it. 20110b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, 20120b57cec5SDimitry Andric false, PSPSlotOffset) 20130b57cec5SDimitry Andric .addReg(Establisher) 20145ffd83dbSDimitry Andric .addMemOperand(MF.getMachineMemOperand( 20155ffd83dbSDimitry Andric NoInfo, 20165ffd83dbSDimitry Andric MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 20175ffd83dbSDimitry Andric SlotSize, Align(SlotSize))); 20180b57cec5SDimitry Andric } 20190b57cec5SDimitry Andric SPOrEstablisher = Establisher; 20200b57cec5SDimitry Andric } else { 20210b57cec5SDimitry Andric SPOrEstablisher = StackPtr; 20220b57cec5SDimitry Andric } 20230b57cec5SDimitry Andric 20240b57cec5SDimitry Andric if (IsWin64Prologue && HasFP) { 20250b57cec5SDimitry Andric // Set RBP to a small fixed offset from RSP. In the funclet case, we base 20260b57cec5SDimitry Andric // this calculation on the incoming establisher, which holds the value of 20270b57cec5SDimitry Andric // RSP from the parent frame at the end of the prologue. 20280b57cec5SDimitry Andric SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes); 20290b57cec5SDimitry Andric if (SEHFrameOffset) 20300b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr), 20310b57cec5SDimitry Andric SPOrEstablisher, false, SEHFrameOffset); 20320b57cec5SDimitry Andric else 20330b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr) 20340b57cec5SDimitry Andric .addReg(SPOrEstablisher); 20350b57cec5SDimitry Andric 20360b57cec5SDimitry Andric // If this is not a funclet, emit the CFI describing our frame pointer. 20370b57cec5SDimitry Andric if (NeedsWinCFI && !IsFunclet) { 20380b57cec5SDimitry Andric assert(!NeedsWinFPO && "this setframe incompatible with FPO data"); 20390b57cec5SDimitry Andric HasWinCFI = true; 20400b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame)) 20410b57cec5SDimitry Andric .addImm(FramePtr) 20420b57cec5SDimitry Andric .addImm(SEHFrameOffset) 20430b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 20440b57cec5SDimitry Andric if (isAsynchronousEHPersonality(Personality)) 20450b57cec5SDimitry Andric MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset; 20460b57cec5SDimitry Andric } 20470b57cec5SDimitry Andric } else if (IsFunclet && STI.is32Bit()) { 20480b57cec5SDimitry Andric // Reset EBP / ESI to something good for funclets. 20490b57cec5SDimitry Andric MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL); 20500b57cec5SDimitry Andric // If we're a catch funclet, we can be returned to via catchret. Save ESP 20510b57cec5SDimitry Andric // into the registration node so that the runtime will restore it for us. 20520b57cec5SDimitry Andric if (!MBB.isCleanupFuncletEntry()) { 20530b57cec5SDimitry Andric assert(Personality == EHPersonality::MSVC_CXX); 20545ffd83dbSDimitry Andric Register FrameReg; 20550b57cec5SDimitry Andric int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex; 2056e8d8bef9SDimitry Andric int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed(); 20570b57cec5SDimitry Andric // ESP is the first field, so no extra displacement is needed. 20580b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg, 20590b57cec5SDimitry Andric false, EHRegOffset) 20600b57cec5SDimitry Andric .addReg(X86::ESP); 20610b57cec5SDimitry Andric } 20620b57cec5SDimitry Andric } 20630b57cec5SDimitry Andric 20640b57cec5SDimitry Andric while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) { 20650b57cec5SDimitry Andric const MachineInstr &FrameInstr = *MBBI; 20660b57cec5SDimitry Andric ++MBBI; 20670b57cec5SDimitry Andric 20680b57cec5SDimitry Andric if (NeedsWinCFI) { 20690b57cec5SDimitry Andric int FI; 20700b57cec5SDimitry Andric if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) { 20710b57cec5SDimitry Andric if (X86::FR64RegClass.contains(Reg)) { 2072c14a5a88SDimitry Andric int Offset; 20735ffd83dbSDimitry Andric Register IgnoredFrameReg; 2074c14a5a88SDimitry Andric if (IsWin64Prologue && IsFunclet) 2075c14a5a88SDimitry Andric Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg); 2076c14a5a88SDimitry Andric else 2077e8d8bef9SDimitry Andric Offset = 2078e8d8bef9SDimitry Andric getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() + 2079c14a5a88SDimitry Andric SEHFrameOffset; 20800b57cec5SDimitry Andric 20810b57cec5SDimitry Andric HasWinCFI = true; 20820b57cec5SDimitry Andric assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data"); 20830b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM)) 20840b57cec5SDimitry Andric .addImm(Reg) 20850b57cec5SDimitry Andric .addImm(Offset) 20860b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 20870b57cec5SDimitry Andric } 20880b57cec5SDimitry Andric } 20890b57cec5SDimitry Andric } 20900b57cec5SDimitry Andric } 20910b57cec5SDimitry Andric 20920b57cec5SDimitry Andric if (NeedsWinCFI && HasWinCFI) 20930b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue)) 20940b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 20950b57cec5SDimitry Andric 20960b57cec5SDimitry Andric if (FnHasClrFunclet && !IsFunclet) { 20970b57cec5SDimitry Andric // Save the so-called Initial-SP (i.e. the value of the stack pointer 20980b57cec5SDimitry Andric // immediately after the prolog) into the PSPSlot so that funclets 20990b57cec5SDimitry Andric // and the GC can recover it. 21000b57cec5SDimitry Andric unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF); 21010b57cec5SDimitry Andric auto PSPInfo = MachinePointerInfo::getFixedStack( 21020b57cec5SDimitry Andric MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx); 21030b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false, 21040b57cec5SDimitry Andric PSPSlotOffset) 21050b57cec5SDimitry Andric .addReg(StackPtr) 21060b57cec5SDimitry Andric .addMemOperand(MF.getMachineMemOperand( 21070b57cec5SDimitry Andric PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 21085ffd83dbSDimitry Andric SlotSize, Align(SlotSize))); 21090b57cec5SDimitry Andric } 21100b57cec5SDimitry Andric 21110b57cec5SDimitry Andric // Realign stack after we spilled callee-saved registers (so that we'll be 21120b57cec5SDimitry Andric // able to calculate their offsets from the frame pointer). 21130b57cec5SDimitry Andric // Win64 requires aligning the stack after the prologue. 2114fe6060f1SDimitry Andric if (IsWin64Prologue && TRI->hasStackRealignment(MF)) { 21150b57cec5SDimitry Andric assert(HasFP && "There should be a frame pointer if stack is realigned."); 21160b57cec5SDimitry Andric BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign); 21170b57cec5SDimitry Andric } 21180b57cec5SDimitry Andric 21190b57cec5SDimitry Andric // We already dealt with stack realignment and funclets above. 21200b57cec5SDimitry Andric if (IsFunclet && STI.is32Bit()) 21210b57cec5SDimitry Andric return; 21220b57cec5SDimitry Andric 21230b57cec5SDimitry Andric // If we need a base pointer, set it up here. It's whatever the value 21240b57cec5SDimitry Andric // of the stack pointer is at this point. Any variable size objects 21250b57cec5SDimitry Andric // will be allocated after this, so we can still use the base pointer 21260b57cec5SDimitry Andric // to reference locals. 21270b57cec5SDimitry Andric if (TRI->hasBasePointer(MF)) { 21280b57cec5SDimitry Andric // Update the base pointer with the current stack pointer. 21290b57cec5SDimitry Andric unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr; 21300b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr) 21310b57cec5SDimitry Andric .addReg(SPOrEstablisher) 21320b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 21330b57cec5SDimitry Andric if (X86FI->getRestoreBasePointer()) { 21340b57cec5SDimitry Andric // Stash value of base pointer. Saving RSP instead of EBP shortens 21350b57cec5SDimitry Andric // dependence chain. Used by SjLj EH. 21360b57cec5SDimitry Andric unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 2137*5f757f3fSDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), FramePtr, true, 2138*5f757f3fSDimitry Andric X86FI->getRestoreBasePointerOffset()) 21390b57cec5SDimitry Andric .addReg(SPOrEstablisher) 21400b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 21410b57cec5SDimitry Andric } 21420b57cec5SDimitry Andric 21430b57cec5SDimitry Andric if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) { 21440b57cec5SDimitry Andric // Stash the value of the frame pointer relative to the base pointer for 21450b57cec5SDimitry Andric // Win32 EH. This supports Win32 EH, which does the inverse of the above: 21460b57cec5SDimitry Andric // it recovers the frame pointer from the base pointer rather than the 21470b57cec5SDimitry Andric // other way around. 21480b57cec5SDimitry Andric unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 21495ffd83dbSDimitry Andric Register UsedReg; 21500b57cec5SDimitry Andric int Offset = 2151e8d8bef9SDimitry Andric getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg) 2152e8d8bef9SDimitry Andric .getFixed(); 21530b57cec5SDimitry Andric assert(UsedReg == BasePtr); 21540b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset) 21550b57cec5SDimitry Andric .addReg(FramePtr) 21560b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 21570b57cec5SDimitry Andric } 21580b57cec5SDimitry Andric } 215906c3fb27SDimitry Andric if (ArgBaseReg.isValid()) { 216006c3fb27SDimitry Andric // Save argument base pointer. 216106c3fb27SDimitry Andric auto *MI = X86FI->getStackPtrSaveMI(); 216206c3fb27SDimitry Andric int FI = MI->getOperand(1).getIndex(); 216306c3fb27SDimitry Andric unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr; 216406c3fb27SDimitry Andric // movl %basereg, offset(%ebp) 216506c3fb27SDimitry Andric addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), FI) 216606c3fb27SDimitry Andric .addReg(ArgBaseReg) 216706c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 216806c3fb27SDimitry Andric } 21690b57cec5SDimitry Andric 21700b57cec5SDimitry Andric if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) { 21710b57cec5SDimitry Andric // Mark end of stack pointer adjustment. 21720b57cec5SDimitry Andric if (!HasFP && NumBytes) { 21730b57cec5SDimitry Andric // Define the current CFA rule to use the provided offset. 21740b57cec5SDimitry Andric assert(StackSize); 21755ffd83dbSDimitry Andric BuildCFI( 21765ffd83dbSDimitry Andric MBB, MBBI, DL, 217781ad6265SDimitry Andric MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth), 217881ad6265SDimitry Andric MachineInstr::FrameSetup); 21790b57cec5SDimitry Andric } 21800b57cec5SDimitry Andric 21810b57cec5SDimitry Andric // Emit DWARF info specifying the offsets of the callee-saved registers. 21825ffd83dbSDimitry Andric emitCalleeSavedFrameMoves(MBB, MBBI, DL, true); 21830b57cec5SDimitry Andric } 21840b57cec5SDimitry Andric 21850b57cec5SDimitry Andric // X86 Interrupt handling function cannot assume anything about the direction 21860b57cec5SDimitry Andric // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction 21870b57cec5SDimitry Andric // in each prologue of interrupt handler function. 21880b57cec5SDimitry Andric // 21890b57cec5SDimitry Andric // FIXME: Create "cld" instruction only in these cases: 21900b57cec5SDimitry Andric // 1. The interrupt handling function uses any of the "rep" instructions. 21910b57cec5SDimitry Andric // 2. Interrupt handling function calls another function. 21920b57cec5SDimitry Andric // 21930b57cec5SDimitry Andric if (Fn.getCallingConv() == CallingConv::X86_INTR) 21940b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::CLD)) 21950b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 21960b57cec5SDimitry Andric 21970b57cec5SDimitry Andric // At this point we know if the function has WinCFI or not. 21980b57cec5SDimitry Andric MF.setHasWinCFI(HasWinCFI); 21990b57cec5SDimitry Andric } 22000b57cec5SDimitry Andric 22010b57cec5SDimitry Andric bool X86FrameLowering::canUseLEAForSPInEpilogue( 22020b57cec5SDimitry Andric const MachineFunction &MF) const { 22030b57cec5SDimitry Andric // We can't use LEA instructions for adjusting the stack pointer if we don't 22040b57cec5SDimitry Andric // have a frame pointer in the Win64 ABI. Only ADD instructions may be used 22050b57cec5SDimitry Andric // to deallocate the stack. 22060b57cec5SDimitry Andric // This means that we can use LEA for SP in two situations: 22070b57cec5SDimitry Andric // 1. We *aren't* using the Win64 ABI which means we are free to use LEA. 22080b57cec5SDimitry Andric // 2. We *have* a frame pointer which means we are permitted to use LEA. 22090b57cec5SDimitry Andric return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF); 22100b57cec5SDimitry Andric } 22110b57cec5SDimitry Andric 22120b57cec5SDimitry Andric static bool isFuncletReturnInstr(MachineInstr &MI) { 22130b57cec5SDimitry Andric switch (MI.getOpcode()) { 22140b57cec5SDimitry Andric case X86::CATCHRET: 22150b57cec5SDimitry Andric case X86::CLEANUPRET: 22160b57cec5SDimitry Andric return true; 22170b57cec5SDimitry Andric default: 22180b57cec5SDimitry Andric return false; 22190b57cec5SDimitry Andric } 22200b57cec5SDimitry Andric llvm_unreachable("impossible"); 22210b57cec5SDimitry Andric } 22220b57cec5SDimitry Andric 22230b57cec5SDimitry Andric // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the 22240b57cec5SDimitry Andric // stack. It holds a pointer to the bottom of the root function frame. The 22250b57cec5SDimitry Andric // establisher frame pointer passed to a nested funclet may point to the 22260b57cec5SDimitry Andric // (mostly empty) frame of its parent funclet, but it will need to find 22270b57cec5SDimitry Andric // the frame of the root function to access locals. To facilitate this, 22280b57cec5SDimitry Andric // every funclet copies the pointer to the bottom of the root function 22290b57cec5SDimitry Andric // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the 22300b57cec5SDimitry Andric // same offset for the PSPSym in the root function frame that's used in the 22310b57cec5SDimitry Andric // funclets' frames allows each funclet to dynamically accept any ancestor 22320b57cec5SDimitry Andric // frame as its establisher argument (the runtime doesn't guarantee the 22330b57cec5SDimitry Andric // immediate parent for some reason lost to history), and also allows the GC, 22340b57cec5SDimitry Andric // which uses the PSPSym for some bookkeeping, to find it in any funclet's 22350b57cec5SDimitry Andric // frame with only a single offset reported for the entire method. 22360b57cec5SDimitry Andric unsigned 22370b57cec5SDimitry Andric X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const { 22380b57cec5SDimitry Andric const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo(); 22395ffd83dbSDimitry Andric Register SPReg; 22400b57cec5SDimitry Andric int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg, 2241e8d8bef9SDimitry Andric /*IgnoreSPUpdates*/ true) 2242e8d8bef9SDimitry Andric .getFixed(); 22430b57cec5SDimitry Andric assert(Offset >= 0 && SPReg == TRI->getStackRegister()); 22440b57cec5SDimitry Andric return static_cast<unsigned>(Offset); 22450b57cec5SDimitry Andric } 22460b57cec5SDimitry Andric 22470b57cec5SDimitry Andric unsigned 22480b57cec5SDimitry Andric X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const { 2249c14a5a88SDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 22500b57cec5SDimitry Andric // This is the size of the pushed CSRs. 2251c14a5a88SDimitry Andric unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 2252c14a5a88SDimitry Andric // This is the size of callee saved XMMs. 2253c14a5a88SDimitry Andric const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 2254*5f757f3fSDimitry Andric unsigned XMMSize = 2255*5f757f3fSDimitry Andric WinEHXMMSlotInfo.size() * TRI->getSpillSize(X86::VR128RegClass); 22560b57cec5SDimitry Andric // This is the amount of stack a funclet needs to allocate. 22570b57cec5SDimitry Andric unsigned UsedSize; 22580b57cec5SDimitry Andric EHPersonality Personality = 22590b57cec5SDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn()); 22600b57cec5SDimitry Andric if (Personality == EHPersonality::CoreCLR) { 22610b57cec5SDimitry Andric // CLR funclets need to hold enough space to include the PSPSym, at the 22620b57cec5SDimitry Andric // same offset from the stack pointer (immediately after the prolog) as it 22630b57cec5SDimitry Andric // resides at in the main function. 22640b57cec5SDimitry Andric UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize; 22650b57cec5SDimitry Andric } else { 22660b57cec5SDimitry Andric // Other funclets just need enough stack for outgoing call arguments. 22670b57cec5SDimitry Andric UsedSize = MF.getFrameInfo().getMaxCallFrameSize(); 22680b57cec5SDimitry Andric } 22690b57cec5SDimitry Andric // RBP is not included in the callee saved register block. After pushing RBP, 22700b57cec5SDimitry Andric // everything is 16 byte aligned. Everything we allocate before an outgoing 22710b57cec5SDimitry Andric // call must also be 16 byte aligned. 22725ffd83dbSDimitry Andric unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign()); 22730b57cec5SDimitry Andric // Subtract out the size of the callee saved registers. This is how much stack 22740b57cec5SDimitry Andric // each funclet will allocate. 2275c14a5a88SDimitry Andric return FrameSizeMinusRBP + XMMSize - CSSize; 22760b57cec5SDimitry Andric } 22770b57cec5SDimitry Andric 22780b57cec5SDimitry Andric static bool isTailCallOpcode(unsigned Opc) { 22790b57cec5SDimitry Andric return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi || 2280*5f757f3fSDimitry Andric Opc == X86::TCRETURNmi || Opc == X86::TCRETURNri64 || 2281*5f757f3fSDimitry Andric Opc == X86::TCRETURNdi64 || Opc == X86::TCRETURNmi64; 22820b57cec5SDimitry Andric } 22830b57cec5SDimitry Andric 22840b57cec5SDimitry Andric void X86FrameLowering::emitEpilogue(MachineFunction &MF, 22850b57cec5SDimitry Andric MachineBasicBlock &MBB) const { 22860b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 22870b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 22880b57cec5SDimitry Andric MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator(); 22890b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI = Terminator; 22900b57cec5SDimitry Andric DebugLoc DL; 22910b57cec5SDimitry Andric if (MBBI != MBB.end()) 22920b57cec5SDimitry Andric DL = MBBI->getDebugLoc(); 22930b57cec5SDimitry Andric // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. 22940b57cec5SDimitry Andric const bool Is64BitILP32 = STI.isTarget64BitILP32(); 22958bcb0991SDimitry Andric Register FramePtr = TRI->getFrameRegister(MF); 2296e8d8bef9SDimitry Andric Register MachineFramePtr = 22978bcb0991SDimitry Andric Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr; 22980b57cec5SDimitry Andric 22990b57cec5SDimitry Andric bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 23000b57cec5SDimitry Andric bool NeedsWin64CFI = 23010b57cec5SDimitry Andric IsWin64Prologue && MF.getFunction().needsUnwindTableEntry(); 23020b57cec5SDimitry Andric bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI); 23030b57cec5SDimitry Andric 23040b57cec5SDimitry Andric // Get the number of bytes to allocate from the FrameInfo. 23050b57cec5SDimitry Andric uint64_t StackSize = MFI.getStackSize(); 23060b57cec5SDimitry Andric uint64_t MaxAlign = calculateMaxStackAlign(MF); 23070b57cec5SDimitry Andric unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 2308349cc55cSDimitry Andric unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta(); 23090b57cec5SDimitry Andric bool HasFP = hasFP(MF); 23100b57cec5SDimitry Andric uint64_t NumBytes = 0; 23110b57cec5SDimitry Andric 2312480093f4SDimitry Andric bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() && 23130b57cec5SDimitry Andric !MF.getTarget().getTargetTriple().isOSWindows()) && 2314480093f4SDimitry Andric MF.needsFrameMoves(); 23150b57cec5SDimitry Andric 231606c3fb27SDimitry Andric Register ArgBaseReg; 231706c3fb27SDimitry Andric if (auto *MI = X86FI->getStackPtrSaveMI()) { 231806c3fb27SDimitry Andric unsigned Opc = X86::LEA32r; 231906c3fb27SDimitry Andric Register StackReg = X86::ESP; 232006c3fb27SDimitry Andric ArgBaseReg = MI->getOperand(0).getReg(); 232106c3fb27SDimitry Andric if (STI.is64Bit()) { 232206c3fb27SDimitry Andric Opc = X86::LEA64r; 232306c3fb27SDimitry Andric StackReg = X86::RSP; 232406c3fb27SDimitry Andric } 232506c3fb27SDimitry Andric // leal -4(%basereg), %esp 232606c3fb27SDimitry Andric // .cfi_def_cfa %esp, 4 232706c3fb27SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Opc), StackReg) 232806c3fb27SDimitry Andric .addUse(ArgBaseReg) 232906c3fb27SDimitry Andric .addImm(1) 233006c3fb27SDimitry Andric .addUse(X86::NoRegister) 233106c3fb27SDimitry Andric .addImm(-(int64_t)SlotSize) 233206c3fb27SDimitry Andric .addUse(X86::NoRegister) 233306c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 233406c3fb27SDimitry Andric if (NeedsDwarfCFI) { 233506c3fb27SDimitry Andric unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackReg, true); 233606c3fb27SDimitry Andric BuildCFI(MBB, MBBI, DL, 233706c3fb27SDimitry Andric MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize), 233806c3fb27SDimitry Andric MachineInstr::FrameDestroy); 233906c3fb27SDimitry Andric --MBBI; 234006c3fb27SDimitry Andric } 234106c3fb27SDimitry Andric --MBBI; 234206c3fb27SDimitry Andric } 234306c3fb27SDimitry Andric 23440b57cec5SDimitry Andric if (IsFunclet) { 23450b57cec5SDimitry Andric assert(HasFP && "EH funclets without FP not yet implemented"); 23460b57cec5SDimitry Andric NumBytes = getWinEHFuncletFrameSize(MF); 23470b57cec5SDimitry Andric } else if (HasFP) { 23480b57cec5SDimitry Andric // Calculate required stack adjustment. 23490b57cec5SDimitry Andric uint64_t FrameSize = StackSize - SlotSize; 2350349cc55cSDimitry Andric NumBytes = FrameSize - CSSize - TailCallArgReserveSize; 23510b57cec5SDimitry Andric 23520b57cec5SDimitry Andric // Callee-saved registers were pushed on stack before the stack was 23530b57cec5SDimitry Andric // realigned. 2354fe6060f1SDimitry Andric if (TRI->hasStackRealignment(MF) && !IsWin64Prologue) 23550b57cec5SDimitry Andric NumBytes = alignTo(FrameSize, MaxAlign); 23560b57cec5SDimitry Andric } else { 2357349cc55cSDimitry Andric NumBytes = StackSize - CSSize - TailCallArgReserveSize; 23580b57cec5SDimitry Andric } 23590b57cec5SDimitry Andric uint64_t SEHStackAllocAmt = NumBytes; 23600b57cec5SDimitry Andric 23615ffd83dbSDimitry Andric // AfterPop is the position to insert .cfi_restore. 23625ffd83dbSDimitry Andric MachineBasicBlock::iterator AfterPop = MBBI; 23630b57cec5SDimitry Andric if (HasFP) { 2364fe6060f1SDimitry Andric if (X86FI->hasSwiftAsyncContext()) { 2365fe6060f1SDimitry Andric // Discard the context. 2366fe6060f1SDimitry Andric int Offset = 16 + mergeSPUpdates(MBB, MBBI, true); 2367fe6060f1SDimitry Andric emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/ true); 2368fe6060f1SDimitry Andric } 23690b57cec5SDimitry Andric // Pop EBP. 2370*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, 2371*5f757f3fSDimitry Andric TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())), 23720b57cec5SDimitry Andric MachineFramePtr) 23730b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 2374fe6060f1SDimitry Andric 2375fe6060f1SDimitry Andric // We need to reset FP to its untagged state on return. Bit 60 is currently 2376fe6060f1SDimitry Andric // used to show the presence of an extended frame. 2377fe6060f1SDimitry Andric if (X86FI->hasSwiftAsyncContext()) { 2378*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8), MachineFramePtr) 2379fe6060f1SDimitry Andric .addUse(MachineFramePtr) 2380fe6060f1SDimitry Andric .addImm(60) 2381fe6060f1SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 2382fe6060f1SDimitry Andric } 2383fe6060f1SDimitry Andric 23840b57cec5SDimitry Andric if (NeedsDwarfCFI) { 238506c3fb27SDimitry Andric if (!ArgBaseReg.isValid()) { 23860b57cec5SDimitry Andric unsigned DwarfStackPtr = 23870b57cec5SDimitry Andric TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true); 23885ffd83dbSDimitry Andric BuildCFI(MBB, MBBI, DL, 238981ad6265SDimitry Andric MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize), 239081ad6265SDimitry Andric MachineInstr::FrameDestroy); 239106c3fb27SDimitry Andric } 23925ffd83dbSDimitry Andric if (!MBB.succ_empty() && !MBB.isReturnBlock()) { 23935ffd83dbSDimitry Andric unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true); 23945ffd83dbSDimitry Andric BuildCFI(MBB, AfterPop, DL, 239581ad6265SDimitry Andric MCCFIInstruction::createRestore(nullptr, DwarfFramePtr), 239681ad6265SDimitry Andric MachineInstr::FrameDestroy); 23975ffd83dbSDimitry Andric --MBBI; 23985ffd83dbSDimitry Andric --AfterPop; 23995ffd83dbSDimitry Andric } 24000b57cec5SDimitry Andric --MBBI; 24010b57cec5SDimitry Andric } 24020b57cec5SDimitry Andric } 24030b57cec5SDimitry Andric 24040b57cec5SDimitry Andric MachineBasicBlock::iterator FirstCSPop = MBBI; 24050b57cec5SDimitry Andric // Skip the callee-saved pop instructions. 24060b57cec5SDimitry Andric while (MBBI != MBB.begin()) { 24070b57cec5SDimitry Andric MachineBasicBlock::iterator PI = std::prev(MBBI); 24080b57cec5SDimitry Andric unsigned Opc = PI->getOpcode(); 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric if (Opc != X86::DBG_VALUE && !PI->isTerminator()) { 2411*5f757f3fSDimitry Andric if (!PI->getFlag(MachineInstr::FrameDestroy) || 2412*5f757f3fSDimitry Andric (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::BTR64ri8 && 2413*5f757f3fSDimitry Andric Opc != X86::ADD64ri32 && Opc != X86::POPP64r && Opc != X86::POP2 && 2414*5f757f3fSDimitry Andric Opc != X86::POP2P && Opc != X86::LEA64r)) 24150b57cec5SDimitry Andric break; 24160b57cec5SDimitry Andric FirstCSPop = PI; 24170b57cec5SDimitry Andric } 24180b57cec5SDimitry Andric 24190b57cec5SDimitry Andric --MBBI; 24200b57cec5SDimitry Andric } 242106c3fb27SDimitry Andric if (ArgBaseReg.isValid()) { 242206c3fb27SDimitry Andric // Restore argument base pointer. 242306c3fb27SDimitry Andric auto *MI = X86FI->getStackPtrSaveMI(); 242406c3fb27SDimitry Andric int FI = MI->getOperand(1).getIndex(); 242506c3fb27SDimitry Andric unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm; 242606c3fb27SDimitry Andric // movl offset(%ebp), %basereg 242706c3fb27SDimitry Andric addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVrm), ArgBaseReg), FI) 242806c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 242906c3fb27SDimitry Andric } 24300b57cec5SDimitry Andric MBBI = FirstCSPop; 24310b57cec5SDimitry Andric 24320b57cec5SDimitry Andric if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET) 24330b57cec5SDimitry Andric emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator); 24340b57cec5SDimitry Andric 24350b57cec5SDimitry Andric if (MBBI != MBB.end()) 24360b57cec5SDimitry Andric DL = MBBI->getDebugLoc(); 24370b57cec5SDimitry Andric // If there is an ADD32ri or SUB32ri of ESP immediately before this 24380b57cec5SDimitry Andric // instruction, merge the two instructions. 24390b57cec5SDimitry Andric if (NumBytes || MFI.hasVarSizedObjects()) 24400b57cec5SDimitry Andric NumBytes += mergeSPUpdates(MBB, MBBI, true); 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric // If dynamic alloca is used, then reset esp to point to the last callee-saved 24430b57cec5SDimitry Andric // slot before popping them off! Same applies for the case, when stack was 24440b57cec5SDimitry Andric // realigned. Don't do this if this was a funclet epilogue, since the funclets 24450b57cec5SDimitry Andric // will not do realignment or dynamic stack allocation. 2446fe6060f1SDimitry Andric if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) && 24470b57cec5SDimitry Andric !IsFunclet) { 2448fe6060f1SDimitry Andric if (TRI->hasStackRealignment(MF)) 24490b57cec5SDimitry Andric MBBI = FirstCSPop; 24500b57cec5SDimitry Andric unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt); 24510b57cec5SDimitry Andric uint64_t LEAAmount = 24520b57cec5SDimitry Andric IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize; 24530b57cec5SDimitry Andric 2454fe6060f1SDimitry Andric if (X86FI->hasSwiftAsyncContext()) 2455fe6060f1SDimitry Andric LEAAmount -= 16; 2456fe6060f1SDimitry Andric 24570b57cec5SDimitry Andric // There are only two legal forms of epilogue: 24580b57cec5SDimitry Andric // - add SEHAllocationSize, %rsp 24590b57cec5SDimitry Andric // - lea SEHAllocationSize(%FramePtr), %rsp 24600b57cec5SDimitry Andric // 24610b57cec5SDimitry Andric // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence. 24620b57cec5SDimitry Andric // However, we may use this sequence if we have a frame pointer because the 24630b57cec5SDimitry Andric // effects of the prologue can safely be undone. 24640b57cec5SDimitry Andric if (LEAAmount != 0) { 24650b57cec5SDimitry Andric unsigned Opc = getLEArOpcode(Uses64BitFramePtr); 2466*5f757f3fSDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr), FramePtr, 2467*5f757f3fSDimitry Andric false, LEAAmount); 24680b57cec5SDimitry Andric --MBBI; 24690b57cec5SDimitry Andric } else { 24700b57cec5SDimitry Andric unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr); 2471*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr).addReg(FramePtr); 24720b57cec5SDimitry Andric --MBBI; 24730b57cec5SDimitry Andric } 24740b57cec5SDimitry Andric } else if (NumBytes) { 24750b57cec5SDimitry Andric // Adjust stack pointer back: ESP += numbytes. 24760b57cec5SDimitry Andric emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true); 2477349cc55cSDimitry Andric if (!HasFP && NeedsDwarfCFI) { 24780b57cec5SDimitry Andric // Define the current CFA rule to use the provided offset. 24795ffd83dbSDimitry Andric BuildCFI(MBB, MBBI, DL, 2480349cc55cSDimitry Andric MCCFIInstruction::cfiDefCfaOffset( 248181ad6265SDimitry Andric nullptr, CSSize + TailCallArgReserveSize + SlotSize), 248281ad6265SDimitry Andric MachineInstr::FrameDestroy); 24830b57cec5SDimitry Andric } 24840b57cec5SDimitry Andric --MBBI; 24850b57cec5SDimitry Andric } 24860b57cec5SDimitry Andric 24870b57cec5SDimitry Andric // Windows unwinder will not invoke function's exception handler if IP is 24880b57cec5SDimitry Andric // either in prologue or in epilogue. This behavior causes a problem when a 24890b57cec5SDimitry Andric // call immediately precedes an epilogue, because the return address points 24900b57cec5SDimitry Andric // into the epilogue. To cope with that, we insert an epilogue marker here, 24910b57cec5SDimitry Andric // then replace it with a 'nop' if it ends up immediately after a CALL in the 24920b57cec5SDimitry Andric // final emitted code. 24930b57cec5SDimitry Andric if (NeedsWin64CFI && MF.hasWinCFI()) 24940b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue)); 24950b57cec5SDimitry Andric 2496349cc55cSDimitry Andric if (!HasFP && NeedsDwarfCFI) { 24970b57cec5SDimitry Andric MBBI = FirstCSPop; 24980b57cec5SDimitry Andric int64_t Offset = -CSSize - SlotSize; 24990b57cec5SDimitry Andric // Mark callee-saved pop instruction. 25000b57cec5SDimitry Andric // Define the current CFA rule to use the provided offset. 25010b57cec5SDimitry Andric while (MBBI != MBB.end()) { 25020b57cec5SDimitry Andric MachineBasicBlock::iterator PI = MBBI; 25030b57cec5SDimitry Andric unsigned Opc = PI->getOpcode(); 25040b57cec5SDimitry Andric ++MBBI; 2505*5f757f3fSDimitry Andric if (Opc == X86::POP32r || Opc == X86::POP64r || Opc == X86::POPP64r || 2506*5f757f3fSDimitry Andric Opc == X86::POP2 || Opc == X86::POP2P) { 2507*5f757f3fSDimitry Andric Offset += SlotSize; 2508*5f757f3fSDimitry Andric // Compared to pop, pop2 introduces more stack offset (one more 2509*5f757f3fSDimitry Andric // register). 2510*5f757f3fSDimitry Andric if (Opc == X86::POP2 || Opc == X86::POP2P) 25110b57cec5SDimitry Andric Offset += SlotSize; 25120b57cec5SDimitry Andric BuildCFI(MBB, MBBI, DL, 251381ad6265SDimitry Andric MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset), 251481ad6265SDimitry Andric MachineInstr::FrameDestroy); 25150b57cec5SDimitry Andric } 25160b57cec5SDimitry Andric } 25170b57cec5SDimitry Andric } 25180b57cec5SDimitry Andric 25195ffd83dbSDimitry Andric // Emit DWARF info specifying the restores of the callee-saved registers. 25205ffd83dbSDimitry Andric // For epilogue with return inside or being other block without successor, 25215ffd83dbSDimitry Andric // no need to generate .cfi_restore for callee-saved registers. 2522349cc55cSDimitry Andric if (NeedsDwarfCFI && !MBB.succ_empty()) 25235ffd83dbSDimitry Andric emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false); 25245ffd83dbSDimitry Andric 25250b57cec5SDimitry Andric if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) { 25260b57cec5SDimitry Andric // Add the return addr area delta back since we are not tail calling. 25270b57cec5SDimitry Andric int Offset = -1 * X86FI->getTCReturnAddrDelta(); 25280b57cec5SDimitry Andric assert(Offset >= 0 && "TCDelta should never be positive"); 25290b57cec5SDimitry Andric if (Offset) { 25300b57cec5SDimitry Andric // Check for possible merge with preceding ADD instruction. 25310b57cec5SDimitry Andric Offset += mergeSPUpdates(MBB, Terminator, true); 25320b57cec5SDimitry Andric emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true); 25330b57cec5SDimitry Andric } 25340b57cec5SDimitry Andric } 2535e8d8bef9SDimitry Andric 2536e8d8bef9SDimitry Andric // Emit tilerelease for AMX kernel. 2537349cc55cSDimitry Andric if (X86FI->hasVirtualTileReg()) 2538e8d8bef9SDimitry Andric BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE)); 25390b57cec5SDimitry Andric } 25400b57cec5SDimitry Andric 2541e8d8bef9SDimitry Andric StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, 2542e8d8bef9SDimitry Andric int FI, 25435ffd83dbSDimitry Andric Register &FrameReg) const { 25440b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 25450b57cec5SDimitry Andric 25460b57cec5SDimitry Andric bool IsFixed = MFI.isFixedObjectIndex(FI); 25470b57cec5SDimitry Andric // We can't calculate offset from frame pointer if the stack is realigned, 25480b57cec5SDimitry Andric // so enforce usage of stack/base pointer. The base pointer is used when we 25490b57cec5SDimitry Andric // have dynamic allocas in addition to dynamic realignment. 25500b57cec5SDimitry Andric if (TRI->hasBasePointer(MF)) 25510b57cec5SDimitry Andric FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister(); 2552fe6060f1SDimitry Andric else if (TRI->hasStackRealignment(MF)) 25530b57cec5SDimitry Andric FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister(); 25540b57cec5SDimitry Andric else 25550b57cec5SDimitry Andric FrameReg = TRI->getFrameRegister(MF); 25560b57cec5SDimitry Andric 25570b57cec5SDimitry Andric // Offset will hold the offset from the stack pointer at function entry to the 25580b57cec5SDimitry Andric // object. 25590b57cec5SDimitry Andric // We need to factor in additional offsets applied during the prologue to the 25600b57cec5SDimitry Andric // frame, base, and stack pointer depending on which is used. 25610b57cec5SDimitry Andric int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea(); 25620b57cec5SDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 25630b57cec5SDimitry Andric unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 25640b57cec5SDimitry Andric uint64_t StackSize = MFI.getStackSize(); 25650b57cec5SDimitry Andric bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 25660b57cec5SDimitry Andric int64_t FPDelta = 0; 25670b57cec5SDimitry Andric 25680b57cec5SDimitry Andric // In an x86 interrupt, remove the offset we added to account for the return 25690b57cec5SDimitry Andric // address from any stack object allocated in the caller's frame. Interrupts 25700b57cec5SDimitry Andric // do not have a standard return address. Fixed objects in the current frame, 25710b57cec5SDimitry Andric // such as SSE register spills, should not get this treatment. 25720b57cec5SDimitry Andric if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR && 25730b57cec5SDimitry Andric Offset >= 0) { 25740b57cec5SDimitry Andric Offset += getOffsetOfLocalArea(); 25750b57cec5SDimitry Andric } 25760b57cec5SDimitry Andric 25770b57cec5SDimitry Andric if (IsWin64Prologue) { 25780b57cec5SDimitry Andric assert(!MFI.hasCalls() || (StackSize % 16) == 8); 25790b57cec5SDimitry Andric 25800b57cec5SDimitry Andric // Calculate required stack adjustment. 25810b57cec5SDimitry Andric uint64_t FrameSize = StackSize - SlotSize; 2582*5f757f3fSDimitry Andric // If required, include space for extra hidden slot for stashing base 2583*5f757f3fSDimitry Andric // pointer. 25840b57cec5SDimitry Andric if (X86FI->getRestoreBasePointer()) 25850b57cec5SDimitry Andric FrameSize += SlotSize; 25860b57cec5SDimitry Andric uint64_t NumBytes = FrameSize - CSSize; 25870b57cec5SDimitry Andric 25880b57cec5SDimitry Andric uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes); 25890b57cec5SDimitry Andric if (FI && FI == X86FI->getFAIndex()) 2590e8d8bef9SDimitry Andric return StackOffset::getFixed(-SEHFrameOffset); 25910b57cec5SDimitry Andric 25920b57cec5SDimitry Andric // FPDelta is the offset from the "traditional" FP location of the old base 25930b57cec5SDimitry Andric // pointer followed by return address and the location required by the 25940b57cec5SDimitry Andric // restricted Win64 prologue. 25950b57cec5SDimitry Andric // Add FPDelta to all offsets below that go through the frame pointer. 25960b57cec5SDimitry Andric FPDelta = FrameSize - SEHFrameOffset; 25970b57cec5SDimitry Andric assert((!MFI.hasCalls() || (FPDelta % 16) == 0) && 25980b57cec5SDimitry Andric "FPDelta isn't aligned per the Win64 ABI!"); 25990b57cec5SDimitry Andric } 26000b57cec5SDimitry Andric 2601349cc55cSDimitry Andric if (FrameReg == TRI->getFramePtr()) { 2602349cc55cSDimitry Andric // Skip saved EBP/RBP 26030b57cec5SDimitry Andric Offset += SlotSize; 26040b57cec5SDimitry Andric 2605349cc55cSDimitry Andric // Account for restricted Windows prologue. 2606349cc55cSDimitry Andric Offset += FPDelta; 2607349cc55cSDimitry Andric 26080b57cec5SDimitry Andric // Skip the RETADDR move area 26090b57cec5SDimitry Andric int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta(); 26100b57cec5SDimitry Andric if (TailCallReturnAddrDelta < 0) 26110b57cec5SDimitry Andric Offset -= TailCallReturnAddrDelta; 2612349cc55cSDimitry Andric 2613349cc55cSDimitry Andric return StackOffset::getFixed(Offset); 26140b57cec5SDimitry Andric } 26150b57cec5SDimitry Andric 2616349cc55cSDimitry Andric // FrameReg is either the stack pointer or a base pointer. But the base is 2617349cc55cSDimitry Andric // located at the end of the statically known StackSize so the distinction 2618349cc55cSDimitry Andric // doesn't really matter. 2619349cc55cSDimitry Andric if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF)) 2620349cc55cSDimitry Andric assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize))); 2621349cc55cSDimitry Andric return StackOffset::getFixed(Offset + StackSize); 26220b57cec5SDimitry Andric } 26230b57cec5SDimitry Andric 26245ffd83dbSDimitry Andric int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI, 26255ffd83dbSDimitry Andric Register &FrameReg) const { 2626c14a5a88SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 2627c14a5a88SDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 2628c14a5a88SDimitry Andric const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 2629c14a5a88SDimitry Andric const auto it = WinEHXMMSlotInfo.find(FI); 2630c14a5a88SDimitry Andric 2631c14a5a88SDimitry Andric if (it == WinEHXMMSlotInfo.end()) 2632e8d8bef9SDimitry Andric return getFrameIndexReference(MF, FI, FrameReg).getFixed(); 2633c14a5a88SDimitry Andric 2634c14a5a88SDimitry Andric FrameReg = TRI->getStackRegister(); 26355ffd83dbSDimitry Andric return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) + 26365ffd83dbSDimitry Andric it->second; 2637c14a5a88SDimitry Andric } 2638c14a5a88SDimitry Andric 2639e8d8bef9SDimitry Andric StackOffset 2640e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI, 2641e8d8bef9SDimitry Andric Register &FrameReg, 26420b57cec5SDimitry Andric int Adjustment) const { 26430b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 26440b57cec5SDimitry Andric FrameReg = TRI->getStackRegister(); 2645e8d8bef9SDimitry Andric return StackOffset::getFixed(MFI.getObjectOffset(FI) - 2646e8d8bef9SDimitry Andric getOffsetOfLocalArea() + Adjustment); 26470b57cec5SDimitry Andric } 26480b57cec5SDimitry Andric 2649e8d8bef9SDimitry Andric StackOffset 2650e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF, 2651e8d8bef9SDimitry Andric int FI, Register &FrameReg, 26520b57cec5SDimitry Andric bool IgnoreSPUpdates) const { 26530b57cec5SDimitry Andric 26540b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 26550b57cec5SDimitry Andric // Does not include any dynamic realign. 26560b57cec5SDimitry Andric const uint64_t StackSize = MFI.getStackSize(); 26570b57cec5SDimitry Andric // LLVM arranges the stack as follows: 26580b57cec5SDimitry Andric // ... 26590b57cec5SDimitry Andric // ARG2 26600b57cec5SDimitry Andric // ARG1 26610b57cec5SDimitry Andric // RETADDR 26620b57cec5SDimitry Andric // PUSH RBP <-- RBP points here 26630b57cec5SDimitry Andric // PUSH CSRs 26640b57cec5SDimitry Andric // ~~~~~~~ <-- possible stack realignment (non-win64) 26650b57cec5SDimitry Andric // ... 26660b57cec5SDimitry Andric // STACK OBJECTS 26670b57cec5SDimitry Andric // ... <-- RSP after prologue points here 26680b57cec5SDimitry Andric // ~~~~~~~ <-- possible stack realignment (win64) 26690b57cec5SDimitry Andric // 26700b57cec5SDimitry Andric // if (hasVarSizedObjects()): 26710b57cec5SDimitry Andric // ... <-- "base pointer" (ESI/RBX) points here 26720b57cec5SDimitry Andric // DYNAMIC ALLOCAS 26730b57cec5SDimitry Andric // ... <-- RSP points here 26740b57cec5SDimitry Andric // 26750b57cec5SDimitry Andric // Case 1: In the simple case of no stack realignment and no dynamic 26760b57cec5SDimitry Andric // allocas, both "fixed" stack objects (arguments and CSRs) are addressable 26770b57cec5SDimitry Andric // with fixed offsets from RSP. 26780b57cec5SDimitry Andric // 26790b57cec5SDimitry Andric // Case 2: In the case of stack realignment with no dynamic allocas, fixed 26800b57cec5SDimitry Andric // stack objects are addressed with RBP and regular stack objects with RSP. 26810b57cec5SDimitry Andric // 26820b57cec5SDimitry Andric // Case 3: In the case of dynamic allocas and stack realignment, RSP is used 26830b57cec5SDimitry Andric // to address stack arguments for outgoing calls and nothing else. The "base 26840b57cec5SDimitry Andric // pointer" points to local variables, and RBP points to fixed objects. 26850b57cec5SDimitry Andric // 26860b57cec5SDimitry Andric // In cases 2 and 3, we can only answer for non-fixed stack objects, and the 26870b57cec5SDimitry Andric // answer we give is relative to the SP after the prologue, and not the 26880b57cec5SDimitry Andric // SP in the middle of the function. 26890b57cec5SDimitry Andric 2690fe6060f1SDimitry Andric if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) && 26910b57cec5SDimitry Andric !STI.isTargetWin64()) 26920b57cec5SDimitry Andric return getFrameIndexReference(MF, FI, FrameReg); 26930b57cec5SDimitry Andric 26940b57cec5SDimitry Andric // If !hasReservedCallFrame the function might have SP adjustement in the 26950b57cec5SDimitry Andric // body. So, even though the offset is statically known, it depends on where 26960b57cec5SDimitry Andric // we are in the function. 26970b57cec5SDimitry Andric if (!IgnoreSPUpdates && !hasReservedCallFrame(MF)) 26980b57cec5SDimitry Andric return getFrameIndexReference(MF, FI, FrameReg); 26990b57cec5SDimitry Andric 27000b57cec5SDimitry Andric // We don't handle tail calls, and shouldn't be seeing them either. 27010b57cec5SDimitry Andric assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 && 27020b57cec5SDimitry Andric "we don't handle this case!"); 27030b57cec5SDimitry Andric 27040b57cec5SDimitry Andric // This is how the math works out: 27050b57cec5SDimitry Andric // 27060b57cec5SDimitry Andric // %rsp grows (i.e. gets lower) left to right. Each box below is 27070b57cec5SDimitry Andric // one word (eight bytes). Obj0 is the stack slot we're trying to 27080b57cec5SDimitry Andric // get to. 27090b57cec5SDimitry Andric // 27100b57cec5SDimitry Andric // ---------------------------------- 27110b57cec5SDimitry Andric // | BP | Obj0 | Obj1 | ... | ObjN | 27120b57cec5SDimitry Andric // ---------------------------------- 27130b57cec5SDimitry Andric // ^ ^ ^ ^ 27140b57cec5SDimitry Andric // A B C E 27150b57cec5SDimitry Andric // 27160b57cec5SDimitry Andric // A is the incoming stack pointer. 27170b57cec5SDimitry Andric // (B - A) is the local area offset (-8 for x86-64) [1] 27180b57cec5SDimitry Andric // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2] 27190b57cec5SDimitry Andric // 27200b57cec5SDimitry Andric // |(E - B)| is the StackSize (absolute value, positive). For a 27210b57cec5SDimitry Andric // stack that grown down, this works out to be (B - E). [3] 27220b57cec5SDimitry Andric // 27230b57cec5SDimitry Andric // E is also the value of %rsp after stack has been set up, and we 27240b57cec5SDimitry Andric // want (C - E) -- the value we can add to %rsp to get to Obj0. Now 27250b57cec5SDimitry Andric // (C - E) == (C - A) - (B - A) + (B - E) 27260b57cec5SDimitry Andric // { Using [1], [2] and [3] above } 27270b57cec5SDimitry Andric // == getObjectOffset - LocalAreaOffset + StackSize 27280b57cec5SDimitry Andric 27290b57cec5SDimitry Andric return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize); 27300b57cec5SDimitry Andric } 27310b57cec5SDimitry Andric 27320b57cec5SDimitry Andric bool X86FrameLowering::assignCalleeSavedSpillSlots( 27330b57cec5SDimitry Andric MachineFunction &MF, const TargetRegisterInfo *TRI, 27340b57cec5SDimitry Andric std::vector<CalleeSavedInfo> &CSI) const { 27350b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 27360b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 27370b57cec5SDimitry Andric 27380b57cec5SDimitry Andric unsigned CalleeSavedFrameSize = 0; 2739c14a5a88SDimitry Andric unsigned XMMCalleeSavedFrameSize = 0; 2740c14a5a88SDimitry Andric auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 27410b57cec5SDimitry Andric int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta(); 27420b57cec5SDimitry Andric 27430b57cec5SDimitry Andric int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta(); 27440b57cec5SDimitry Andric 27450b57cec5SDimitry Andric if (TailCallReturnAddrDelta < 0) { 27460b57cec5SDimitry Andric // create RETURNADDR area 27470b57cec5SDimitry Andric // arg 27480b57cec5SDimitry Andric // arg 27490b57cec5SDimitry Andric // RETADDR 27500b57cec5SDimitry Andric // { ... 27510b57cec5SDimitry Andric // RETADDR area 27520b57cec5SDimitry Andric // ... 27530b57cec5SDimitry Andric // } 27540b57cec5SDimitry Andric // [EBP] 27550b57cec5SDimitry Andric MFI.CreateFixedObject(-TailCallReturnAddrDelta, 27560b57cec5SDimitry Andric TailCallReturnAddrDelta - SlotSize, true); 27570b57cec5SDimitry Andric } 27580b57cec5SDimitry Andric 27590b57cec5SDimitry Andric // Spill the BasePtr if it's used. 27600b57cec5SDimitry Andric if (this->TRI->hasBasePointer(MF)) { 27610b57cec5SDimitry Andric // Allocate a spill slot for EBP if we have a base pointer and EH funclets. 27620b57cec5SDimitry Andric if (MF.hasEHFunclets()) { 27635ffd83dbSDimitry Andric int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize)); 27640b57cec5SDimitry Andric X86FI->setHasSEHFramePtrSave(true); 27650b57cec5SDimitry Andric X86FI->setSEHFramePtrSaveIndex(FI); 27660b57cec5SDimitry Andric } 27670b57cec5SDimitry Andric } 27680b57cec5SDimitry Andric 27690b57cec5SDimitry Andric if (hasFP(MF)) { 27700b57cec5SDimitry Andric // emitPrologue always spills frame register the first thing. 27710b57cec5SDimitry Andric SpillSlotOffset -= SlotSize; 27720b57cec5SDimitry Andric MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 27730b57cec5SDimitry Andric 2774fe6060f1SDimitry Andric // The async context lives directly before the frame pointer, and we 2775fe6060f1SDimitry Andric // allocate a second slot to preserve stack alignment. 2776fe6060f1SDimitry Andric if (X86FI->hasSwiftAsyncContext()) { 2777fe6060f1SDimitry Andric SpillSlotOffset -= SlotSize; 2778fe6060f1SDimitry Andric MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 2779fe6060f1SDimitry Andric SpillSlotOffset -= SlotSize; 2780fe6060f1SDimitry Andric } 2781fe6060f1SDimitry Andric 27820b57cec5SDimitry Andric // Since emitPrologue and emitEpilogue will handle spilling and restoring of 27830b57cec5SDimitry Andric // the frame register, we can delete it from CSI list and not have to worry 27840b57cec5SDimitry Andric // about avoiding it later. 27858bcb0991SDimitry Andric Register FPReg = TRI->getFrameRegister(MF); 27860b57cec5SDimitry Andric for (unsigned i = 0; i < CSI.size(); ++i) { 27870b57cec5SDimitry Andric if (TRI->regsOverlap(CSI[i].getReg(), FPReg)) { 27880b57cec5SDimitry Andric CSI.erase(CSI.begin() + i); 27890b57cec5SDimitry Andric break; 27900b57cec5SDimitry Andric } 27910b57cec5SDimitry Andric } 27920b57cec5SDimitry Andric } 27930b57cec5SDimitry Andric 2794*5f757f3fSDimitry Andric // Strategy: 2795*5f757f3fSDimitry Andric // 1. Use push2 when 2796*5f757f3fSDimitry Andric // a) number of CSR > 1 if no need padding 2797*5f757f3fSDimitry Andric // b) number of CSR > 2 if need padding 2798*5f757f3fSDimitry Andric // 2. When the number of CSR push is odd 2799*5f757f3fSDimitry Andric // a. Start to use push2 from the 1st push if stack is 16B aligned. 2800*5f757f3fSDimitry Andric // b. Start to use push2 from the 2nd push if stack is not 16B aligned. 2801*5f757f3fSDimitry Andric // 3. When the number of CSR push is even, start to use push2 from the 1st 2802*5f757f3fSDimitry Andric // push and make the stack 16B aligned before the push 2803*5f757f3fSDimitry Andric unsigned NumRegsForPush2 = 0; 2804*5f757f3fSDimitry Andric if (STI.hasPush2Pop2()) { 2805*5f757f3fSDimitry Andric unsigned NumCSGPR = llvm::count_if(CSI, [](const CalleeSavedInfo &I) { 2806*5f757f3fSDimitry Andric return X86::GR64RegClass.contains(I.getReg()); 2807*5f757f3fSDimitry Andric }); 2808*5f757f3fSDimitry Andric bool NeedPadding = (SpillSlotOffset % 16 != 0) && (NumCSGPR % 2 == 0); 2809*5f757f3fSDimitry Andric bool UsePush2Pop2 = NeedPadding ? NumCSGPR > 2 : NumCSGPR > 1; 2810*5f757f3fSDimitry Andric X86FI->setPadForPush2Pop2(NeedPadding && UsePush2Pop2); 2811*5f757f3fSDimitry Andric NumRegsForPush2 = UsePush2Pop2 ? alignDown(NumCSGPR, 2) : 0; 2812*5f757f3fSDimitry Andric if (X86FI->padForPush2Pop2()) { 2813*5f757f3fSDimitry Andric SpillSlotOffset -= SlotSize; 2814*5f757f3fSDimitry Andric MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 2815*5f757f3fSDimitry Andric } 2816*5f757f3fSDimitry Andric } 2817*5f757f3fSDimitry Andric 28180b57cec5SDimitry Andric // Assign slots for GPRs. It increases frame size. 28190eae32dcSDimitry Andric for (CalleeSavedInfo &I : llvm::reverse(CSI)) { 282004eeddc0SDimitry Andric Register Reg = I.getReg(); 28210b57cec5SDimitry Andric 28220b57cec5SDimitry Andric if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg)) 28230b57cec5SDimitry Andric continue; 28240b57cec5SDimitry Andric 2825*5f757f3fSDimitry Andric // A CSR is a candidate for push2/pop2 when it's slot offset is 16B aligned 2826*5f757f3fSDimitry Andric // or only an odd number of registers in the candidates. 2827*5f757f3fSDimitry Andric if (X86FI->getNumCandidatesForPush2Pop2() < NumRegsForPush2 && 2828*5f757f3fSDimitry Andric (SpillSlotOffset % 16 == 0 || 2829*5f757f3fSDimitry Andric X86FI->getNumCandidatesForPush2Pop2() % 2)) 2830*5f757f3fSDimitry Andric X86FI->addCandidateForPush2Pop2(Reg); 2831*5f757f3fSDimitry Andric 28320b57cec5SDimitry Andric SpillSlotOffset -= SlotSize; 28330b57cec5SDimitry Andric CalleeSavedFrameSize += SlotSize; 28340b57cec5SDimitry Andric 28350b57cec5SDimitry Andric int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 28360eae32dcSDimitry Andric I.setFrameIdx(SlotIndex); 28370b57cec5SDimitry Andric } 28380b57cec5SDimitry Andric 283906c3fb27SDimitry Andric // Adjust the offset of spill slot as we know the accurate callee saved frame 284006c3fb27SDimitry Andric // size. 284106c3fb27SDimitry Andric if (X86FI->getRestoreBasePointer()) { 284206c3fb27SDimitry Andric SpillSlotOffset -= SlotSize; 284306c3fb27SDimitry Andric CalleeSavedFrameSize += SlotSize; 284406c3fb27SDimitry Andric 284506c3fb27SDimitry Andric MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 284606c3fb27SDimitry Andric // TODO: saving the slot index is better? 284706c3fb27SDimitry Andric X86FI->setRestoreBasePointer(CalleeSavedFrameSize); 284806c3fb27SDimitry Andric } 2849*5f757f3fSDimitry Andric assert(X86FI->getNumCandidatesForPush2Pop2() % 2 == 0 && 2850*5f757f3fSDimitry Andric "Expect even candidates for push2/pop2"); 2851*5f757f3fSDimitry Andric if (X86FI->getNumCandidatesForPush2Pop2()) 2852*5f757f3fSDimitry Andric ++NumFunctionUsingPush2Pop2; 28530b57cec5SDimitry Andric X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize); 28540b57cec5SDimitry Andric MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize); 28550b57cec5SDimitry Andric 28560b57cec5SDimitry Andric // Assign slots for XMMs. 28570eae32dcSDimitry Andric for (CalleeSavedInfo &I : llvm::reverse(CSI)) { 285804eeddc0SDimitry Andric Register Reg = I.getReg(); 28590b57cec5SDimitry Andric if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg)) 28600b57cec5SDimitry Andric continue; 28610b57cec5SDimitry Andric 28620b57cec5SDimitry Andric // If this is k-register make sure we lookup via the largest legal type. 28630b57cec5SDimitry Andric MVT VT = MVT::Other; 28640b57cec5SDimitry Andric if (X86::VK16RegClass.contains(Reg)) 28650b57cec5SDimitry Andric VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 28660b57cec5SDimitry Andric 28670b57cec5SDimitry Andric const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 28680b57cec5SDimitry Andric unsigned Size = TRI->getSpillSize(*RC); 28695ffd83dbSDimitry Andric Align Alignment = TRI->getSpillAlign(*RC); 28700b57cec5SDimitry Andric // ensure alignment 2871c14a5a88SDimitry Andric assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86"); 28725ffd83dbSDimitry Andric SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment); 2873c14a5a88SDimitry Andric 28740b57cec5SDimitry Andric // spill into slot 28750b57cec5SDimitry Andric SpillSlotOffset -= Size; 28760b57cec5SDimitry Andric int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset); 28770eae32dcSDimitry Andric I.setFrameIdx(SlotIndex); 28785ffd83dbSDimitry Andric MFI.ensureMaxAlignment(Alignment); 2879c14a5a88SDimitry Andric 2880c14a5a88SDimitry Andric // Save the start offset and size of XMM in stack frame for funclets. 2881c14a5a88SDimitry Andric if (X86::VR128RegClass.contains(Reg)) { 2882c14a5a88SDimitry Andric WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize; 2883c14a5a88SDimitry Andric XMMCalleeSavedFrameSize += Size; 2884c14a5a88SDimitry Andric } 28850b57cec5SDimitry Andric } 28860b57cec5SDimitry Andric 28870b57cec5SDimitry Andric return true; 28880b57cec5SDimitry Andric } 28890b57cec5SDimitry Andric 28900b57cec5SDimitry Andric bool X86FrameLowering::spillCalleeSavedRegisters( 28910b57cec5SDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 28925ffd83dbSDimitry Andric ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 28930b57cec5SDimitry Andric DebugLoc DL = MBB.findDebugLoc(MI); 28940b57cec5SDimitry Andric 28950b57cec5SDimitry Andric // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI 28960b57cec5SDimitry Andric // for us, and there are no XMM CSRs on Win32. 28970b57cec5SDimitry Andric if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows()) 28980b57cec5SDimitry Andric return true; 28990b57cec5SDimitry Andric 29000b57cec5SDimitry Andric // Push GPRs. It increases frame size. 29010b57cec5SDimitry Andric const MachineFunction &MF = *MBB.getParent(); 2902*5f757f3fSDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 2903*5f757f3fSDimitry Andric if (X86FI->padForPush2Pop2()) 2904*5f757f3fSDimitry Andric emitSPUpdate(MBB, MI, DL, -(int64_t)SlotSize, /*InEpilogue=*/false); 29050b57cec5SDimitry Andric 2906*5f757f3fSDimitry Andric // Update LiveIn of the basic block and decide whether we can add a kill flag 2907*5f757f3fSDimitry Andric // to the use. 2908*5f757f3fSDimitry Andric auto UpdateLiveInCheckCanKill = [&](Register Reg) { 29090b57cec5SDimitry Andric const MachineRegisterInfo &MRI = MF.getRegInfo(); 29100b57cec5SDimitry Andric // Do not set a kill flag on values that are also marked as live-in. This 29110b57cec5SDimitry Andric // happens with the @llvm-returnaddress intrinsic and with arguments 29120b57cec5SDimitry Andric // passed in callee saved registers. 29130b57cec5SDimitry Andric // Omitting the kill flags is conservatively correct even if the live-in 29140b57cec5SDimitry Andric // is not used after all. 2915*5f757f3fSDimitry Andric if (MRI.isLiveIn(Reg)) 2916*5f757f3fSDimitry Andric return false; 2917*5f757f3fSDimitry Andric MBB.addLiveIn(Reg); 2918*5f757f3fSDimitry Andric // Check if any subregister is live-in 2919*5f757f3fSDimitry Andric for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) 2920*5f757f3fSDimitry Andric if (MRI.isLiveIn(*AReg)) 2921*5f757f3fSDimitry Andric return false; 2922*5f757f3fSDimitry Andric return true; 2923*5f757f3fSDimitry Andric }; 2924*5f757f3fSDimitry Andric auto UpdateLiveInGetKillRegState = [&](Register Reg) { 2925*5f757f3fSDimitry Andric return getKillRegState(UpdateLiveInCheckCanKill(Reg)); 2926*5f757f3fSDimitry Andric }; 2927*5f757f3fSDimitry Andric 2928*5f757f3fSDimitry Andric for (auto RI = CSI.rbegin(), RE = CSI.rend(); RI != RE; ++RI) { 2929*5f757f3fSDimitry Andric Register Reg = RI->getReg(); 2930*5f757f3fSDimitry Andric if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg)) 2931*5f757f3fSDimitry Andric continue; 2932*5f757f3fSDimitry Andric 2933*5f757f3fSDimitry Andric if (X86FI->isCandidateForPush2Pop2(Reg)) { 2934*5f757f3fSDimitry Andric Register Reg2 = (++RI)->getReg(); 2935*5f757f3fSDimitry Andric BuildMI(MBB, MI, DL, TII.get(getPUSH2Opcode(STI))) 2936*5f757f3fSDimitry Andric .addReg(Reg, UpdateLiveInGetKillRegState(Reg)) 2937*5f757f3fSDimitry Andric .addReg(Reg2, UpdateLiveInGetKillRegState(Reg2)) 2938*5f757f3fSDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 2939*5f757f3fSDimitry Andric } else { 2940*5f757f3fSDimitry Andric BuildMI(MBB, MI, DL, TII.get(getPUSHOpcode(STI))) 2941*5f757f3fSDimitry Andric .addReg(Reg, UpdateLiveInGetKillRegState(Reg)) 29420b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 29430b57cec5SDimitry Andric } 2944*5f757f3fSDimitry Andric } 29450b57cec5SDimitry Andric 294606c3fb27SDimitry Andric if (X86FI->getRestoreBasePointer()) { 294706c3fb27SDimitry Andric unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r; 294806c3fb27SDimitry Andric Register BaseReg = this->TRI->getBaseRegister(); 294906c3fb27SDimitry Andric BuildMI(MBB, MI, DL, TII.get(Opc)) 295006c3fb27SDimitry Andric .addReg(BaseReg, getKillRegState(true)) 295106c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 295206c3fb27SDimitry Andric } 295306c3fb27SDimitry Andric 29540b57cec5SDimitry Andric // Make XMM regs spilled. X86 does not have ability of push/pop XMM. 29550b57cec5SDimitry Andric // It can be done by spilling XMMs to stack frame. 29560eae32dcSDimitry Andric for (const CalleeSavedInfo &I : llvm::reverse(CSI)) { 295704eeddc0SDimitry Andric Register Reg = I.getReg(); 29580b57cec5SDimitry Andric if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg)) 29590b57cec5SDimitry Andric continue; 29600b57cec5SDimitry Andric 29610b57cec5SDimitry Andric // If this is k-register make sure we lookup via the largest legal type. 29620b57cec5SDimitry Andric MVT VT = MVT::Other; 29630b57cec5SDimitry Andric if (X86::VK16RegClass.contains(Reg)) 29640b57cec5SDimitry Andric VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 29650b57cec5SDimitry Andric 29660b57cec5SDimitry Andric // Add the callee-saved register as live-in. It's killed at the spill. 29670b57cec5SDimitry Andric MBB.addLiveIn(Reg); 29680b57cec5SDimitry Andric const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 29690b57cec5SDimitry Andric 2970bdd1243dSDimitry Andric TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, TRI, 2971bdd1243dSDimitry Andric Register()); 29720b57cec5SDimitry Andric --MI; 29730b57cec5SDimitry Andric MI->setFlag(MachineInstr::FrameSetup); 29740b57cec5SDimitry Andric ++MI; 29750b57cec5SDimitry Andric } 29760b57cec5SDimitry Andric 29770b57cec5SDimitry Andric return true; 29780b57cec5SDimitry Andric } 29790b57cec5SDimitry Andric 29800b57cec5SDimitry Andric void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB, 29810b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI, 29820b57cec5SDimitry Andric MachineInstr *CatchRet) const { 29830b57cec5SDimitry Andric // SEH shouldn't use catchret. 29840b57cec5SDimitry Andric assert(!isAsynchronousEHPersonality(classifyEHPersonality( 29850b57cec5SDimitry Andric MBB.getParent()->getFunction().getPersonalityFn())) && 29860b57cec5SDimitry Andric "SEH should not use CATCHRET"); 2987fe6060f1SDimitry Andric const DebugLoc &DL = CatchRet->getDebugLoc(); 29880b57cec5SDimitry Andric MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB(); 29890b57cec5SDimitry Andric 29900b57cec5SDimitry Andric // Fill EAX/RAX with the address of the target block. 29910b57cec5SDimitry Andric if (STI.is64Bit()) { 29920b57cec5SDimitry Andric // LEA64r CatchRetTarget(%rip), %rax 29930b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX) 29940b57cec5SDimitry Andric .addReg(X86::RIP) 29950b57cec5SDimitry Andric .addImm(0) 29960b57cec5SDimitry Andric .addReg(0) 29970b57cec5SDimitry Andric .addMBB(CatchRetTarget) 29980b57cec5SDimitry Andric .addReg(0); 29990b57cec5SDimitry Andric } else { 30000b57cec5SDimitry Andric // MOV32ri $CatchRetTarget, %eax 30010b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) 30020b57cec5SDimitry Andric .addMBB(CatchRetTarget); 30030b57cec5SDimitry Andric } 30040b57cec5SDimitry Andric 30050b57cec5SDimitry Andric // Record that we've taken the address of CatchRetTarget and no longer just 30060b57cec5SDimitry Andric // reference it in a terminator. 3007bdd1243dSDimitry Andric CatchRetTarget->setMachineBlockAddressTaken(); 30080b57cec5SDimitry Andric } 30090b57cec5SDimitry Andric 30105ffd83dbSDimitry Andric bool X86FrameLowering::restoreCalleeSavedRegisters( 30115ffd83dbSDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 30125ffd83dbSDimitry Andric MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 30130b57cec5SDimitry Andric if (CSI.empty()) 30140b57cec5SDimitry Andric return false; 30150b57cec5SDimitry Andric 30160b57cec5SDimitry Andric if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) { 30170b57cec5SDimitry Andric // Don't restore CSRs in 32-bit EH funclets. Matches 30180b57cec5SDimitry Andric // spillCalleeSavedRegisters. 30190b57cec5SDimitry Andric if (STI.is32Bit()) 30200b57cec5SDimitry Andric return true; 30210b57cec5SDimitry Andric // Don't restore CSRs before an SEH catchret. SEH except blocks do not form 30220b57cec5SDimitry Andric // funclets. emitEpilogue transforms these to normal jumps. 30230b57cec5SDimitry Andric if (MI->getOpcode() == X86::CATCHRET) { 30240b57cec5SDimitry Andric const Function &F = MBB.getParent()->getFunction(); 30250b57cec5SDimitry Andric bool IsSEH = isAsynchronousEHPersonality( 30260b57cec5SDimitry Andric classifyEHPersonality(F.getPersonalityFn())); 30270b57cec5SDimitry Andric if (IsSEH) 30280b57cec5SDimitry Andric return true; 30290b57cec5SDimitry Andric } 30300b57cec5SDimitry Andric } 30310b57cec5SDimitry Andric 30320b57cec5SDimitry Andric DebugLoc DL = MBB.findDebugLoc(MI); 30330b57cec5SDimitry Andric 30340b57cec5SDimitry Andric // Reload XMMs from stack frame. 30354824e7fdSDimitry Andric for (const CalleeSavedInfo &I : CSI) { 303604eeddc0SDimitry Andric Register Reg = I.getReg(); 3037*5f757f3fSDimitry Andric if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg)) 30380b57cec5SDimitry Andric continue; 30390b57cec5SDimitry Andric 30400b57cec5SDimitry Andric // If this is k-register make sure we lookup via the largest legal type. 30410b57cec5SDimitry Andric MVT VT = MVT::Other; 30420b57cec5SDimitry Andric if (X86::VK16RegClass.contains(Reg)) 30430b57cec5SDimitry Andric VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 30440b57cec5SDimitry Andric 30450b57cec5SDimitry Andric const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 3046bdd1243dSDimitry Andric TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, TRI, 3047bdd1243dSDimitry Andric Register()); 30480b57cec5SDimitry Andric } 30490b57cec5SDimitry Andric 305006c3fb27SDimitry Andric // Clear the stack slot for spill base pointer register. 305106c3fb27SDimitry Andric MachineFunction &MF = *MBB.getParent(); 305206c3fb27SDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 305306c3fb27SDimitry Andric if (X86FI->getRestoreBasePointer()) { 305406c3fb27SDimitry Andric unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r; 305506c3fb27SDimitry Andric Register BaseReg = this->TRI->getBaseRegister(); 305606c3fb27SDimitry Andric BuildMI(MBB, MI, DL, TII.get(Opc), BaseReg) 305706c3fb27SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 305806c3fb27SDimitry Andric } 305906c3fb27SDimitry Andric 30600b57cec5SDimitry Andric // POP GPRs. 3061*5f757f3fSDimitry Andric for (auto I = CSI.begin(), E = CSI.end(); I != E; ++I) { 3062*5f757f3fSDimitry Andric Register Reg = I->getReg(); 3063*5f757f3fSDimitry Andric if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg)) 30640b57cec5SDimitry Andric continue; 30650b57cec5SDimitry Andric 3066*5f757f3fSDimitry Andric if (X86FI->isCandidateForPush2Pop2(Reg)) 3067*5f757f3fSDimitry Andric BuildMI(MBB, MI, DL, TII.get(getPOP2Opcode(STI)), Reg) 3068*5f757f3fSDimitry Andric .addReg((++I)->getReg(), RegState::Define) 3069*5f757f3fSDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 3070*5f757f3fSDimitry Andric else 3071*5f757f3fSDimitry Andric BuildMI(MBB, MI, DL, TII.get(getPOPOpcode(STI)), Reg) 30720b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameDestroy); 30730b57cec5SDimitry Andric } 3074*5f757f3fSDimitry Andric if (X86FI->padForPush2Pop2()) 3075*5f757f3fSDimitry Andric emitSPUpdate(MBB, MI, DL, SlotSize, /*InEpilogue=*/true); 3076*5f757f3fSDimitry Andric 30770b57cec5SDimitry Andric return true; 30780b57cec5SDimitry Andric } 30790b57cec5SDimitry Andric 30800b57cec5SDimitry Andric void X86FrameLowering::determineCalleeSaves(MachineFunction &MF, 30810b57cec5SDimitry Andric BitVector &SavedRegs, 30820b57cec5SDimitry Andric RegScavenger *RS) const { 30830b57cec5SDimitry Andric TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 30840b57cec5SDimitry Andric 30850b57cec5SDimitry Andric // Spill the BasePtr if it's used. 30860b57cec5SDimitry Andric if (TRI->hasBasePointer(MF)) { 30878bcb0991SDimitry Andric Register BasePtr = TRI->getBaseRegister(); 30880b57cec5SDimitry Andric if (STI.isTarget64BitILP32()) 30890b57cec5SDimitry Andric BasePtr = getX86SubSuperRegister(BasePtr, 64); 30900b57cec5SDimitry Andric SavedRegs.set(BasePtr); 30910b57cec5SDimitry Andric } 30920b57cec5SDimitry Andric } 30930b57cec5SDimitry Andric 3094*5f757f3fSDimitry Andric static bool HasNestArgument(const MachineFunction *MF) { 30950b57cec5SDimitry Andric const Function &F = MF->getFunction(); 3096*5f757f3fSDimitry Andric for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 3097*5f757f3fSDimitry Andric I++) { 30988bcb0991SDimitry Andric if (I->hasNestAttr() && !I->use_empty()) 30990b57cec5SDimitry Andric return true; 31000b57cec5SDimitry Andric } 31010b57cec5SDimitry Andric return false; 31020b57cec5SDimitry Andric } 31030b57cec5SDimitry Andric 31040b57cec5SDimitry Andric /// GetScratchRegister - Get a temp register for performing work in the 31050b57cec5SDimitry Andric /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform 31060b57cec5SDimitry Andric /// and the properties of the function either one or two registers will be 31070b57cec5SDimitry Andric /// needed. Set primary to true for the first register, false for the second. 3108*5f757f3fSDimitry Andric static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64, 3109*5f757f3fSDimitry Andric const MachineFunction &MF, bool Primary) { 31100b57cec5SDimitry Andric CallingConv::ID CallingConvention = MF.getFunction().getCallingConv(); 31110b57cec5SDimitry Andric 31120b57cec5SDimitry Andric // Erlang stuff. 31130b57cec5SDimitry Andric if (CallingConvention == CallingConv::HiPE) { 31140b57cec5SDimitry Andric if (Is64Bit) 31150b57cec5SDimitry Andric return Primary ? X86::R14 : X86::R13; 31160b57cec5SDimitry Andric else 31170b57cec5SDimitry Andric return Primary ? X86::EBX : X86::EDI; 31180b57cec5SDimitry Andric } 31190b57cec5SDimitry Andric 31200b57cec5SDimitry Andric if (Is64Bit) { 31210b57cec5SDimitry Andric if (IsLP64) 31220b57cec5SDimitry Andric return Primary ? X86::R11 : X86::R12; 31230b57cec5SDimitry Andric else 31240b57cec5SDimitry Andric return Primary ? X86::R11D : X86::R12D; 31250b57cec5SDimitry Andric } 31260b57cec5SDimitry Andric 31270b57cec5SDimitry Andric bool IsNested = HasNestArgument(&MF); 31280b57cec5SDimitry Andric 31290b57cec5SDimitry Andric if (CallingConvention == CallingConv::X86_FastCall || 31308bcb0991SDimitry Andric CallingConvention == CallingConv::Fast || 31318bcb0991SDimitry Andric CallingConvention == CallingConv::Tail) { 31320b57cec5SDimitry Andric if (IsNested) 31330b57cec5SDimitry Andric report_fatal_error("Segmented stacks does not support fastcall with " 31340b57cec5SDimitry Andric "nested function."); 31350b57cec5SDimitry Andric return Primary ? X86::EAX : X86::ECX; 31360b57cec5SDimitry Andric } 31370b57cec5SDimitry Andric if (IsNested) 31380b57cec5SDimitry Andric return Primary ? X86::EDX : X86::EAX; 31390b57cec5SDimitry Andric return Primary ? X86::ECX : X86::EAX; 31400b57cec5SDimitry Andric } 31410b57cec5SDimitry Andric 31420b57cec5SDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual stack 31430b57cec5SDimitry Andric // limit. 31440b57cec5SDimitry Andric static const uint64_t kSplitStackAvailable = 256; 31450b57cec5SDimitry Andric 31460b57cec5SDimitry Andric void X86FrameLowering::adjustForSegmentedStacks( 31470b57cec5SDimitry Andric MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 31480b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 31490b57cec5SDimitry Andric uint64_t StackSize; 31500b57cec5SDimitry Andric unsigned TlsReg, TlsOffset; 31510b57cec5SDimitry Andric DebugLoc DL; 31520b57cec5SDimitry Andric 31530b57cec5SDimitry Andric // To support shrink-wrapping we would need to insert the new blocks 31540b57cec5SDimitry Andric // at the right place and update the branches to PrologueMBB. 31550b57cec5SDimitry Andric assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet"); 31560b57cec5SDimitry Andric 31570b57cec5SDimitry Andric unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true); 31580b57cec5SDimitry Andric assert(!MF.getRegInfo().isLiveIn(ScratchReg) && 31590b57cec5SDimitry Andric "Scratch register is live-in"); 31600b57cec5SDimitry Andric 31610b57cec5SDimitry Andric if (MF.getFunction().isVarArg()) 31620b57cec5SDimitry Andric report_fatal_error("Segmented stacks do not support vararg functions."); 31630b57cec5SDimitry Andric if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() && 31640b57cec5SDimitry Andric !STI.isTargetWin64() && !STI.isTargetFreeBSD() && 31650b57cec5SDimitry Andric !STI.isTargetDragonFly()) 31660b57cec5SDimitry Andric report_fatal_error("Segmented stacks not supported on this platform."); 31670b57cec5SDimitry Andric 31680b57cec5SDimitry Andric // Eventually StackSize will be calculated by a link-time pass; which will 31690b57cec5SDimitry Andric // also decide whether checking code needs to be injected into this particular 31700b57cec5SDimitry Andric // prologue. 31710b57cec5SDimitry Andric StackSize = MFI.getStackSize(); 31720b57cec5SDimitry Andric 317381ad6265SDimitry Andric if (!MFI.needsSplitStackProlog()) 31740b57cec5SDimitry Andric return; 31750b57cec5SDimitry Andric 31760b57cec5SDimitry Andric MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock(); 31770b57cec5SDimitry Andric MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock(); 31780b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 31790b57cec5SDimitry Andric bool IsNested = false; 31800b57cec5SDimitry Andric 31810b57cec5SDimitry Andric // We need to know if the function has a nest argument only in 64 bit mode. 31820b57cec5SDimitry Andric if (Is64Bit) 31830b57cec5SDimitry Andric IsNested = HasNestArgument(&MF); 31840b57cec5SDimitry Andric 31850b57cec5SDimitry Andric // The MOV R10, RAX needs to be in a different block, since the RET we emit in 31860b57cec5SDimitry Andric // allocMBB needs to be last (terminating) instruction. 31870b57cec5SDimitry Andric 31880b57cec5SDimitry Andric for (const auto &LI : PrologueMBB.liveins()) { 31890b57cec5SDimitry Andric allocMBB->addLiveIn(LI); 31900b57cec5SDimitry Andric checkMBB->addLiveIn(LI); 31910b57cec5SDimitry Andric } 31920b57cec5SDimitry Andric 31930b57cec5SDimitry Andric if (IsNested) 31940b57cec5SDimitry Andric allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D); 31950b57cec5SDimitry Andric 31960b57cec5SDimitry Andric MF.push_front(allocMBB); 31970b57cec5SDimitry Andric MF.push_front(checkMBB); 31980b57cec5SDimitry Andric 31990b57cec5SDimitry Andric // When the frame size is less than 256 we just compare the stack 32000b57cec5SDimitry Andric // boundary directly to the value of the stack pointer, per gcc. 32010b57cec5SDimitry Andric bool CompareStackPointer = StackSize < kSplitStackAvailable; 32020b57cec5SDimitry Andric 32030b57cec5SDimitry Andric // Read the limit off the current stacklet off the stack_guard location. 32040b57cec5SDimitry Andric if (Is64Bit) { 32050b57cec5SDimitry Andric if (STI.isTargetLinux()) { 32060b57cec5SDimitry Andric TlsReg = X86::FS; 32070b57cec5SDimitry Andric TlsOffset = IsLP64 ? 0x70 : 0x40; 32080b57cec5SDimitry Andric } else if (STI.isTargetDarwin()) { 32090b57cec5SDimitry Andric TlsReg = X86::GS; 32100b57cec5SDimitry Andric TlsOffset = 0x60 + 90 * 8; // See pthread_machdep.h. Steal TLS slot 90. 32110b57cec5SDimitry Andric } else if (STI.isTargetWin64()) { 32120b57cec5SDimitry Andric TlsReg = X86::GS; 32130b57cec5SDimitry Andric TlsOffset = 0x28; // pvArbitrary, reserved for application use 32140b57cec5SDimitry Andric } else if (STI.isTargetFreeBSD()) { 32150b57cec5SDimitry Andric TlsReg = X86::FS; 32160b57cec5SDimitry Andric TlsOffset = 0x18; 32170b57cec5SDimitry Andric } else if (STI.isTargetDragonFly()) { 32180b57cec5SDimitry Andric TlsReg = X86::FS; 32190b57cec5SDimitry Andric TlsOffset = 0x20; // use tls_tcb.tcb_segstack 32200b57cec5SDimitry Andric } else { 32210b57cec5SDimitry Andric report_fatal_error("Segmented stacks not supported on this platform."); 32220b57cec5SDimitry Andric } 32230b57cec5SDimitry Andric 32240b57cec5SDimitry Andric if (CompareStackPointer) 32250b57cec5SDimitry Andric ScratchReg = IsLP64 ? X86::RSP : X86::ESP; 32260b57cec5SDimitry Andric else 3227*5f757f3fSDimitry Andric BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), 3228*5f757f3fSDimitry Andric ScratchReg) 3229*5f757f3fSDimitry Andric .addReg(X86::RSP) 3230*5f757f3fSDimitry Andric .addImm(1) 3231*5f757f3fSDimitry Andric .addReg(0) 3232*5f757f3fSDimitry Andric .addImm(-StackSize) 3233*5f757f3fSDimitry Andric .addReg(0); 32340b57cec5SDimitry Andric 3235*5f757f3fSDimitry Andric BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)) 3236*5f757f3fSDimitry Andric .addReg(ScratchReg) 3237*5f757f3fSDimitry Andric .addReg(0) 3238*5f757f3fSDimitry Andric .addImm(1) 3239*5f757f3fSDimitry Andric .addReg(0) 3240*5f757f3fSDimitry Andric .addImm(TlsOffset) 3241*5f757f3fSDimitry Andric .addReg(TlsReg); 32420b57cec5SDimitry Andric } else { 32430b57cec5SDimitry Andric if (STI.isTargetLinux()) { 32440b57cec5SDimitry Andric TlsReg = X86::GS; 32450b57cec5SDimitry Andric TlsOffset = 0x30; 32460b57cec5SDimitry Andric } else if (STI.isTargetDarwin()) { 32470b57cec5SDimitry Andric TlsReg = X86::GS; 32480b57cec5SDimitry Andric TlsOffset = 0x48 + 90 * 4; 32490b57cec5SDimitry Andric } else if (STI.isTargetWin32()) { 32500b57cec5SDimitry Andric TlsReg = X86::FS; 32510b57cec5SDimitry Andric TlsOffset = 0x14; // pvArbitrary, reserved for application use 32520b57cec5SDimitry Andric } else if (STI.isTargetDragonFly()) { 32530b57cec5SDimitry Andric TlsReg = X86::FS; 32540b57cec5SDimitry Andric TlsOffset = 0x10; // use tls_tcb.tcb_segstack 32550b57cec5SDimitry Andric } else if (STI.isTargetFreeBSD()) { 32560b57cec5SDimitry Andric report_fatal_error("Segmented stacks not supported on FreeBSD i386."); 32570b57cec5SDimitry Andric } else { 32580b57cec5SDimitry Andric report_fatal_error("Segmented stacks not supported on this platform."); 32590b57cec5SDimitry Andric } 32600b57cec5SDimitry Andric 32610b57cec5SDimitry Andric if (CompareStackPointer) 32620b57cec5SDimitry Andric ScratchReg = X86::ESP; 32630b57cec5SDimitry Andric else 3264*5f757f3fSDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg) 3265*5f757f3fSDimitry Andric .addReg(X86::ESP) 3266*5f757f3fSDimitry Andric .addImm(1) 3267*5f757f3fSDimitry Andric .addReg(0) 3268*5f757f3fSDimitry Andric .addImm(-StackSize) 3269*5f757f3fSDimitry Andric .addReg(0); 32700b57cec5SDimitry Andric 32710b57cec5SDimitry Andric if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() || 32720b57cec5SDimitry Andric STI.isTargetDragonFly()) { 3273*5f757f3fSDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)) 3274*5f757f3fSDimitry Andric .addReg(ScratchReg) 3275*5f757f3fSDimitry Andric .addReg(0) 3276*5f757f3fSDimitry Andric .addImm(0) 3277*5f757f3fSDimitry Andric .addReg(0) 3278*5f757f3fSDimitry Andric .addImm(TlsOffset) 3279*5f757f3fSDimitry Andric .addReg(TlsReg); 32800b57cec5SDimitry Andric } else if (STI.isTargetDarwin()) { 32810b57cec5SDimitry Andric 32820b57cec5SDimitry Andric // TlsOffset doesn't fit into a mod r/m byte so we need an extra register. 32830b57cec5SDimitry Andric unsigned ScratchReg2; 32840b57cec5SDimitry Andric bool SaveScratch2; 32850b57cec5SDimitry Andric if (CompareStackPointer) { 32860b57cec5SDimitry Andric // The primary scratch register is available for holding the TLS offset. 32870b57cec5SDimitry Andric ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true); 32880b57cec5SDimitry Andric SaveScratch2 = false; 32890b57cec5SDimitry Andric } else { 32900b57cec5SDimitry Andric // Need to use a second register to hold the TLS offset 32910b57cec5SDimitry Andric ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false); 32920b57cec5SDimitry Andric 32930b57cec5SDimitry Andric // Unfortunately, with fastcc the second scratch register may hold an 32940b57cec5SDimitry Andric // argument. 32950b57cec5SDimitry Andric SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2); 32960b57cec5SDimitry Andric } 32970b57cec5SDimitry Andric 32980b57cec5SDimitry Andric // If Scratch2 is live-in then it needs to be saved. 32990b57cec5SDimitry Andric assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) && 33000b57cec5SDimitry Andric "Scratch register is live-in and not saved"); 33010b57cec5SDimitry Andric 33020b57cec5SDimitry Andric if (SaveScratch2) 33030b57cec5SDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::PUSH32r)) 33040b57cec5SDimitry Andric .addReg(ScratchReg2, RegState::Kill); 33050b57cec5SDimitry Andric 33060b57cec5SDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2) 33070b57cec5SDimitry Andric .addImm(TlsOffset); 33080b57cec5SDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)) 33090b57cec5SDimitry Andric .addReg(ScratchReg) 3310*5f757f3fSDimitry Andric .addReg(ScratchReg2) 3311*5f757f3fSDimitry Andric .addImm(1) 3312*5f757f3fSDimitry Andric .addReg(0) 33130b57cec5SDimitry Andric .addImm(0) 33140b57cec5SDimitry Andric .addReg(TlsReg); 33150b57cec5SDimitry Andric 33160b57cec5SDimitry Andric if (SaveScratch2) 33170b57cec5SDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2); 33180b57cec5SDimitry Andric } 33190b57cec5SDimitry Andric } 33200b57cec5SDimitry Andric 33210b57cec5SDimitry Andric // This jump is taken if SP >= (Stacklet Limit + Stack Space required). 33220b57cec5SDimitry Andric // It jumps to normal execution of the function body. 3323*5f757f3fSDimitry Andric BuildMI(checkMBB, DL, TII.get(X86::JCC_1)) 3324*5f757f3fSDimitry Andric .addMBB(&PrologueMBB) 3325*5f757f3fSDimitry Andric .addImm(X86::COND_A); 33260b57cec5SDimitry Andric 33270b57cec5SDimitry Andric // On 32 bit we first push the arguments size and then the frame size. On 64 33280b57cec5SDimitry Andric // bit, we pass the stack frame size in r10 and the argument size in r11. 33290b57cec5SDimitry Andric if (Is64Bit) { 33300b57cec5SDimitry Andric // Functions with nested arguments use R10, so it needs to be saved across 33310b57cec5SDimitry Andric // the call to _morestack 33320b57cec5SDimitry Andric 33330b57cec5SDimitry Andric const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX; 33340b57cec5SDimitry Andric const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D; 33350b57cec5SDimitry Andric const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D; 33360b57cec5SDimitry Andric const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr; 33370b57cec5SDimitry Andric 33380b57cec5SDimitry Andric if (IsNested) 33390b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10); 33400b57cec5SDimitry Andric 334104eeddc0SDimitry Andric BuildMI(allocMBB, DL, TII.get(getMOVriOpcode(IsLP64, StackSize)), Reg10) 33420b57cec5SDimitry Andric .addImm(StackSize); 334304eeddc0SDimitry Andric BuildMI(allocMBB, DL, 334404eeddc0SDimitry Andric TII.get(getMOVriOpcode(IsLP64, X86FI->getArgumentStackSize())), 334504eeddc0SDimitry Andric Reg11) 33460b57cec5SDimitry Andric .addImm(X86FI->getArgumentStackSize()); 33470b57cec5SDimitry Andric } else { 334806c3fb27SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::PUSH32i)) 33490b57cec5SDimitry Andric .addImm(X86FI->getArgumentStackSize()); 3350*5f757f3fSDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::PUSH32i)).addImm(StackSize); 33510b57cec5SDimitry Andric } 33520b57cec5SDimitry Andric 33530b57cec5SDimitry Andric // __morestack is in libgcc 33540b57cec5SDimitry Andric if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) { 33550b57cec5SDimitry Andric // Under the large code model, we cannot assume that __morestack lives 33560b57cec5SDimitry Andric // within 2^31 bytes of the call site, so we cannot use pc-relative 33570b57cec5SDimitry Andric // addressing. We cannot perform the call via a temporary register, 33580b57cec5SDimitry Andric // as the rax register may be used to store the static chain, and all 33590b57cec5SDimitry Andric // other suitable registers may be either callee-save or used for 33600b57cec5SDimitry Andric // parameter passing. We cannot use the stack at this point either 33610b57cec5SDimitry Andric // because __morestack manipulates the stack directly. 33620b57cec5SDimitry Andric // 33630b57cec5SDimitry Andric // To avoid these issues, perform an indirect call via a read-only memory 33640b57cec5SDimitry Andric // location containing the address. 33650b57cec5SDimitry Andric // 33660b57cec5SDimitry Andric // This solution is not perfect, as it assumes that the .rodata section 33670b57cec5SDimitry Andric // is laid out within 2^31 bytes of each function body, but this seems 33680b57cec5SDimitry Andric // to be sufficient for JIT. 33690b57cec5SDimitry Andric // FIXME: Add retpoline support and remove the error here.. 33700946e70aSDimitry Andric if (STI.useIndirectThunkCalls()) 33710b57cec5SDimitry Andric report_fatal_error("Emitting morestack calls on 64-bit with the large " 33720946e70aSDimitry Andric "code model and thunks not yet implemented."); 33730b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::CALL64m)) 33740b57cec5SDimitry Andric .addReg(X86::RIP) 33750b57cec5SDimitry Andric .addImm(0) 33760b57cec5SDimitry Andric .addReg(0) 33770b57cec5SDimitry Andric .addExternalSymbol("__morestack_addr") 33780b57cec5SDimitry Andric .addReg(0); 33790b57cec5SDimitry Andric } else { 33800b57cec5SDimitry Andric if (Is64Bit) 33810b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32)) 33820b57cec5SDimitry Andric .addExternalSymbol("__morestack"); 33830b57cec5SDimitry Andric else 33840b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32)) 33850b57cec5SDimitry Andric .addExternalSymbol("__morestack"); 33860b57cec5SDimitry Andric } 33870b57cec5SDimitry Andric 33880b57cec5SDimitry Andric if (IsNested) 33890b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10)); 33900b57cec5SDimitry Andric else 33910b57cec5SDimitry Andric BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET)); 33920b57cec5SDimitry Andric 33930b57cec5SDimitry Andric allocMBB->addSuccessor(&PrologueMBB); 33940b57cec5SDimitry Andric 33950b57cec5SDimitry Andric checkMBB->addSuccessor(allocMBB, BranchProbability::getZero()); 33960b57cec5SDimitry Andric checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne()); 33970b57cec5SDimitry Andric 33980b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 33990b57cec5SDimitry Andric MF.verify(); 34000b57cec5SDimitry Andric #endif 34010b57cec5SDimitry Andric } 34020b57cec5SDimitry Andric 34030b57cec5SDimitry Andric /// Lookup an ERTS parameter in the !hipe.literals named metadata node. 34040b57cec5SDimitry Andric /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets 34050b57cec5SDimitry Andric /// to fields it needs, through a named metadata node "hipe.literals" containing 34060b57cec5SDimitry Andric /// name-value pairs. 3407*5f757f3fSDimitry Andric static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD, 3408*5f757f3fSDimitry Andric const StringRef LiteralName) { 34090b57cec5SDimitry Andric for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) { 34100b57cec5SDimitry Andric MDNode *Node = HiPELiteralsMD->getOperand(i); 3411*5f757f3fSDimitry Andric if (Node->getNumOperands() != 2) 3412*5f757f3fSDimitry Andric continue; 34130b57cec5SDimitry Andric MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0)); 34140b57cec5SDimitry Andric ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1)); 3415*5f757f3fSDimitry Andric if (!NodeName || !NodeVal) 3416*5f757f3fSDimitry Andric continue; 34170b57cec5SDimitry Andric ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue()); 34180b57cec5SDimitry Andric if (ValConst && NodeName->getString() == LiteralName) { 34190b57cec5SDimitry Andric return ValConst->getZExtValue(); 34200b57cec5SDimitry Andric } 34210b57cec5SDimitry Andric } 34220b57cec5SDimitry Andric 3423*5f757f3fSDimitry Andric report_fatal_error("HiPE literal " + LiteralName + 3424*5f757f3fSDimitry Andric " required but not provided"); 34250b57cec5SDimitry Andric } 34260b57cec5SDimitry Andric 34278bcb0991SDimitry Andric // Return true if there are no non-ehpad successors to MBB and there are no 34288bcb0991SDimitry Andric // non-meta instructions between MBBI and MBB.end(). 34298bcb0991SDimitry Andric static bool blockEndIsUnreachable(const MachineBasicBlock &MBB, 34308bcb0991SDimitry Andric MachineBasicBlock::const_iterator MBBI) { 3431e8d8bef9SDimitry Andric return llvm::all_of( 3432e8d8bef9SDimitry Andric MBB.successors(), 34338bcb0991SDimitry Andric [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) && 34348bcb0991SDimitry Andric std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) { 34358bcb0991SDimitry Andric return MI.isMetaInstruction(); 34368bcb0991SDimitry Andric }); 34378bcb0991SDimitry Andric } 34388bcb0991SDimitry Andric 34390b57cec5SDimitry Andric /// Erlang programs may need a special prologue to handle the stack size they 34400b57cec5SDimitry Andric /// might need at runtime. That is because Erlang/OTP does not implement a C 34410b57cec5SDimitry Andric /// stack but uses a custom implementation of hybrid stack/heap architecture. 34420b57cec5SDimitry Andric /// (for more information see Eric Stenman's Ph.D. thesis: 34430b57cec5SDimitry Andric /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf) 34440b57cec5SDimitry Andric /// 34450b57cec5SDimitry Andric /// CheckStack: 34460b57cec5SDimitry Andric /// temp0 = sp - MaxStack 34470b57cec5SDimitry Andric /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart 34480b57cec5SDimitry Andric /// OldStart: 34490b57cec5SDimitry Andric /// ... 34500b57cec5SDimitry Andric /// IncStack: 34510b57cec5SDimitry Andric /// call inc_stack # doubles the stack space 34520b57cec5SDimitry Andric /// temp0 = sp - MaxStack 34530b57cec5SDimitry Andric /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart 34540b57cec5SDimitry Andric void X86FrameLowering::adjustForHiPEPrologue( 34550b57cec5SDimitry Andric MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 34560b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 34570b57cec5SDimitry Andric DebugLoc DL; 34580b57cec5SDimitry Andric 34590b57cec5SDimitry Andric // To support shrink-wrapping we would need to insert the new blocks 34600b57cec5SDimitry Andric // at the right place and update the branches to PrologueMBB. 34610b57cec5SDimitry Andric assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet"); 34620b57cec5SDimitry Andric 34630b57cec5SDimitry Andric // HiPE-specific values 3464*5f757f3fSDimitry Andric NamedMDNode *HiPELiteralsMD = 3465*5f757f3fSDimitry Andric MF.getMMI().getModule()->getNamedMetadata("hipe.literals"); 34660b57cec5SDimitry Andric if (!HiPELiteralsMD) 34670b57cec5SDimitry Andric report_fatal_error( 34680b57cec5SDimitry Andric "Can't generate HiPE prologue without runtime parameters"); 3469*5f757f3fSDimitry Andric const unsigned HipeLeafWords = getHiPELiteral( 3470*5f757f3fSDimitry Andric HiPELiteralsMD, Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS"); 34710b57cec5SDimitry Andric const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5; 34720b57cec5SDimitry Andric const unsigned Guaranteed = HipeLeafWords * SlotSize; 3473*5f757f3fSDimitry Andric unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs 3474*5f757f3fSDimitry Andric ? MF.getFunction().arg_size() - CCRegisteredArgs 3475*5f757f3fSDimitry Andric : 0; 34760b57cec5SDimitry Andric unsigned MaxStack = MFI.getStackSize() + CallerStkArity * SlotSize + SlotSize; 34770b57cec5SDimitry Andric 34780b57cec5SDimitry Andric assert(STI.isTargetLinux() && 34790b57cec5SDimitry Andric "HiPE prologue is only supported on Linux operating systems."); 34800b57cec5SDimitry Andric 34810b57cec5SDimitry Andric // Compute the largest caller's frame that is needed to fit the callees' 34820b57cec5SDimitry Andric // frames. This 'MaxStack' is computed from: 34830b57cec5SDimitry Andric // 34840b57cec5SDimitry Andric // a) the fixed frame size, which is the space needed for all spilled temps, 34850b57cec5SDimitry Andric // b) outgoing on-stack parameter areas, and 34860b57cec5SDimitry Andric // c) the minimum stack space this function needs to make available for the 34870b57cec5SDimitry Andric // functions it calls (a tunable ABI property). 34880b57cec5SDimitry Andric if (MFI.hasCalls()) { 34890b57cec5SDimitry Andric unsigned MoreStackForCalls = 0; 34900b57cec5SDimitry Andric 34910b57cec5SDimitry Andric for (auto &MBB : MF) { 34920b57cec5SDimitry Andric for (auto &MI : MBB) { 34930b57cec5SDimitry Andric if (!MI.isCall()) 34940b57cec5SDimitry Andric continue; 34950b57cec5SDimitry Andric 34960b57cec5SDimitry Andric // Get callee operand. 34970b57cec5SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 34980b57cec5SDimitry Andric 34990b57cec5SDimitry Andric // Only take account of global function calls (no closures etc.). 35000b57cec5SDimitry Andric if (!MO.isGlobal()) 35010b57cec5SDimitry Andric continue; 35020b57cec5SDimitry Andric 35030b57cec5SDimitry Andric const Function *F = dyn_cast<Function>(MO.getGlobal()); 35040b57cec5SDimitry Andric if (!F) 35050b57cec5SDimitry Andric continue; 35060b57cec5SDimitry Andric 35070b57cec5SDimitry Andric // Do not update 'MaxStack' for primitive and built-in functions 35080b57cec5SDimitry Andric // (encoded with names either starting with "erlang."/"bif_" or not 35090b57cec5SDimitry Andric // having a ".", such as a simple <Module>.<Function>.<Arity>, or an 35100b57cec5SDimitry Andric // "_", such as the BIF "suspend_0") as they are executed on another 35110b57cec5SDimitry Andric // stack. 3512349cc55cSDimitry Andric if (F->getName().contains("erlang.") || F->getName().contains("bif_") || 35130b57cec5SDimitry Andric F->getName().find_first_of("._") == StringRef::npos) 35140b57cec5SDimitry Andric continue; 35150b57cec5SDimitry Andric 3516*5f757f3fSDimitry Andric unsigned CalleeStkArity = F->arg_size() > CCRegisteredArgs 3517*5f757f3fSDimitry Andric ? F->arg_size() - CCRegisteredArgs 3518*5f757f3fSDimitry Andric : 0; 35190b57cec5SDimitry Andric if (HipeLeafWords - 1 > CalleeStkArity) 3520*5f757f3fSDimitry Andric MoreStackForCalls = 3521*5f757f3fSDimitry Andric std::max(MoreStackForCalls, 35220b57cec5SDimitry Andric (HipeLeafWords - 1 - CalleeStkArity) * SlotSize); 35230b57cec5SDimitry Andric } 35240b57cec5SDimitry Andric } 35250b57cec5SDimitry Andric MaxStack += MoreStackForCalls; 35260b57cec5SDimitry Andric } 35270b57cec5SDimitry Andric 35280b57cec5SDimitry Andric // If the stack frame needed is larger than the guaranteed then runtime checks 35290b57cec5SDimitry Andric // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue. 35300b57cec5SDimitry Andric if (MaxStack > Guaranteed) { 35310b57cec5SDimitry Andric MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock(); 35320b57cec5SDimitry Andric MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock(); 35330b57cec5SDimitry Andric 35340b57cec5SDimitry Andric for (const auto &LI : PrologueMBB.liveins()) { 35350b57cec5SDimitry Andric stackCheckMBB->addLiveIn(LI); 35360b57cec5SDimitry Andric incStackMBB->addLiveIn(LI); 35370b57cec5SDimitry Andric } 35380b57cec5SDimitry Andric 35390b57cec5SDimitry Andric MF.push_front(incStackMBB); 35400b57cec5SDimitry Andric MF.push_front(stackCheckMBB); 35410b57cec5SDimitry Andric 35420b57cec5SDimitry Andric unsigned ScratchReg, SPReg, PReg, SPLimitOffset; 35430b57cec5SDimitry Andric unsigned LEAop, CMPop, CALLop; 35440b57cec5SDimitry Andric SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT"); 35450b57cec5SDimitry Andric if (Is64Bit) { 35460b57cec5SDimitry Andric SPReg = X86::RSP; 35470b57cec5SDimitry Andric PReg = X86::RBP; 35480b57cec5SDimitry Andric LEAop = X86::LEA64r; 35490b57cec5SDimitry Andric CMPop = X86::CMP64rm; 35500b57cec5SDimitry Andric CALLop = X86::CALL64pcrel32; 35510b57cec5SDimitry Andric } else { 35520b57cec5SDimitry Andric SPReg = X86::ESP; 35530b57cec5SDimitry Andric PReg = X86::EBP; 35540b57cec5SDimitry Andric LEAop = X86::LEA32r; 35550b57cec5SDimitry Andric CMPop = X86::CMP32rm; 35560b57cec5SDimitry Andric CALLop = X86::CALLpcrel32; 35570b57cec5SDimitry Andric } 35580b57cec5SDimitry Andric 35590b57cec5SDimitry Andric ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true); 35600b57cec5SDimitry Andric assert(!MF.getRegInfo().isLiveIn(ScratchReg) && 35610b57cec5SDimitry Andric "HiPE prologue scratch register is live-in"); 35620b57cec5SDimitry Andric 35630b57cec5SDimitry Andric // Create new MBB for StackCheck: 3564*5f757f3fSDimitry Andric addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg), SPReg, 3565*5f757f3fSDimitry Andric false, -MaxStack); 35660b57cec5SDimitry Andric // SPLimitOffset is in a fixed heap location (pointed by BP). 3567*5f757f3fSDimitry Andric addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop)).addReg(ScratchReg), 3568*5f757f3fSDimitry Andric PReg, false, SPLimitOffset); 3569*5f757f3fSDimitry Andric BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)) 3570*5f757f3fSDimitry Andric .addMBB(&PrologueMBB) 3571*5f757f3fSDimitry Andric .addImm(X86::COND_AE); 35720b57cec5SDimitry Andric 35730b57cec5SDimitry Andric // Create new MBB for IncStack: 3574*5f757f3fSDimitry Andric BuildMI(incStackMBB, DL, TII.get(CALLop)).addExternalSymbol("inc_stack_0"); 3575*5f757f3fSDimitry Andric addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg), SPReg, 3576*5f757f3fSDimitry Andric false, -MaxStack); 3577*5f757f3fSDimitry Andric addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop)).addReg(ScratchReg), 3578*5f757f3fSDimitry Andric PReg, false, SPLimitOffset); 3579*5f757f3fSDimitry Andric BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)) 3580*5f757f3fSDimitry Andric .addMBB(incStackMBB) 3581*5f757f3fSDimitry Andric .addImm(X86::COND_LE); 35820b57cec5SDimitry Andric 35830b57cec5SDimitry Andric stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100}); 35840b57cec5SDimitry Andric stackCheckMBB->addSuccessor(incStackMBB, {1, 100}); 35850b57cec5SDimitry Andric incStackMBB->addSuccessor(&PrologueMBB, {99, 100}); 35860b57cec5SDimitry Andric incStackMBB->addSuccessor(incStackMBB, {1, 100}); 35870b57cec5SDimitry Andric } 35880b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 35890b57cec5SDimitry Andric MF.verify(); 35900b57cec5SDimitry Andric #endif 35910b57cec5SDimitry Andric } 35920b57cec5SDimitry Andric 35930b57cec5SDimitry Andric bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB, 35940b57cec5SDimitry Andric MachineBasicBlock::iterator MBBI, 35950b57cec5SDimitry Andric const DebugLoc &DL, 35960b57cec5SDimitry Andric int Offset) const { 35970b57cec5SDimitry Andric if (Offset <= 0) 35980b57cec5SDimitry Andric return false; 35990b57cec5SDimitry Andric 36000b57cec5SDimitry Andric if (Offset % SlotSize) 36010b57cec5SDimitry Andric return false; 36020b57cec5SDimitry Andric 36030b57cec5SDimitry Andric int NumPops = Offset / SlotSize; 36040b57cec5SDimitry Andric // This is only worth it if we have at most 2 pops. 36050b57cec5SDimitry Andric if (NumPops != 1 && NumPops != 2) 36060b57cec5SDimitry Andric return false; 36070b57cec5SDimitry Andric 36080b57cec5SDimitry Andric // Handle only the trivial case where the adjustment directly follows 36090b57cec5SDimitry Andric // a call. This is the most common one, anyway. 36100b57cec5SDimitry Andric if (MBBI == MBB.begin()) 36110b57cec5SDimitry Andric return false; 36120b57cec5SDimitry Andric MachineBasicBlock::iterator Prev = std::prev(MBBI); 36130b57cec5SDimitry Andric if (!Prev->isCall() || !Prev->getOperand(1).isRegMask()) 36140b57cec5SDimitry Andric return false; 36150b57cec5SDimitry Andric 36160b57cec5SDimitry Andric unsigned Regs[2]; 36170b57cec5SDimitry Andric unsigned FoundRegs = 0; 36180b57cec5SDimitry Andric 3619e8d8bef9SDimitry Andric const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 3620e8d8bef9SDimitry Andric const MachineOperand &RegMask = Prev->getOperand(1); 36210b57cec5SDimitry Andric 36220b57cec5SDimitry Andric auto &RegClass = 36230b57cec5SDimitry Andric Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass; 36240b57cec5SDimitry Andric // Try to find up to NumPops free registers. 36250b57cec5SDimitry Andric for (auto Candidate : RegClass) { 36260b57cec5SDimitry Andric // Poor man's liveness: 36270b57cec5SDimitry Andric // Since we're immediately after a call, any register that is clobbered 36280b57cec5SDimitry Andric // by the call and not defined by it can be considered dead. 36290b57cec5SDimitry Andric if (!RegMask.clobbersPhysReg(Candidate)) 36300b57cec5SDimitry Andric continue; 36310b57cec5SDimitry Andric 36320b57cec5SDimitry Andric // Don't clobber reserved registers 36330b57cec5SDimitry Andric if (MRI.isReserved(Candidate)) 36340b57cec5SDimitry Andric continue; 36350b57cec5SDimitry Andric 36360b57cec5SDimitry Andric bool IsDef = false; 36370b57cec5SDimitry Andric for (const MachineOperand &MO : Prev->implicit_operands()) { 36380b57cec5SDimitry Andric if (MO.isReg() && MO.isDef() && 36390b57cec5SDimitry Andric TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) { 36400b57cec5SDimitry Andric IsDef = true; 36410b57cec5SDimitry Andric break; 36420b57cec5SDimitry Andric } 36430b57cec5SDimitry Andric } 36440b57cec5SDimitry Andric 36450b57cec5SDimitry Andric if (IsDef) 36460b57cec5SDimitry Andric continue; 36470b57cec5SDimitry Andric 36480b57cec5SDimitry Andric Regs[FoundRegs++] = Candidate; 36490b57cec5SDimitry Andric if (FoundRegs == (unsigned)NumPops) 36500b57cec5SDimitry Andric break; 36510b57cec5SDimitry Andric } 36520b57cec5SDimitry Andric 36530b57cec5SDimitry Andric if (FoundRegs == 0) 36540b57cec5SDimitry Andric return false; 36550b57cec5SDimitry Andric 36560b57cec5SDimitry Andric // If we found only one free register, but need two, reuse the same one twice. 36570b57cec5SDimitry Andric while (FoundRegs < (unsigned)NumPops) 36580b57cec5SDimitry Andric Regs[FoundRegs++] = Regs[0]; 36590b57cec5SDimitry Andric 36600b57cec5SDimitry Andric for (int i = 0; i < NumPops; ++i) 3661*5f757f3fSDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), 3662*5f757f3fSDimitry Andric Regs[i]); 36630b57cec5SDimitry Andric 36640b57cec5SDimitry Andric return true; 36650b57cec5SDimitry Andric } 36660b57cec5SDimitry Andric 3667*5f757f3fSDimitry Andric MachineBasicBlock::iterator X86FrameLowering::eliminateCallFramePseudoInstr( 3668*5f757f3fSDimitry Andric MachineFunction &MF, MachineBasicBlock &MBB, 36690b57cec5SDimitry Andric MachineBasicBlock::iterator I) const { 36700b57cec5SDimitry Andric bool reserveCallFrame = hasReservedCallFrame(MF); 36710b57cec5SDimitry Andric unsigned Opcode = I->getOpcode(); 36720b57cec5SDimitry Andric bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode(); 3673fe6060f1SDimitry Andric DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased. 36748bcb0991SDimitry Andric uint64_t Amount = TII.getFrameSize(*I); 36750b57cec5SDimitry Andric uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0; 36760b57cec5SDimitry Andric I = MBB.erase(I); 36770b57cec5SDimitry Andric auto InsertPos = skipDebugInstructionsForward(I, MBB.end()); 36780b57cec5SDimitry Andric 36795ffd83dbSDimitry Andric // Try to avoid emitting dead SP adjustments if the block end is unreachable, 36805ffd83dbSDimitry Andric // typically because the function is marked noreturn (abort, throw, 36815ffd83dbSDimitry Andric // assert_fail, etc). 36825ffd83dbSDimitry Andric if (isDestroy && blockEndIsUnreachable(MBB, I)) 36835ffd83dbSDimitry Andric return I; 36845ffd83dbSDimitry Andric 36850b57cec5SDimitry Andric if (!reserveCallFrame) { 36860b57cec5SDimitry Andric // If the stack pointer can be changed after prologue, turn the 36870b57cec5SDimitry Andric // adjcallstackup instruction into a 'sub ESP, <amt>' and the 36880b57cec5SDimitry Andric // adjcallstackdown instruction into 'add ESP, <amt>' 36890b57cec5SDimitry Andric 36900b57cec5SDimitry Andric // We need to keep the stack aligned properly. To do this, we round the 36910b57cec5SDimitry Andric // amount of space needed for the outgoing arguments up to the next 36920b57cec5SDimitry Andric // alignment boundary. 36935ffd83dbSDimitry Andric Amount = alignTo(Amount, getStackAlign()); 36940b57cec5SDimitry Andric 36950b57cec5SDimitry Andric const Function &F = MF.getFunction(); 36960b57cec5SDimitry Andric bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 3697480093f4SDimitry Andric bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves(); 36980b57cec5SDimitry Andric 36990b57cec5SDimitry Andric // If we have any exception handlers in this function, and we adjust 37000b57cec5SDimitry Andric // the SP before calls, we may need to indicate this to the unwinder 37010b57cec5SDimitry Andric // using GNU_ARGS_SIZE. Note that this may be necessary even when 37020b57cec5SDimitry Andric // Amount == 0, because the preceding function may have set a non-0 37030b57cec5SDimitry Andric // GNU_ARGS_SIZE. 37040b57cec5SDimitry Andric // TODO: We don't need to reset this between subsequent functions, 37050b57cec5SDimitry Andric // if it didn't change. 37060b57cec5SDimitry Andric bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty(); 37070b57cec5SDimitry Andric 37080b57cec5SDimitry Andric if (HasDwarfEHHandlers && !isDestroy && 37090b57cec5SDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences()) 37100b57cec5SDimitry Andric BuildCFI(MBB, InsertPos, DL, 37110b57cec5SDimitry Andric MCCFIInstruction::createGnuArgsSize(nullptr, Amount)); 37120b57cec5SDimitry Andric 37130b57cec5SDimitry Andric if (Amount == 0) 37140b57cec5SDimitry Andric return I; 37150b57cec5SDimitry Andric 37160b57cec5SDimitry Andric // Factor out the amount that gets handled inside the sequence 37170b57cec5SDimitry Andric // (Pushes of argument for frame setup, callee pops for frame destroy) 37180b57cec5SDimitry Andric Amount -= InternalAmt; 37190b57cec5SDimitry Andric 37200b57cec5SDimitry Andric // TODO: This is needed only if we require precise CFA. 37210b57cec5SDimitry Andric // If this is a callee-pop calling convention, emit a CFA adjust for 37220b57cec5SDimitry Andric // the amount the callee popped. 37230b57cec5SDimitry Andric if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF)) 37240b57cec5SDimitry Andric BuildCFI(MBB, InsertPos, DL, 37250b57cec5SDimitry Andric MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt)); 37260b57cec5SDimitry Andric 37270b57cec5SDimitry Andric // Add Amount to SP to destroy a frame, or subtract to setup. 37280b57cec5SDimitry Andric int64_t StackAdjustment = isDestroy ? Amount : -Amount; 37290b57cec5SDimitry Andric 37300b57cec5SDimitry Andric if (StackAdjustment) { 37310b57cec5SDimitry Andric // Merge with any previous or following adjustment instruction. Note: the 37320b57cec5SDimitry Andric // instructions merged with here do not have CFI, so their stack 37330b57cec5SDimitry Andric // adjustments do not feed into CfaAdjustment. 37340b57cec5SDimitry Andric StackAdjustment += mergeSPUpdates(MBB, InsertPos, true); 37350b57cec5SDimitry Andric StackAdjustment += mergeSPUpdates(MBB, InsertPos, false); 37360b57cec5SDimitry Andric 37370b57cec5SDimitry Andric if (StackAdjustment) { 37380b57cec5SDimitry Andric if (!(F.hasMinSize() && 37390b57cec5SDimitry Andric adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment))) 37400b57cec5SDimitry Andric BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment, 37410b57cec5SDimitry Andric /*InEpilogue=*/false); 37420b57cec5SDimitry Andric } 37430b57cec5SDimitry Andric } 37440b57cec5SDimitry Andric 37450b57cec5SDimitry Andric if (DwarfCFI && !hasFP(MF)) { 37460b57cec5SDimitry Andric // If we don't have FP, but need to generate unwind information, 37470b57cec5SDimitry Andric // we need to set the correct CFA offset after the stack adjustment. 37480b57cec5SDimitry Andric // How much we adjust the CFA offset depends on whether we're emitting 37490b57cec5SDimitry Andric // CFI only for EH purposes or for debugging. EH only requires the CFA 37500b57cec5SDimitry Andric // offset to be correct at each call site, while for debugging we want 37510b57cec5SDimitry Andric // it to be more precise. 37520b57cec5SDimitry Andric 37530b57cec5SDimitry Andric int64_t CfaAdjustment = -StackAdjustment; 37540b57cec5SDimitry Andric // TODO: When not using precise CFA, we also need to adjust for the 37550b57cec5SDimitry Andric // InternalAmt here. 37560b57cec5SDimitry Andric if (CfaAdjustment) { 3757*5f757f3fSDimitry Andric BuildCFI( 3758*5f757f3fSDimitry Andric MBB, InsertPos, DL, 3759*5f757f3fSDimitry Andric MCCFIInstruction::createAdjustCfaOffset(nullptr, CfaAdjustment)); 37600b57cec5SDimitry Andric } 37610b57cec5SDimitry Andric } 37620b57cec5SDimitry Andric 37630b57cec5SDimitry Andric return I; 37640b57cec5SDimitry Andric } 37650b57cec5SDimitry Andric 37665ffd83dbSDimitry Andric if (InternalAmt) { 37670b57cec5SDimitry Andric MachineBasicBlock::iterator CI = I; 37680b57cec5SDimitry Andric MachineBasicBlock::iterator B = MBB.begin(); 37690b57cec5SDimitry Andric while (CI != B && !std::prev(CI)->isCall()) 37700b57cec5SDimitry Andric --CI; 37710b57cec5SDimitry Andric BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false); 37720b57cec5SDimitry Andric } 37730b57cec5SDimitry Andric 37740b57cec5SDimitry Andric return I; 37750b57cec5SDimitry Andric } 37760b57cec5SDimitry Andric 37770b57cec5SDimitry Andric bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const { 37780b57cec5SDimitry Andric assert(MBB.getParent() && "Block is not attached to a function!"); 37790b57cec5SDimitry Andric const MachineFunction &MF = *MBB.getParent(); 3780fe6060f1SDimitry Andric if (!MBB.isLiveIn(X86::EFLAGS)) 3781fe6060f1SDimitry Andric return true; 3782fe6060f1SDimitry Andric 3783bdd1243dSDimitry Andric // If stack probes have to loop inline or call, that will clobber EFLAGS. 3784bdd1243dSDimitry Andric // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock. 3785bdd1243dSDimitry Andric const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 3786bdd1243dSDimitry Andric const X86TargetLowering &TLI = *STI.getTargetLowering(); 3787bdd1243dSDimitry Andric if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF)) 3788bdd1243dSDimitry Andric return false; 3789bdd1243dSDimitry Andric 3790fe6060f1SDimitry Andric const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 3791fe6060f1SDimitry Andric return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext(); 37920b57cec5SDimitry Andric } 37930b57cec5SDimitry Andric 37940b57cec5SDimitry Andric bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const { 37950b57cec5SDimitry Andric assert(MBB.getParent() && "Block is not attached to a function!"); 37960b57cec5SDimitry Andric 37970b57cec5SDimitry Andric // Win64 has strict requirements in terms of epilogue and we are 37980b57cec5SDimitry Andric // not taking a chance at messing with them. 37990b57cec5SDimitry Andric // I.e., unless this block is already an exit block, we can't use 38000b57cec5SDimitry Andric // it as an epilogue. 38010b57cec5SDimitry Andric if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock()) 38020b57cec5SDimitry Andric return false; 38030b57cec5SDimitry Andric 3804fe6060f1SDimitry Andric // Swift async context epilogue has a BTR instruction that clobbers parts of 3805fe6060f1SDimitry Andric // EFLAGS. 3806fe6060f1SDimitry Andric const MachineFunction &MF = *MBB.getParent(); 3807fe6060f1SDimitry Andric if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext()) 3808fe6060f1SDimitry Andric return !flagsNeedToBePreservedBeforeTheTerminators(MBB); 3809fe6060f1SDimitry Andric 38100b57cec5SDimitry Andric if (canUseLEAForSPInEpilogue(*MBB.getParent())) 38110b57cec5SDimitry Andric return true; 38120b57cec5SDimitry Andric 38130b57cec5SDimitry Andric // If we cannot use LEA to adjust SP, we may need to use ADD, which 38140b57cec5SDimitry Andric // clobbers the EFLAGS. Check that we do not need to preserve it, 38150b57cec5SDimitry Andric // otherwise, conservatively assume this is not 38160b57cec5SDimitry Andric // safe to insert the epilogue here. 38170b57cec5SDimitry Andric return !flagsNeedToBePreservedBeforeTheTerminators(MBB); 38180b57cec5SDimitry Andric } 38190b57cec5SDimitry Andric 38200b57cec5SDimitry Andric bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const { 38210b57cec5SDimitry Andric // If we may need to emit frameless compact unwind information, give 38220b57cec5SDimitry Andric // up as this is currently broken: PR25614. 3823e8d8bef9SDimitry Andric bool CompactUnwind = 3824e8d8bef9SDimitry Andric MF.getMMI().getContext().getObjectFileInfo()->getCompactUnwindSection() != 3825e8d8bef9SDimitry Andric nullptr; 3826e8d8bef9SDimitry Andric return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) || 3827e8d8bef9SDimitry Andric !CompactUnwind) && 3828e8d8bef9SDimitry Andric // The lowering of segmented stack and HiPE only support entry 3829e8d8bef9SDimitry Andric // blocks as prologue blocks: PR26107. This limitation may be 3830e8d8bef9SDimitry Andric // lifted if we fix: 38310b57cec5SDimitry Andric // - adjustForSegmentedStacks 38320b57cec5SDimitry Andric // - adjustForHiPEPrologue 38330b57cec5SDimitry Andric MF.getFunction().getCallingConv() != CallingConv::HiPE && 38340b57cec5SDimitry Andric !MF.shouldSplitStack(); 38350b57cec5SDimitry Andric } 38360b57cec5SDimitry Andric 38370b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers( 38380b57cec5SDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 38390b57cec5SDimitry Andric const DebugLoc &DL, bool RestoreSP) const { 38400b57cec5SDimitry Andric assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env"); 38410b57cec5SDimitry Andric assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32"); 38420b57cec5SDimitry Andric assert(STI.is32Bit() && !Uses64BitFramePtr && 38430b57cec5SDimitry Andric "restoring EBP/ESI on non-32-bit target"); 38440b57cec5SDimitry Andric 38450b57cec5SDimitry Andric MachineFunction &MF = *MBB.getParent(); 38468bcb0991SDimitry Andric Register FramePtr = TRI->getFrameRegister(MF); 38478bcb0991SDimitry Andric Register BasePtr = TRI->getBaseRegister(); 38480b57cec5SDimitry Andric WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo(); 38490b57cec5SDimitry Andric X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 38500b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 38510b57cec5SDimitry Andric 38520b57cec5SDimitry Andric // FIXME: Don't set FrameSetup flag in catchret case. 38530b57cec5SDimitry Andric 38540b57cec5SDimitry Andric int FI = FuncInfo.EHRegNodeFrameIndex; 38550b57cec5SDimitry Andric int EHRegSize = MFI.getObjectSize(FI); 38560b57cec5SDimitry Andric 38570b57cec5SDimitry Andric if (RestoreSP) { 38580b57cec5SDimitry Andric // MOV32rm -EHRegSize(%ebp), %esp 38590b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP), 38600b57cec5SDimitry Andric X86::EBP, true, -EHRegSize) 38610b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 38620b57cec5SDimitry Andric } 38630b57cec5SDimitry Andric 38645ffd83dbSDimitry Andric Register UsedReg; 3865e8d8bef9SDimitry Andric int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed(); 38660b57cec5SDimitry Andric int EndOffset = -EHRegOffset - EHRegSize; 38670b57cec5SDimitry Andric FuncInfo.EHRegNodeEndOffset = EndOffset; 38680b57cec5SDimitry Andric 38690b57cec5SDimitry Andric if (UsedReg == FramePtr) { 38700b57cec5SDimitry Andric // ADD $offset, %ebp 387106c3fb27SDimitry Andric unsigned ADDri = getADDriOpcode(false); 38720b57cec5SDimitry Andric BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr) 38730b57cec5SDimitry Andric .addReg(FramePtr) 38740b57cec5SDimitry Andric .addImm(EndOffset) 38750b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup) 38760b57cec5SDimitry Andric ->getOperand(3) 38770b57cec5SDimitry Andric .setIsDead(); 38780b57cec5SDimitry Andric assert(EndOffset >= 0 && 38790b57cec5SDimitry Andric "end of registration object above normal EBP position!"); 38800b57cec5SDimitry Andric } else if (UsedReg == BasePtr) { 38810b57cec5SDimitry Andric // LEA offset(%ebp), %esi 38820b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr), 38830b57cec5SDimitry Andric FramePtr, false, EndOffset) 38840b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 38850b57cec5SDimitry Andric // MOV32rm SavedEBPOffset(%esi), %ebp 38860b57cec5SDimitry Andric assert(X86FI->getHasSEHFramePtrSave()); 38870b57cec5SDimitry Andric int Offset = 3888e8d8bef9SDimitry Andric getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg) 3889e8d8bef9SDimitry Andric .getFixed(); 38900b57cec5SDimitry Andric assert(UsedReg == BasePtr); 38910b57cec5SDimitry Andric addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr), 38920b57cec5SDimitry Andric UsedReg, true, Offset) 38930b57cec5SDimitry Andric .setMIFlag(MachineInstr::FrameSetup); 38940b57cec5SDimitry Andric } else { 38950b57cec5SDimitry Andric llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr"); 38960b57cec5SDimitry Andric } 38970b57cec5SDimitry Andric return MBBI; 38980b57cec5SDimitry Andric } 38990b57cec5SDimitry Andric 39000b57cec5SDimitry Andric int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const { 39010b57cec5SDimitry Andric return TRI->getSlotSize(); 39020b57cec5SDimitry Andric } 39030b57cec5SDimitry Andric 39045ffd83dbSDimitry Andric Register 39055ffd83dbSDimitry Andric X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const { 390606c3fb27SDimitry Andric return StackPtr; 390706c3fb27SDimitry Andric } 390806c3fb27SDimitry Andric 390906c3fb27SDimitry Andric TargetFrameLowering::DwarfFrameBase 391006c3fb27SDimitry Andric X86FrameLowering::getDwarfFrameBase(const MachineFunction &MF) const { 391106c3fb27SDimitry Andric const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 391206c3fb27SDimitry Andric Register FrameRegister = RI->getFrameRegister(MF); 391306c3fb27SDimitry Andric if (getInitialCFARegister(MF) == FrameRegister && 391406c3fb27SDimitry Andric MF.getInfo<X86MachineFunctionInfo>()->hasCFIAdjustCfa()) { 391506c3fb27SDimitry Andric DwarfFrameBase FrameBase; 391606c3fb27SDimitry Andric FrameBase.Kind = DwarfFrameBase::CFA; 391706c3fb27SDimitry Andric FrameBase.Location.Offset = 391806c3fb27SDimitry Andric -MF.getFrameInfo().getStackSize() - getInitialCFAOffset(MF); 391906c3fb27SDimitry Andric return FrameBase; 392006c3fb27SDimitry Andric } 392106c3fb27SDimitry Andric 392206c3fb27SDimitry Andric return DwarfFrameBase{DwarfFrameBase::Register, {FrameRegister}}; 39230b57cec5SDimitry Andric } 39240b57cec5SDimitry Andric 39250b57cec5SDimitry Andric namespace { 39260b57cec5SDimitry Andric // Struct used by orderFrameObjects to help sort the stack objects. 39270b57cec5SDimitry Andric struct X86FrameSortingObject { 39280b57cec5SDimitry Andric bool IsValid = false; // true if we care about this Object. 39290b57cec5SDimitry Andric unsigned ObjectIndex = 0; // Index of Object into MFI list. 39300b57cec5SDimitry Andric unsigned ObjectSize = 0; // Size of Object in bytes. 39315ffd83dbSDimitry Andric Align ObjectAlignment = Align(1); // Alignment of Object in bytes. 39320b57cec5SDimitry Andric unsigned ObjectNumUses = 0; // Object static number of uses. 39330b57cec5SDimitry Andric }; 39340b57cec5SDimitry Andric 39350b57cec5SDimitry Andric // The comparison function we use for std::sort to order our local 39360b57cec5SDimitry Andric // stack symbols. The current algorithm is to use an estimated 39370b57cec5SDimitry Andric // "density". This takes into consideration the size and number of 39380b57cec5SDimitry Andric // uses each object has in order to roughly minimize code size. 39390b57cec5SDimitry Andric // So, for example, an object of size 16B that is referenced 5 times 39400b57cec5SDimitry Andric // will get higher priority than 4 4B objects referenced 1 time each. 39410b57cec5SDimitry Andric // It's not perfect and we may be able to squeeze a few more bytes out of 39420b57cec5SDimitry Andric // it (for example : 0(esp) requires fewer bytes, symbols allocated at the 39430b57cec5SDimitry Andric // fringe end can have special consideration, given their size is less 39440b57cec5SDimitry Andric // important, etc.), but the algorithmic complexity grows too much to be 39450b57cec5SDimitry Andric // worth the extra gains we get. This gets us pretty close. 39460b57cec5SDimitry Andric // The final order leaves us with objects with highest priority going 39470b57cec5SDimitry Andric // at the end of our list. 39480b57cec5SDimitry Andric struct X86FrameSortingComparator { 39490b57cec5SDimitry Andric inline bool operator()(const X86FrameSortingObject &A, 3950e8d8bef9SDimitry Andric const X86FrameSortingObject &B) const { 39510b57cec5SDimitry Andric uint64_t DensityAScaled, DensityBScaled; 39520b57cec5SDimitry Andric 39530b57cec5SDimitry Andric // For consistency in our comparison, all invalid objects are placed 39540b57cec5SDimitry Andric // at the end. This also allows us to stop walking when we hit the 39550b57cec5SDimitry Andric // first invalid item after it's all sorted. 39560b57cec5SDimitry Andric if (!A.IsValid) 39570b57cec5SDimitry Andric return false; 39580b57cec5SDimitry Andric if (!B.IsValid) 39590b57cec5SDimitry Andric return true; 39600b57cec5SDimitry Andric 39610b57cec5SDimitry Andric // The density is calculated by doing : 39620b57cec5SDimitry Andric // (double)DensityA = A.ObjectNumUses / A.ObjectSize 39630b57cec5SDimitry Andric // (double)DensityB = B.ObjectNumUses / B.ObjectSize 39640b57cec5SDimitry Andric // Since this approach may cause inconsistencies in 39650b57cec5SDimitry Andric // the floating point <, >, == comparisons, depending on the floating 39660b57cec5SDimitry Andric // point model with which the compiler was built, we're going 39670b57cec5SDimitry Andric // to scale both sides by multiplying with 39680b57cec5SDimitry Andric // A.ObjectSize * B.ObjectSize. This ends up factoring away 39690b57cec5SDimitry Andric // the division and, with it, the need for any floating point 39700b57cec5SDimitry Andric // arithmetic. 39710b57cec5SDimitry Andric DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) * 39720b57cec5SDimitry Andric static_cast<uint64_t>(B.ObjectSize); 39730b57cec5SDimitry Andric DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) * 39740b57cec5SDimitry Andric static_cast<uint64_t>(A.ObjectSize); 39750b57cec5SDimitry Andric 39760b57cec5SDimitry Andric // If the two densities are equal, prioritize highest alignment 39770b57cec5SDimitry Andric // objects. This allows for similar alignment objects 39780b57cec5SDimitry Andric // to be packed together (given the same density). 39790b57cec5SDimitry Andric // There's room for improvement here, also, since we can pack 39800b57cec5SDimitry Andric // similar alignment (different density) objects next to each 39810b57cec5SDimitry Andric // other to save padding. This will also require further 39820b57cec5SDimitry Andric // complexity/iterations, and the overall gain isn't worth it, 39830b57cec5SDimitry Andric // in general. Something to keep in mind, though. 39840b57cec5SDimitry Andric if (DensityAScaled == DensityBScaled) 39850b57cec5SDimitry Andric return A.ObjectAlignment < B.ObjectAlignment; 39860b57cec5SDimitry Andric 39870b57cec5SDimitry Andric return DensityAScaled < DensityBScaled; 39880b57cec5SDimitry Andric } 39890b57cec5SDimitry Andric }; 39900b57cec5SDimitry Andric } // namespace 39910b57cec5SDimitry Andric 39920b57cec5SDimitry Andric // Order the symbols in the local stack. 39930b57cec5SDimitry Andric // We want to place the local stack objects in some sort of sensible order. 39940b57cec5SDimitry Andric // The heuristic we use is to try and pack them according to static number 39950b57cec5SDimitry Andric // of uses and size of object in order to minimize code size. 39960b57cec5SDimitry Andric void X86FrameLowering::orderFrameObjects( 39970b57cec5SDimitry Andric const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const { 39980b57cec5SDimitry Andric const MachineFrameInfo &MFI = MF.getFrameInfo(); 39990b57cec5SDimitry Andric 40000b57cec5SDimitry Andric // Don't waste time if there's nothing to do. 40010b57cec5SDimitry Andric if (ObjectsToAllocate.empty()) 40020b57cec5SDimitry Andric return; 40030b57cec5SDimitry Andric 40040b57cec5SDimitry Andric // Create an array of all MFI objects. We won't need all of these 40050b57cec5SDimitry Andric // objects, but we're going to create a full array of them to make 40060b57cec5SDimitry Andric // it easier to index into when we're counting "uses" down below. 40070b57cec5SDimitry Andric // We want to be able to easily/cheaply access an object by simply 40080b57cec5SDimitry Andric // indexing into it, instead of having to search for it every time. 40090b57cec5SDimitry Andric std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd()); 40100b57cec5SDimitry Andric 40110b57cec5SDimitry Andric // Walk the objects we care about and mark them as such in our working 40120b57cec5SDimitry Andric // struct. 40130b57cec5SDimitry Andric for (auto &Obj : ObjectsToAllocate) { 40140b57cec5SDimitry Andric SortingObjects[Obj].IsValid = true; 40150b57cec5SDimitry Andric SortingObjects[Obj].ObjectIndex = Obj; 40165ffd83dbSDimitry Andric SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj); 40170b57cec5SDimitry Andric // Set the size. 40180b57cec5SDimitry Andric int ObjectSize = MFI.getObjectSize(Obj); 40190b57cec5SDimitry Andric if (ObjectSize == 0) 40200b57cec5SDimitry Andric // Variable size. Just use 4. 40210b57cec5SDimitry Andric SortingObjects[Obj].ObjectSize = 4; 40220b57cec5SDimitry Andric else 40230b57cec5SDimitry Andric SortingObjects[Obj].ObjectSize = ObjectSize; 40240b57cec5SDimitry Andric } 40250b57cec5SDimitry Andric 40260b57cec5SDimitry Andric // Count the number of uses for each object. 40270b57cec5SDimitry Andric for (auto &MBB : MF) { 40280b57cec5SDimitry Andric for (auto &MI : MBB) { 40290b57cec5SDimitry Andric if (MI.isDebugInstr()) 40300b57cec5SDimitry Andric continue; 40310b57cec5SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 40320b57cec5SDimitry Andric // Check to see if it's a local stack symbol. 40330b57cec5SDimitry Andric if (!MO.isFI()) 40340b57cec5SDimitry Andric continue; 40350b57cec5SDimitry Andric int Index = MO.getIndex(); 40360b57cec5SDimitry Andric // Check to see if it falls within our range, and is tagged 40370b57cec5SDimitry Andric // to require ordering. 40380b57cec5SDimitry Andric if (Index >= 0 && Index < MFI.getObjectIndexEnd() && 40390b57cec5SDimitry Andric SortingObjects[Index].IsValid) 40400b57cec5SDimitry Andric SortingObjects[Index].ObjectNumUses++; 40410b57cec5SDimitry Andric } 40420b57cec5SDimitry Andric } 40430b57cec5SDimitry Andric } 40440b57cec5SDimitry Andric 40450b57cec5SDimitry Andric // Sort the objects using X86FrameSortingAlgorithm (see its comment for 40460b57cec5SDimitry Andric // info). 40470b57cec5SDimitry Andric llvm::stable_sort(SortingObjects, X86FrameSortingComparator()); 40480b57cec5SDimitry Andric 40490b57cec5SDimitry Andric // Now modify the original list to represent the final order that 40500b57cec5SDimitry Andric // we want. The order will depend on whether we're going to access them 40510b57cec5SDimitry Andric // from the stack pointer or the frame pointer. For SP, the list should 40520b57cec5SDimitry Andric // end up with the END containing objects that we want with smaller offsets. 40530b57cec5SDimitry Andric // For FP, it should be flipped. 40540b57cec5SDimitry Andric int i = 0; 40550b57cec5SDimitry Andric for (auto &Obj : SortingObjects) { 40560b57cec5SDimitry Andric // All invalid items are sorted at the end, so it's safe to stop. 40570b57cec5SDimitry Andric if (!Obj.IsValid) 40580b57cec5SDimitry Andric break; 40590b57cec5SDimitry Andric ObjectsToAllocate[i++] = Obj.ObjectIndex; 40600b57cec5SDimitry Andric } 40610b57cec5SDimitry Andric 40620b57cec5SDimitry Andric // Flip it if we're accessing off of the FP. 4063fe6060f1SDimitry Andric if (!TRI->hasStackRealignment(MF) && hasFP(MF)) 40640b57cec5SDimitry Andric std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end()); 40650b57cec5SDimitry Andric } 40660b57cec5SDimitry Andric 4067*5f757f3fSDimitry Andric unsigned 4068*5f757f3fSDimitry Andric X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const { 40690b57cec5SDimitry Andric // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue. 40700b57cec5SDimitry Andric unsigned Offset = 16; 40710b57cec5SDimitry Andric // RBP is immediately pushed. 40720b57cec5SDimitry Andric Offset += SlotSize; 40730b57cec5SDimitry Andric // All callee-saved registers are then pushed. 40740b57cec5SDimitry Andric Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize(); 40750b57cec5SDimitry Andric // Every funclet allocates enough stack space for the largest outgoing call. 40760b57cec5SDimitry Andric Offset += getWinEHFuncletFrameSize(MF); 40770b57cec5SDimitry Andric return Offset; 40780b57cec5SDimitry Andric } 40790b57cec5SDimitry Andric 40800b57cec5SDimitry Andric void X86FrameLowering::processFunctionBeforeFrameFinalized( 40810b57cec5SDimitry Andric MachineFunction &MF, RegScavenger *RS) const { 40820b57cec5SDimitry Andric // Mark the function as not having WinCFI. We will set it back to true in 40830b57cec5SDimitry Andric // emitPrologue if it gets called and emits CFI. 40840b57cec5SDimitry Andric MF.setHasWinCFI(false); 40850b57cec5SDimitry Andric 4086e8d8bef9SDimitry Andric // If we are using Windows x64 CFI, ensure that the stack is always 8 byte 4087e8d8bef9SDimitry Andric // aligned. The format doesn't support misaligned stack adjustments. 4088e8d8bef9SDimitry Andric if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) 4089e8d8bef9SDimitry Andric MF.getFrameInfo().ensureMaxAlignment(Align(SlotSize)); 4090e8d8bef9SDimitry Andric 40910b57cec5SDimitry Andric // If this function isn't doing Win64-style C++ EH, we don't need to do 40920b57cec5SDimitry Andric // anything. 4093e8d8bef9SDimitry Andric if (STI.is64Bit() && MF.hasEHFunclets() && 4094e8d8bef9SDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn()) == 4095e8d8bef9SDimitry Andric EHPersonality::MSVC_CXX) { 4096e8d8bef9SDimitry Andric adjustFrameForMsvcCxxEh(MF); 4097e8d8bef9SDimitry Andric } 4098e8d8bef9SDimitry Andric } 40990b57cec5SDimitry Andric 4100e8d8bef9SDimitry Andric void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const { 41010b57cec5SDimitry Andric // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset 41020b57cec5SDimitry Andric // relative to RSP after the prologue. Find the offset of the last fixed 41030b57cec5SDimitry Andric // object, so that we can allocate a slot immediately following it. If there 41040b57cec5SDimitry Andric // were no fixed objects, use offset -SlotSize, which is immediately after the 41050b57cec5SDimitry Andric // return address. Fixed objects have negative frame indices. 41060b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo(); 41070b57cec5SDimitry Andric WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo(); 41080b57cec5SDimitry Andric int64_t MinFixedObjOffset = -SlotSize; 41090b57cec5SDimitry Andric for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) 41100b57cec5SDimitry Andric MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I)); 41110b57cec5SDimitry Andric 41120b57cec5SDimitry Andric for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) { 41130b57cec5SDimitry Andric for (WinEHHandlerType &H : TBME.HandlerArray) { 41140b57cec5SDimitry Andric int FrameIndex = H.CatchObj.FrameIndex; 41150b57cec5SDimitry Andric if (FrameIndex != INT_MAX) { 41160b57cec5SDimitry Andric // Ensure alignment. 41175ffd83dbSDimitry Andric unsigned Align = MFI.getObjectAlign(FrameIndex).value(); 41180b57cec5SDimitry Andric MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align; 41190b57cec5SDimitry Andric MinFixedObjOffset -= MFI.getObjectSize(FrameIndex); 41200b57cec5SDimitry Andric MFI.setObjectOffset(FrameIndex, MinFixedObjOffset); 41210b57cec5SDimitry Andric } 41220b57cec5SDimitry Andric } 41230b57cec5SDimitry Andric } 41240b57cec5SDimitry Andric 41250b57cec5SDimitry Andric // Ensure alignment. 41260b57cec5SDimitry Andric MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8; 41270b57cec5SDimitry Andric int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize; 41280b57cec5SDimitry Andric int UnwindHelpFI = 41290b57cec5SDimitry Andric MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false); 41300b57cec5SDimitry Andric EHInfo.UnwindHelpFrameIdx = UnwindHelpFI; 41310b57cec5SDimitry Andric 41320b57cec5SDimitry Andric // Store -2 into UnwindHelp on function entry. We have to scan forwards past 41330b57cec5SDimitry Andric // other frame setup instructions. 41340b57cec5SDimitry Andric MachineBasicBlock &MBB = MF.front(); 41350b57cec5SDimitry Andric auto MBBI = MBB.begin(); 41360b57cec5SDimitry Andric while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) 41370b57cec5SDimitry Andric ++MBBI; 41380b57cec5SDimitry Andric 41390b57cec5SDimitry Andric DebugLoc DL = MBB.findDebugLoc(MBBI); 41400b57cec5SDimitry Andric addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)), 41410b57cec5SDimitry Andric UnwindHelpFI) 41420b57cec5SDimitry Andric .addImm(-2); 41430b57cec5SDimitry Andric } 41445ffd83dbSDimitry Andric 41455ffd83dbSDimitry Andric void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced( 41465ffd83dbSDimitry Andric MachineFunction &MF, RegScavenger *RS) const { 414706c3fb27SDimitry Andric auto *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 414806c3fb27SDimitry Andric 41495ffd83dbSDimitry Andric if (STI.is32Bit() && MF.hasEHFunclets()) 41505ffd83dbSDimitry Andric restoreWinEHStackPointersInParent(MF); 415106c3fb27SDimitry Andric // We have emitted prolog and epilog. Don't need stack pointer saving 415206c3fb27SDimitry Andric // instruction any more. 415306c3fb27SDimitry Andric if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) { 415406c3fb27SDimitry Andric MI->eraseFromParent(); 415506c3fb27SDimitry Andric X86FI->setStackPtrSaveMI(nullptr); 415606c3fb27SDimitry Andric } 41575ffd83dbSDimitry Andric } 41585ffd83dbSDimitry Andric 41595ffd83dbSDimitry Andric void X86FrameLowering::restoreWinEHStackPointersInParent( 41605ffd83dbSDimitry Andric MachineFunction &MF) const { 41615ffd83dbSDimitry Andric // 32-bit functions have to restore stack pointers when control is transferred 41625ffd83dbSDimitry Andric // back to the parent function. These blocks are identified as eh pads that 41635ffd83dbSDimitry Andric // are not funclet entries. 41645ffd83dbSDimitry Andric bool IsSEH = isAsynchronousEHPersonality( 41655ffd83dbSDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn())); 41665ffd83dbSDimitry Andric for (MachineBasicBlock &MBB : MF) { 41675ffd83dbSDimitry Andric bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry(); 41685ffd83dbSDimitry Andric if (NeedsRestore) 41695ffd83dbSDimitry Andric restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(), 41705ffd83dbSDimitry Andric /*RestoreSP=*/IsSEH); 41715ffd83dbSDimitry Andric } 41725ffd83dbSDimitry Andric } 4173