xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86DynAllocaExpander.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1349cc55cSDimitry Andric //===----- X86DynAllocaExpander.cpp - Expand DynAlloca pseudo instruction -===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This file defines a pass that expands DynAlloca pseudo-instructions.
10349cc55cSDimitry Andric //
11349cc55cSDimitry Andric // It performs a conservative analysis to determine whether each allocation
12349cc55cSDimitry Andric // falls within a region of the stack that is safe to use, or whether stack
13349cc55cSDimitry Andric // probes must be emitted.
14349cc55cSDimitry Andric //
15349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
16349cc55cSDimitry Andric 
17349cc55cSDimitry Andric #include "X86.h"
18349cc55cSDimitry Andric #include "X86InstrBuilder.h"
19349cc55cSDimitry Andric #include "X86InstrInfo.h"
20349cc55cSDimitry Andric #include "X86MachineFunctionInfo.h"
21349cc55cSDimitry Andric #include "X86Subtarget.h"
22349cc55cSDimitry Andric #include "llvm/ADT/MapVector.h"
23349cc55cSDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
24349cc55cSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
25349cc55cSDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
26349cc55cSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
27349cc55cSDimitry Andric #include "llvm/CodeGen/Passes.h"
28349cc55cSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
29349cc55cSDimitry Andric #include "llvm/IR/Function.h"
30349cc55cSDimitry Andric #include "llvm/Support/raw_ostream.h"
31349cc55cSDimitry Andric 
32349cc55cSDimitry Andric using namespace llvm;
33349cc55cSDimitry Andric 
34349cc55cSDimitry Andric namespace {
35349cc55cSDimitry Andric 
36349cc55cSDimitry Andric class X86DynAllocaExpander : public MachineFunctionPass {
37349cc55cSDimitry Andric public:
X86DynAllocaExpander()38349cc55cSDimitry Andric   X86DynAllocaExpander() : MachineFunctionPass(ID) {}
39349cc55cSDimitry Andric 
40349cc55cSDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
41349cc55cSDimitry Andric 
42349cc55cSDimitry Andric private:
43349cc55cSDimitry Andric   /// Strategies for lowering a DynAlloca.
44349cc55cSDimitry Andric   enum Lowering { TouchAndSub, Sub, Probe };
45349cc55cSDimitry Andric 
46349cc55cSDimitry Andric   /// Deterministic-order map from DynAlloca instruction to desired lowering.
47349cc55cSDimitry Andric   typedef MapVector<MachineInstr*, Lowering> LoweringMap;
48349cc55cSDimitry Andric 
49349cc55cSDimitry Andric   /// Compute which lowering to use for each DynAlloca instruction.
50349cc55cSDimitry Andric   void computeLowerings(MachineFunction &MF, LoweringMap& Lowerings);
51349cc55cSDimitry Andric 
52349cc55cSDimitry Andric   /// Get the appropriate lowering based on current offset and amount.
53349cc55cSDimitry Andric   Lowering getLowering(int64_t CurrentOffset, int64_t AllocaAmount);
54349cc55cSDimitry Andric 
55349cc55cSDimitry Andric   /// Lower a DynAlloca instruction.
56349cc55cSDimitry Andric   void lower(MachineInstr* MI, Lowering L);
57349cc55cSDimitry Andric 
58349cc55cSDimitry Andric   MachineRegisterInfo *MRI = nullptr;
59349cc55cSDimitry Andric   const X86Subtarget *STI = nullptr;
60349cc55cSDimitry Andric   const TargetInstrInfo *TII = nullptr;
61349cc55cSDimitry Andric   const X86RegisterInfo *TRI = nullptr;
62349cc55cSDimitry Andric   unsigned StackPtr = 0;
63349cc55cSDimitry Andric   unsigned SlotSize = 0;
64349cc55cSDimitry Andric   int64_t StackProbeSize = 0;
65349cc55cSDimitry Andric   bool NoStackArgProbe = false;
66349cc55cSDimitry Andric 
getPassName() const67349cc55cSDimitry Andric   StringRef getPassName() const override { return "X86 DynAlloca Expander"; }
68349cc55cSDimitry Andric   static char ID;
69349cc55cSDimitry Andric };
70349cc55cSDimitry Andric 
71349cc55cSDimitry Andric char X86DynAllocaExpander::ID = 0;
72349cc55cSDimitry Andric 
73349cc55cSDimitry Andric } // end anonymous namespace
74349cc55cSDimitry Andric 
createX86DynAllocaExpander()75349cc55cSDimitry Andric FunctionPass *llvm::createX86DynAllocaExpander() {
76349cc55cSDimitry Andric   return new X86DynAllocaExpander();
77349cc55cSDimitry Andric }
78349cc55cSDimitry Andric 
79349cc55cSDimitry Andric /// Return the allocation amount for a DynAlloca instruction, or -1 if unknown.
getDynAllocaAmount(MachineInstr * MI,MachineRegisterInfo * MRI)80349cc55cSDimitry Andric static int64_t getDynAllocaAmount(MachineInstr *MI, MachineRegisterInfo *MRI) {
81349cc55cSDimitry Andric   assert(MI->getOpcode() == X86::DYN_ALLOCA_32 ||
82349cc55cSDimitry Andric          MI->getOpcode() == X86::DYN_ALLOCA_64);
83349cc55cSDimitry Andric   assert(MI->getOperand(0).isReg());
84349cc55cSDimitry Andric 
85349cc55cSDimitry Andric   Register AmountReg = MI->getOperand(0).getReg();
86349cc55cSDimitry Andric   MachineInstr *Def = MRI->getUniqueVRegDef(AmountReg);
87349cc55cSDimitry Andric 
88349cc55cSDimitry Andric   if (!Def ||
89349cc55cSDimitry Andric       (Def->getOpcode() != X86::MOV32ri && Def->getOpcode() != X86::MOV64ri) ||
90349cc55cSDimitry Andric       !Def->getOperand(1).isImm())
91349cc55cSDimitry Andric     return -1;
92349cc55cSDimitry Andric 
93349cc55cSDimitry Andric   return Def->getOperand(1).getImm();
94349cc55cSDimitry Andric }
95349cc55cSDimitry Andric 
96349cc55cSDimitry Andric X86DynAllocaExpander::Lowering
getLowering(int64_t CurrentOffset,int64_t AllocaAmount)97349cc55cSDimitry Andric X86DynAllocaExpander::getLowering(int64_t CurrentOffset,
98349cc55cSDimitry Andric                                   int64_t AllocaAmount) {
99349cc55cSDimitry Andric   // For a non-constant amount or a large amount, we have to probe.
100349cc55cSDimitry Andric   if (AllocaAmount < 0 || AllocaAmount > StackProbeSize)
101349cc55cSDimitry Andric     return Probe;
102349cc55cSDimitry Andric 
103349cc55cSDimitry Andric   // If it fits within the safe region of the stack, just subtract.
104349cc55cSDimitry Andric   if (CurrentOffset + AllocaAmount <= StackProbeSize)
105349cc55cSDimitry Andric     return Sub;
106349cc55cSDimitry Andric 
107349cc55cSDimitry Andric   // Otherwise, touch the current tip of the stack, then subtract.
108349cc55cSDimitry Andric   return TouchAndSub;
109349cc55cSDimitry Andric }
110349cc55cSDimitry Andric 
isPushPop(const MachineInstr & MI)111349cc55cSDimitry Andric static bool isPushPop(const MachineInstr &MI) {
112349cc55cSDimitry Andric   switch (MI.getOpcode()) {
113349cc55cSDimitry Andric   case X86::PUSH32r:
114349cc55cSDimitry Andric   case X86::PUSH32rmm:
115349cc55cSDimitry Andric   case X86::PUSH32rmr:
116*06c3fb27SDimitry Andric   case X86::PUSH32i:
117349cc55cSDimitry Andric   case X86::PUSH64r:
118349cc55cSDimitry Andric   case X86::PUSH64rmm:
119349cc55cSDimitry Andric   case X86::PUSH64rmr:
120349cc55cSDimitry Andric   case X86::PUSH64i32:
121349cc55cSDimitry Andric   case X86::POP32r:
122349cc55cSDimitry Andric   case X86::POP64r:
123349cc55cSDimitry Andric     return true;
124349cc55cSDimitry Andric   default:
125349cc55cSDimitry Andric     return false;
126349cc55cSDimitry Andric   }
127349cc55cSDimitry Andric }
128349cc55cSDimitry Andric 
computeLowerings(MachineFunction & MF,LoweringMap & Lowerings)129349cc55cSDimitry Andric void X86DynAllocaExpander::computeLowerings(MachineFunction &MF,
130349cc55cSDimitry Andric                                             LoweringMap &Lowerings) {
131349cc55cSDimitry Andric   // Do a one-pass reverse post-order walk of the CFG to conservatively estimate
132349cc55cSDimitry Andric   // the offset between the stack pointer and the lowest touched part of the
133349cc55cSDimitry Andric   // stack, and use that to decide how to lower each DynAlloca instruction.
134349cc55cSDimitry Andric 
135349cc55cSDimitry Andric   // Initialize OutOffset[B], the stack offset at exit from B, to something big.
136349cc55cSDimitry Andric   DenseMap<MachineBasicBlock *, int64_t> OutOffset;
137349cc55cSDimitry Andric   for (MachineBasicBlock &MBB : MF)
138349cc55cSDimitry Andric     OutOffset[&MBB] = INT32_MAX;
139349cc55cSDimitry Andric 
140349cc55cSDimitry Andric   // Note: we don't know the offset at the start of the entry block since the
141349cc55cSDimitry Andric   // prologue hasn't been inserted yet, and how much that will adjust the stack
142349cc55cSDimitry Andric   // pointer depends on register spills, which have not been computed yet.
143349cc55cSDimitry Andric 
144349cc55cSDimitry Andric   // Compute the reverse post-order.
145349cc55cSDimitry Andric   ReversePostOrderTraversal<MachineFunction*> RPO(&MF);
146349cc55cSDimitry Andric 
147349cc55cSDimitry Andric   for (MachineBasicBlock *MBB : RPO) {
148349cc55cSDimitry Andric     int64_t Offset = -1;
149349cc55cSDimitry Andric     for (MachineBasicBlock *Pred : MBB->predecessors())
150349cc55cSDimitry Andric       Offset = std::max(Offset, OutOffset[Pred]);
151349cc55cSDimitry Andric     if (Offset == -1) Offset = INT32_MAX;
152349cc55cSDimitry Andric 
153349cc55cSDimitry Andric     for (MachineInstr &MI : *MBB) {
154349cc55cSDimitry Andric       if (MI.getOpcode() == X86::DYN_ALLOCA_32 ||
155349cc55cSDimitry Andric           MI.getOpcode() == X86::DYN_ALLOCA_64) {
156349cc55cSDimitry Andric         // A DynAlloca moves StackPtr, and potentially touches it.
157349cc55cSDimitry Andric         int64_t Amount = getDynAllocaAmount(&MI, MRI);
158349cc55cSDimitry Andric         Lowering L = getLowering(Offset, Amount);
159349cc55cSDimitry Andric         Lowerings[&MI] = L;
160349cc55cSDimitry Andric         switch (L) {
161349cc55cSDimitry Andric         case Sub:
162349cc55cSDimitry Andric           Offset += Amount;
163349cc55cSDimitry Andric           break;
164349cc55cSDimitry Andric         case TouchAndSub:
165349cc55cSDimitry Andric           Offset = Amount;
166349cc55cSDimitry Andric           break;
167349cc55cSDimitry Andric         case Probe:
168349cc55cSDimitry Andric           Offset = 0;
169349cc55cSDimitry Andric           break;
170349cc55cSDimitry Andric         }
171349cc55cSDimitry Andric       } else if (MI.isCall() || isPushPop(MI)) {
172349cc55cSDimitry Andric         // Calls, pushes and pops touch the tip of the stack.
173349cc55cSDimitry Andric         Offset = 0;
174349cc55cSDimitry Andric       } else if (MI.getOpcode() == X86::ADJCALLSTACKUP32 ||
175349cc55cSDimitry Andric                  MI.getOpcode() == X86::ADJCALLSTACKUP64) {
176349cc55cSDimitry Andric         Offset -= MI.getOperand(0).getImm();
177349cc55cSDimitry Andric       } else if (MI.getOpcode() == X86::ADJCALLSTACKDOWN32 ||
178349cc55cSDimitry Andric                  MI.getOpcode() == X86::ADJCALLSTACKDOWN64) {
179349cc55cSDimitry Andric         Offset += MI.getOperand(0).getImm();
180349cc55cSDimitry Andric       } else if (MI.modifiesRegister(StackPtr, TRI)) {
181349cc55cSDimitry Andric         // Any other modification of SP means we've lost track of it.
182349cc55cSDimitry Andric         Offset = INT32_MAX;
183349cc55cSDimitry Andric       }
184349cc55cSDimitry Andric     }
185349cc55cSDimitry Andric 
186349cc55cSDimitry Andric     OutOffset[MBB] = Offset;
187349cc55cSDimitry Andric   }
188349cc55cSDimitry Andric }
189349cc55cSDimitry Andric 
getSubOpcode(bool Is64Bit)190*06c3fb27SDimitry Andric static unsigned getSubOpcode(bool Is64Bit) {
191349cc55cSDimitry Andric   if (Is64Bit)
192*06c3fb27SDimitry Andric     return X86::SUB64ri32;
193*06c3fb27SDimitry Andric   return X86::SUB32ri;
194349cc55cSDimitry Andric }
195349cc55cSDimitry Andric 
lower(MachineInstr * MI,Lowering L)196349cc55cSDimitry Andric void X86DynAllocaExpander::lower(MachineInstr *MI, Lowering L) {
197349cc55cSDimitry Andric   const DebugLoc &DL = MI->getDebugLoc();
198349cc55cSDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
199349cc55cSDimitry Andric   MachineBasicBlock::iterator I = *MI;
200349cc55cSDimitry Andric 
201349cc55cSDimitry Andric   int64_t Amount = getDynAllocaAmount(MI, MRI);
202349cc55cSDimitry Andric   if (Amount == 0) {
203349cc55cSDimitry Andric     MI->eraseFromParent();
204349cc55cSDimitry Andric     return;
205349cc55cSDimitry Andric   }
206349cc55cSDimitry Andric 
207349cc55cSDimitry Andric   // These two variables differ on x32, which is a 64-bit target with a
208349cc55cSDimitry Andric   // 32-bit alloca.
209349cc55cSDimitry Andric   bool Is64Bit = STI->is64Bit();
210349cc55cSDimitry Andric   bool Is64BitAlloca = MI->getOpcode() == X86::DYN_ALLOCA_64;
211349cc55cSDimitry Andric   assert(SlotSize == 4 || SlotSize == 8);
212349cc55cSDimitry Andric 
213bdd1243dSDimitry Andric   std::optional<MachineFunction::DebugInstrOperandPair> InstrNum;
2144824e7fdSDimitry Andric   if (unsigned Num = MI->peekDebugInstrNum()) {
2154824e7fdSDimitry Andric     // Operand 2 of DYN_ALLOCAs contains the stack def.
2164824e7fdSDimitry Andric     InstrNum = {Num, 2};
2174824e7fdSDimitry Andric   }
2184824e7fdSDimitry Andric 
219349cc55cSDimitry Andric   switch (L) {
220349cc55cSDimitry Andric   case TouchAndSub: {
221349cc55cSDimitry Andric     assert(Amount >= SlotSize);
222349cc55cSDimitry Andric 
223349cc55cSDimitry Andric     // Use a push to touch the top of the stack.
224349cc55cSDimitry Andric     unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
225349cc55cSDimitry Andric     BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
226349cc55cSDimitry Andric         .addReg(RegA, RegState::Undef);
227349cc55cSDimitry Andric     Amount -= SlotSize;
228349cc55cSDimitry Andric     if (!Amount)
229349cc55cSDimitry Andric       break;
230349cc55cSDimitry Andric 
231349cc55cSDimitry Andric     // Fall through to make any remaining adjustment.
232bdd1243dSDimitry Andric     [[fallthrough]];
233349cc55cSDimitry Andric   }
234349cc55cSDimitry Andric   case Sub:
235349cc55cSDimitry Andric     assert(Amount > 0);
236349cc55cSDimitry Andric     if (Amount == SlotSize) {
237349cc55cSDimitry Andric       // Use push to save size.
238349cc55cSDimitry Andric       unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
239349cc55cSDimitry Andric       BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
240349cc55cSDimitry Andric           .addReg(RegA, RegState::Undef);
241349cc55cSDimitry Andric     } else {
242349cc55cSDimitry Andric       // Sub.
243*06c3fb27SDimitry Andric       BuildMI(*MBB, I, DL, TII->get(getSubOpcode(Is64BitAlloca)), StackPtr)
244349cc55cSDimitry Andric           .addReg(StackPtr)
245349cc55cSDimitry Andric           .addImm(Amount);
246349cc55cSDimitry Andric     }
247349cc55cSDimitry Andric     break;
248349cc55cSDimitry Andric   case Probe:
249349cc55cSDimitry Andric     if (!NoStackArgProbe) {
250349cc55cSDimitry Andric       // The probe lowering expects the amount in RAX/EAX.
251349cc55cSDimitry Andric       unsigned RegA = Is64BitAlloca ? X86::RAX : X86::EAX;
252349cc55cSDimitry Andric       BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY), RegA)
253349cc55cSDimitry Andric           .addReg(MI->getOperand(0).getReg());
254349cc55cSDimitry Andric 
255349cc55cSDimitry Andric       // Do the probe.
256349cc55cSDimitry Andric       STI->getFrameLowering()->emitStackProbe(*MBB->getParent(), *MBB, MI, DL,
2574824e7fdSDimitry Andric                                               /*InProlog=*/false, InstrNum);
258349cc55cSDimitry Andric     } else {
259349cc55cSDimitry Andric       // Sub
260349cc55cSDimitry Andric       BuildMI(*MBB, I, DL,
261349cc55cSDimitry Andric               TII->get(Is64BitAlloca ? X86::SUB64rr : X86::SUB32rr), StackPtr)
262349cc55cSDimitry Andric           .addReg(StackPtr)
263349cc55cSDimitry Andric           .addReg(MI->getOperand(0).getReg());
264349cc55cSDimitry Andric     }
265349cc55cSDimitry Andric     break;
266349cc55cSDimitry Andric   }
267349cc55cSDimitry Andric 
268349cc55cSDimitry Andric   Register AmountReg = MI->getOperand(0).getReg();
269349cc55cSDimitry Andric   MI->eraseFromParent();
270349cc55cSDimitry Andric 
271349cc55cSDimitry Andric   // Delete the definition of AmountReg.
272349cc55cSDimitry Andric   if (MRI->use_empty(AmountReg))
273349cc55cSDimitry Andric     if (MachineInstr *AmountDef = MRI->getUniqueVRegDef(AmountReg))
274349cc55cSDimitry Andric       AmountDef->eraseFromParent();
275349cc55cSDimitry Andric }
276349cc55cSDimitry Andric 
runOnMachineFunction(MachineFunction & MF)277349cc55cSDimitry Andric bool X86DynAllocaExpander::runOnMachineFunction(MachineFunction &MF) {
278349cc55cSDimitry Andric   if (!MF.getInfo<X86MachineFunctionInfo>()->hasDynAlloca())
279349cc55cSDimitry Andric     return false;
280349cc55cSDimitry Andric 
281349cc55cSDimitry Andric   MRI = &MF.getRegInfo();
282349cc55cSDimitry Andric   STI = &MF.getSubtarget<X86Subtarget>();
283349cc55cSDimitry Andric   TII = STI->getInstrInfo();
284349cc55cSDimitry Andric   TRI = STI->getRegisterInfo();
285349cc55cSDimitry Andric   StackPtr = TRI->getStackRegister();
286349cc55cSDimitry Andric   SlotSize = TRI->getSlotSize();
287bdd1243dSDimitry Andric   StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
288349cc55cSDimitry Andric   NoStackArgProbe = MF.getFunction().hasFnAttribute("no-stack-arg-probe");
289349cc55cSDimitry Andric   if (NoStackArgProbe)
290349cc55cSDimitry Andric     StackProbeSize = INT64_MAX;
291349cc55cSDimitry Andric 
292349cc55cSDimitry Andric   LoweringMap Lowerings;
293349cc55cSDimitry Andric   computeLowerings(MF, Lowerings);
294349cc55cSDimitry Andric   for (auto &P : Lowerings)
295349cc55cSDimitry Andric     lower(P.first, P.second);
296349cc55cSDimitry Andric 
297349cc55cSDimitry Andric   return true;
298349cc55cSDimitry Andric }
299