xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/X86/X86DynAllocaExpander.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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:
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 
67349cc55cSDimitry 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 
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.
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
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 
111349cc55cSDimitry Andric static bool isPushPop(const MachineInstr &MI) {
112349cc55cSDimitry Andric   switch (MI.getOpcode()) {
113349cc55cSDimitry Andric   case X86::PUSH32i8:
114349cc55cSDimitry Andric   case X86::PUSH32r:
115349cc55cSDimitry Andric   case X86::PUSH32rmm:
116349cc55cSDimitry Andric   case X86::PUSH32rmr:
117349cc55cSDimitry Andric   case X86::PUSHi32:
118349cc55cSDimitry Andric   case X86::PUSH64i8:
119349cc55cSDimitry Andric   case X86::PUSH64r:
120349cc55cSDimitry Andric   case X86::PUSH64rmm:
121349cc55cSDimitry Andric   case X86::PUSH64rmr:
122349cc55cSDimitry Andric   case X86::PUSH64i32:
123349cc55cSDimitry Andric   case X86::POP32r:
124349cc55cSDimitry Andric   case X86::POP64r:
125349cc55cSDimitry Andric     return true;
126349cc55cSDimitry Andric   default:
127349cc55cSDimitry Andric     return false;
128349cc55cSDimitry Andric   }
129349cc55cSDimitry Andric }
130349cc55cSDimitry Andric 
131349cc55cSDimitry Andric void X86DynAllocaExpander::computeLowerings(MachineFunction &MF,
132349cc55cSDimitry Andric                                             LoweringMap &Lowerings) {
133349cc55cSDimitry Andric   // Do a one-pass reverse post-order walk of the CFG to conservatively estimate
134349cc55cSDimitry Andric   // the offset between the stack pointer and the lowest touched part of the
135349cc55cSDimitry Andric   // stack, and use that to decide how to lower each DynAlloca instruction.
136349cc55cSDimitry Andric 
137349cc55cSDimitry Andric   // Initialize OutOffset[B], the stack offset at exit from B, to something big.
138349cc55cSDimitry Andric   DenseMap<MachineBasicBlock *, int64_t> OutOffset;
139349cc55cSDimitry Andric   for (MachineBasicBlock &MBB : MF)
140349cc55cSDimitry Andric     OutOffset[&MBB] = INT32_MAX;
141349cc55cSDimitry Andric 
142349cc55cSDimitry Andric   // Note: we don't know the offset at the start of the entry block since the
143349cc55cSDimitry Andric   // prologue hasn't been inserted yet, and how much that will adjust the stack
144349cc55cSDimitry Andric   // pointer depends on register spills, which have not been computed yet.
145349cc55cSDimitry Andric 
146349cc55cSDimitry Andric   // Compute the reverse post-order.
147349cc55cSDimitry Andric   ReversePostOrderTraversal<MachineFunction*> RPO(&MF);
148349cc55cSDimitry Andric 
149349cc55cSDimitry Andric   for (MachineBasicBlock *MBB : RPO) {
150349cc55cSDimitry Andric     int64_t Offset = -1;
151349cc55cSDimitry Andric     for (MachineBasicBlock *Pred : MBB->predecessors())
152349cc55cSDimitry Andric       Offset = std::max(Offset, OutOffset[Pred]);
153349cc55cSDimitry Andric     if (Offset == -1) Offset = INT32_MAX;
154349cc55cSDimitry Andric 
155349cc55cSDimitry Andric     for (MachineInstr &MI : *MBB) {
156349cc55cSDimitry Andric       if (MI.getOpcode() == X86::DYN_ALLOCA_32 ||
157349cc55cSDimitry Andric           MI.getOpcode() == X86::DYN_ALLOCA_64) {
158349cc55cSDimitry Andric         // A DynAlloca moves StackPtr, and potentially touches it.
159349cc55cSDimitry Andric         int64_t Amount = getDynAllocaAmount(&MI, MRI);
160349cc55cSDimitry Andric         Lowering L = getLowering(Offset, Amount);
161349cc55cSDimitry Andric         Lowerings[&MI] = L;
162349cc55cSDimitry Andric         switch (L) {
163349cc55cSDimitry Andric         case Sub:
164349cc55cSDimitry Andric           Offset += Amount;
165349cc55cSDimitry Andric           break;
166349cc55cSDimitry Andric         case TouchAndSub:
167349cc55cSDimitry Andric           Offset = Amount;
168349cc55cSDimitry Andric           break;
169349cc55cSDimitry Andric         case Probe:
170349cc55cSDimitry Andric           Offset = 0;
171349cc55cSDimitry Andric           break;
172349cc55cSDimitry Andric         }
173349cc55cSDimitry Andric       } else if (MI.isCall() || isPushPop(MI)) {
174349cc55cSDimitry Andric         // Calls, pushes and pops touch the tip of the stack.
175349cc55cSDimitry Andric         Offset = 0;
176349cc55cSDimitry Andric       } else if (MI.getOpcode() == X86::ADJCALLSTACKUP32 ||
177349cc55cSDimitry Andric                  MI.getOpcode() == X86::ADJCALLSTACKUP64) {
178349cc55cSDimitry Andric         Offset -= MI.getOperand(0).getImm();
179349cc55cSDimitry Andric       } else if (MI.getOpcode() == X86::ADJCALLSTACKDOWN32 ||
180349cc55cSDimitry Andric                  MI.getOpcode() == X86::ADJCALLSTACKDOWN64) {
181349cc55cSDimitry Andric         Offset += MI.getOperand(0).getImm();
182349cc55cSDimitry Andric       } else if (MI.modifiesRegister(StackPtr, TRI)) {
183349cc55cSDimitry Andric         // Any other modification of SP means we've lost track of it.
184349cc55cSDimitry Andric         Offset = INT32_MAX;
185349cc55cSDimitry Andric       }
186349cc55cSDimitry Andric     }
187349cc55cSDimitry Andric 
188349cc55cSDimitry Andric     OutOffset[MBB] = Offset;
189349cc55cSDimitry Andric   }
190349cc55cSDimitry Andric }
191349cc55cSDimitry Andric 
192349cc55cSDimitry Andric static unsigned getSubOpcode(bool Is64Bit, int64_t Amount) {
193349cc55cSDimitry Andric   if (Is64Bit)
194349cc55cSDimitry Andric     return isInt<8>(Amount) ? X86::SUB64ri8 : X86::SUB64ri32;
195349cc55cSDimitry Andric   return isInt<8>(Amount) ? X86::SUB32ri8 : X86::SUB32ri;
196349cc55cSDimitry Andric }
197349cc55cSDimitry Andric 
198349cc55cSDimitry Andric void X86DynAllocaExpander::lower(MachineInstr *MI, Lowering L) {
199349cc55cSDimitry Andric   const DebugLoc &DL = MI->getDebugLoc();
200349cc55cSDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
201349cc55cSDimitry Andric   MachineBasicBlock::iterator I = *MI;
202349cc55cSDimitry Andric 
203349cc55cSDimitry Andric   int64_t Amount = getDynAllocaAmount(MI, MRI);
204349cc55cSDimitry Andric   if (Amount == 0) {
205349cc55cSDimitry Andric     MI->eraseFromParent();
206349cc55cSDimitry Andric     return;
207349cc55cSDimitry Andric   }
208349cc55cSDimitry Andric 
209349cc55cSDimitry Andric   // These two variables differ on x32, which is a 64-bit target with a
210349cc55cSDimitry Andric   // 32-bit alloca.
211349cc55cSDimitry Andric   bool Is64Bit = STI->is64Bit();
212349cc55cSDimitry Andric   bool Is64BitAlloca = MI->getOpcode() == X86::DYN_ALLOCA_64;
213349cc55cSDimitry Andric   assert(SlotSize == 4 || SlotSize == 8);
214349cc55cSDimitry Andric 
215*bdd1243dSDimitry Andric   std::optional<MachineFunction::DebugInstrOperandPair> InstrNum;
2164824e7fdSDimitry Andric   if (unsigned Num = MI->peekDebugInstrNum()) {
2174824e7fdSDimitry Andric     // Operand 2 of DYN_ALLOCAs contains the stack def.
2184824e7fdSDimitry Andric     InstrNum = {Num, 2};
2194824e7fdSDimitry Andric   }
2204824e7fdSDimitry Andric 
221349cc55cSDimitry Andric   switch (L) {
222349cc55cSDimitry Andric   case TouchAndSub: {
223349cc55cSDimitry Andric     assert(Amount >= SlotSize);
224349cc55cSDimitry Andric 
225349cc55cSDimitry Andric     // Use a push to touch the top of the stack.
226349cc55cSDimitry Andric     unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
227349cc55cSDimitry Andric     BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
228349cc55cSDimitry Andric         .addReg(RegA, RegState::Undef);
229349cc55cSDimitry Andric     Amount -= SlotSize;
230349cc55cSDimitry Andric     if (!Amount)
231349cc55cSDimitry Andric       break;
232349cc55cSDimitry Andric 
233349cc55cSDimitry Andric     // Fall through to make any remaining adjustment.
234*bdd1243dSDimitry Andric     [[fallthrough]];
235349cc55cSDimitry Andric   }
236349cc55cSDimitry Andric   case Sub:
237349cc55cSDimitry Andric     assert(Amount > 0);
238349cc55cSDimitry Andric     if (Amount == SlotSize) {
239349cc55cSDimitry Andric       // Use push to save size.
240349cc55cSDimitry Andric       unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
241349cc55cSDimitry Andric       BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
242349cc55cSDimitry Andric           .addReg(RegA, RegState::Undef);
243349cc55cSDimitry Andric     } else {
244349cc55cSDimitry Andric       // Sub.
245349cc55cSDimitry Andric       BuildMI(*MBB, I, DL,
246349cc55cSDimitry Andric               TII->get(getSubOpcode(Is64BitAlloca, Amount)), StackPtr)
247349cc55cSDimitry Andric           .addReg(StackPtr)
248349cc55cSDimitry Andric           .addImm(Amount);
249349cc55cSDimitry Andric     }
250349cc55cSDimitry Andric     break;
251349cc55cSDimitry Andric   case Probe:
252349cc55cSDimitry Andric     if (!NoStackArgProbe) {
253349cc55cSDimitry Andric       // The probe lowering expects the amount in RAX/EAX.
254349cc55cSDimitry Andric       unsigned RegA = Is64BitAlloca ? X86::RAX : X86::EAX;
255349cc55cSDimitry Andric       BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY), RegA)
256349cc55cSDimitry Andric           .addReg(MI->getOperand(0).getReg());
257349cc55cSDimitry Andric 
258349cc55cSDimitry Andric       // Do the probe.
259349cc55cSDimitry Andric       STI->getFrameLowering()->emitStackProbe(*MBB->getParent(), *MBB, MI, DL,
2604824e7fdSDimitry Andric                                               /*InProlog=*/false, InstrNum);
261349cc55cSDimitry Andric     } else {
262349cc55cSDimitry Andric       // Sub
263349cc55cSDimitry Andric       BuildMI(*MBB, I, DL,
264349cc55cSDimitry Andric               TII->get(Is64BitAlloca ? X86::SUB64rr : X86::SUB32rr), StackPtr)
265349cc55cSDimitry Andric           .addReg(StackPtr)
266349cc55cSDimitry Andric           .addReg(MI->getOperand(0).getReg());
267349cc55cSDimitry Andric     }
268349cc55cSDimitry Andric     break;
269349cc55cSDimitry Andric   }
270349cc55cSDimitry Andric 
271349cc55cSDimitry Andric   Register AmountReg = MI->getOperand(0).getReg();
272349cc55cSDimitry Andric   MI->eraseFromParent();
273349cc55cSDimitry Andric 
274349cc55cSDimitry Andric   // Delete the definition of AmountReg.
275349cc55cSDimitry Andric   if (MRI->use_empty(AmountReg))
276349cc55cSDimitry Andric     if (MachineInstr *AmountDef = MRI->getUniqueVRegDef(AmountReg))
277349cc55cSDimitry Andric       AmountDef->eraseFromParent();
278349cc55cSDimitry Andric }
279349cc55cSDimitry Andric 
280349cc55cSDimitry Andric bool X86DynAllocaExpander::runOnMachineFunction(MachineFunction &MF) {
281349cc55cSDimitry Andric   if (!MF.getInfo<X86MachineFunctionInfo>()->hasDynAlloca())
282349cc55cSDimitry Andric     return false;
283349cc55cSDimitry Andric 
284349cc55cSDimitry Andric   MRI = &MF.getRegInfo();
285349cc55cSDimitry Andric   STI = &MF.getSubtarget<X86Subtarget>();
286349cc55cSDimitry Andric   TII = STI->getInstrInfo();
287349cc55cSDimitry Andric   TRI = STI->getRegisterInfo();
288349cc55cSDimitry Andric   StackPtr = TRI->getStackRegister();
289349cc55cSDimitry Andric   SlotSize = TRI->getSlotSize();
290*bdd1243dSDimitry Andric   StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
291349cc55cSDimitry Andric   NoStackArgProbe = MF.getFunction().hasFnAttribute("no-stack-arg-probe");
292349cc55cSDimitry Andric   if (NoStackArgProbe)
293349cc55cSDimitry Andric     StackProbeSize = INT64_MAX;
294349cc55cSDimitry Andric 
295349cc55cSDimitry Andric   LoweringMap Lowerings;
296349cc55cSDimitry Andric   computeLowerings(MF, Lowerings);
297349cc55cSDimitry Andric   for (auto &P : Lowerings)
298349cc55cSDimitry Andric     lower(P.first, P.second);
299349cc55cSDimitry Andric 
300349cc55cSDimitry Andric   return true;
301349cc55cSDimitry Andric }
302