1*0b57cec5SDimitry Andric //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This pass assigns local frame indices to stack slots relative to one another
10*0b57cec5SDimitry Andric // and allocates additional base registers to access them when the target
11*0b57cec5SDimitry Andric // estimates they are likely to be out of range of stack pointer and frame
12*0b57cec5SDimitry Andric // pointer relative addressing.
13*0b57cec5SDimitry Andric //
14*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15*0b57cec5SDimitry Andric 
16*0b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
20*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
21*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
22*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
23*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
24*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
25*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
27*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
30*0b57cec5SDimitry Andric #include "llvm/InitializePasses.h"
31*0b57cec5SDimitry Andric #include "llvm/Pass.h"
32*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
33*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
34*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
35*0b57cec5SDimitry Andric #include <algorithm>
36*0b57cec5SDimitry Andric #include <cassert>
37*0b57cec5SDimitry Andric #include <cstdint>
38*0b57cec5SDimitry Andric #include <tuple>
39*0b57cec5SDimitry Andric 
40*0b57cec5SDimitry Andric using namespace llvm;
41*0b57cec5SDimitry Andric 
42*0b57cec5SDimitry Andric #define DEBUG_TYPE "localstackalloc"
43*0b57cec5SDimitry Andric 
44*0b57cec5SDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
45*0b57cec5SDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
46*0b57cec5SDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
47*0b57cec5SDimitry Andric 
48*0b57cec5SDimitry Andric namespace {
49*0b57cec5SDimitry Andric 
50*0b57cec5SDimitry Andric   class FrameRef {
51*0b57cec5SDimitry Andric     MachineBasicBlock::iterator MI; // Instr referencing the frame
52*0b57cec5SDimitry Andric     int64_t LocalOffset;            // Local offset of the frame idx referenced
53*0b57cec5SDimitry Andric     int FrameIdx;                   // The frame index
54*0b57cec5SDimitry Andric 
55*0b57cec5SDimitry Andric     // Order reference instruction appears in program. Used to ensure
56*0b57cec5SDimitry Andric     // deterministic order when multiple instructions may reference the same
57*0b57cec5SDimitry Andric     // location.
58*0b57cec5SDimitry Andric     unsigned Order;
59*0b57cec5SDimitry Andric 
60*0b57cec5SDimitry Andric   public:
FrameRef(MachineInstr * I,int64_t Offset,int Idx,unsigned Ord)61*0b57cec5SDimitry Andric     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
62*0b57cec5SDimitry Andric       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
63*0b57cec5SDimitry Andric 
operator <(const FrameRef & RHS) const64*0b57cec5SDimitry Andric     bool operator<(const FrameRef &RHS) const {
65*0b57cec5SDimitry Andric       return std::tie(LocalOffset, FrameIdx, Order) <
66*0b57cec5SDimitry Andric              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
67*0b57cec5SDimitry Andric     }
68*0b57cec5SDimitry Andric 
getMachineInstr() const69*0b57cec5SDimitry Andric     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
getLocalOffset() const70*0b57cec5SDimitry Andric     int64_t getLocalOffset() const { return LocalOffset; }
getFrameIndex() const71*0b57cec5SDimitry Andric     int getFrameIndex() const { return FrameIdx; }
72*0b57cec5SDimitry Andric   };
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric   class LocalStackSlotPass: public MachineFunctionPass {
75*0b57cec5SDimitry Andric     SmallVector<int64_t, 16> LocalOffsets;
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric     /// StackObjSet - A set of stack object indexes
78*0b57cec5SDimitry Andric     using StackObjSet = SmallSetVector<int, 8>;
79*0b57cec5SDimitry Andric 
80*0b57cec5SDimitry Andric     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
81*0b57cec5SDimitry Andric                            bool StackGrowsDown, Align &MaxAlign);
82*0b57cec5SDimitry Andric     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
83*0b57cec5SDimitry Andric                                SmallSet<int, 16> &ProtectedObjs,
84*0b57cec5SDimitry Andric                                MachineFrameInfo &MFI, bool StackGrowsDown,
85*0b57cec5SDimitry Andric                                int64_t &Offset, Align &MaxAlign);
86*0b57cec5SDimitry Andric     void calculateFrameObjectOffsets(MachineFunction &Fn);
87*0b57cec5SDimitry Andric     bool insertFrameReferenceRegisters(MachineFunction &Fn);
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric   public:
90*0b57cec5SDimitry Andric     static char ID; // Pass identification, replacement for typeid
91*0b57cec5SDimitry Andric 
LocalStackSlotPass()92*0b57cec5SDimitry Andric     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
93*0b57cec5SDimitry Andric       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
94*0b57cec5SDimitry Andric     }
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
97*0b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const98*0b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
99*0b57cec5SDimitry Andric       AU.setPreservesCFG();
100*0b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
101*0b57cec5SDimitry Andric     }
102*0b57cec5SDimitry Andric   };
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric } // end anonymous namespace
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric char LocalStackSlotPass::ID = 0;
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
109*0b57cec5SDimitry Andric INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
110*0b57cec5SDimitry Andric                 "Local Stack Slot Allocation", false, false)
111*0b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)112*0b57cec5SDimitry Andric bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
113*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
114*0b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
115*0b57cec5SDimitry Andric   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
116*0b57cec5SDimitry Andric 
117*0b57cec5SDimitry Andric   // If the target doesn't want/need this pass, or if there are no locals
118*0b57cec5SDimitry Andric   // to consider, early exit.
119*0b57cec5SDimitry Andric   if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
120*0b57cec5SDimitry Andric     return false;
121*0b57cec5SDimitry Andric 
122*0b57cec5SDimitry Andric   // Make sure we have enough space to store the local offsets.
123*0b57cec5SDimitry Andric   LocalOffsets.resize(MFI.getObjectIndexEnd());
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric   // Lay out the local blob.
126*0b57cec5SDimitry Andric   calculateFrameObjectOffsets(MF);
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric   // Insert virtual base registers to resolve frame index references.
129*0b57cec5SDimitry Andric   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
130*0b57cec5SDimitry Andric 
131*0b57cec5SDimitry Andric   // Tell MFI whether any base registers were allocated. PEI will only
132*0b57cec5SDimitry Andric   // want to use the local block allocations from this pass if there were any.
133*0b57cec5SDimitry Andric   // Otherwise, PEI can do a bit better job of getting the alignment right
134*0b57cec5SDimitry Andric   // without a hole at the start since it knows the alignment of the stack
135*0b57cec5SDimitry Andric   // at the start of local allocation, and this pass doesn't.
136*0b57cec5SDimitry Andric   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
137*0b57cec5SDimitry Andric 
138*0b57cec5SDimitry Andric   return true;
139*0b57cec5SDimitry Andric }
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
AdjustStackOffset(MachineFrameInfo & MFI,int FrameIdx,int64_t & Offset,bool StackGrowsDown,Align & MaxAlign)142*0b57cec5SDimitry Andric void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
143*0b57cec5SDimitry Andric                                            int64_t &Offset, bool StackGrowsDown,
144*0b57cec5SDimitry Andric                                            Align &MaxAlign) {
145*0b57cec5SDimitry Andric   // If the stack grows down, add the object size to find the lowest address.
146*0b57cec5SDimitry Andric   if (StackGrowsDown)
147*0b57cec5SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric   Align Alignment = MFI.getObjectAlign(FrameIdx);
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric   // If the alignment of this object is greater than that of the stack, then
152*0b57cec5SDimitry Andric   // increase the stack alignment to match.
153*0b57cec5SDimitry Andric   MaxAlign = std::max(MaxAlign, Alignment);
154*0b57cec5SDimitry Andric 
155*0b57cec5SDimitry Andric   // Adjust to alignment boundary.
156*0b57cec5SDimitry Andric   Offset = alignTo(Offset, Alignment);
157*0b57cec5SDimitry Andric 
158*0b57cec5SDimitry Andric   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
159*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
160*0b57cec5SDimitry Andric                     << LocalOffset << "\n");
161*0b57cec5SDimitry Andric   // Keep the offset available for base register allocation
162*0b57cec5SDimitry Andric   LocalOffsets[FrameIdx] = LocalOffset;
163*0b57cec5SDimitry Andric   // And tell MFI about it for PEI to use later
164*0b57cec5SDimitry Andric   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
165*0b57cec5SDimitry Andric 
166*0b57cec5SDimitry Andric   if (!StackGrowsDown)
167*0b57cec5SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric   ++NumAllocations;
170*0b57cec5SDimitry Andric }
171*0b57cec5SDimitry Andric 
172*0b57cec5SDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
173*0b57cec5SDimitry Andric /// those required to be close to the Stack Protector) to stack offsets.
AssignProtectedObjSet(const StackObjSet & UnassignedObjs,SmallSet<int,16> & ProtectedObjs,MachineFrameInfo & MFI,bool StackGrowsDown,int64_t & Offset,Align & MaxAlign)174*0b57cec5SDimitry Andric void LocalStackSlotPass::AssignProtectedObjSet(
175*0b57cec5SDimitry Andric     const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
176*0b57cec5SDimitry Andric     MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
177*0b57cec5SDimitry Andric     Align &MaxAlign) {
178*0b57cec5SDimitry Andric   for (int i : UnassignedObjs) {
179*0b57cec5SDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
180*0b57cec5SDimitry Andric     ProtectedObjs.insert(i);
181*0b57cec5SDimitry Andric   }
182*0b57cec5SDimitry Andric }
183*0b57cec5SDimitry Andric 
184*0b57cec5SDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
185*0b57cec5SDimitry Andric /// abstract stack objects.
calculateFrameObjectOffsets(MachineFunction & Fn)186*0b57cec5SDimitry Andric void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
187*0b57cec5SDimitry Andric   // Loop over all of the stack objects, assigning sequential addresses...
188*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
189*0b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
190*0b57cec5SDimitry Andric   bool StackGrowsDown =
191*0b57cec5SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
192*0b57cec5SDimitry Andric   int64_t Offset = 0;
193*0b57cec5SDimitry Andric   Align MaxAlign;
194*0b57cec5SDimitry Andric 
195*0b57cec5SDimitry Andric   // Make sure that the stack protector comes before the local variables on the
196*0b57cec5SDimitry Andric   // stack.
197*0b57cec5SDimitry Andric   SmallSet<int, 16> ProtectedObjs;
198*0b57cec5SDimitry Andric   if (MFI.hasStackProtectorIndex()) {
199*0b57cec5SDimitry Andric     int StackProtectorFI = MFI.getStackProtectorIndex();
200*0b57cec5SDimitry Andric 
201*0b57cec5SDimitry Andric     // We need to make sure we didn't pre-allocate the stack protector when
202*0b57cec5SDimitry Andric     // doing this.
203*0b57cec5SDimitry Andric     // If we already have a stack protector, this will re-assign it to a slot
204*0b57cec5SDimitry Andric     // that is **not** covering the protected objects.
205*0b57cec5SDimitry Andric     assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
206*0b57cec5SDimitry Andric            "Stack protector pre-allocated in LocalStackSlotAllocation");
207*0b57cec5SDimitry Andric 
208*0b57cec5SDimitry Andric     StackObjSet LargeArrayObjs;
209*0b57cec5SDimitry Andric     StackObjSet SmallArrayObjs;
210*0b57cec5SDimitry Andric     StackObjSet AddrOfObjs;
211*0b57cec5SDimitry Andric 
212*0b57cec5SDimitry Andric     // Only place the stack protector in the local stack area if the target
213*0b57cec5SDimitry Andric     // allows it.
214*0b57cec5SDimitry Andric     if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
215*0b57cec5SDimitry Andric       AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
216*0b57cec5SDimitry Andric                         MaxAlign);
217*0b57cec5SDimitry Andric 
218*0b57cec5SDimitry Andric     // Assign large stack objects first.
219*0b57cec5SDimitry Andric     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
220*0b57cec5SDimitry Andric       if (MFI.isDeadObjectIndex(i))
221*0b57cec5SDimitry Andric         continue;
222*0b57cec5SDimitry Andric       if (StackProtectorFI == (int)i)
223*0b57cec5SDimitry Andric         continue;
224*0b57cec5SDimitry Andric       if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
225*0b57cec5SDimitry Andric         continue;
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric       switch (MFI.getObjectSSPLayout(i)) {
228*0b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_None:
229*0b57cec5SDimitry Andric         continue;
230*0b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_SmallArray:
231*0b57cec5SDimitry Andric         SmallArrayObjs.insert(i);
232*0b57cec5SDimitry Andric         continue;
233*0b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_AddrOf:
234*0b57cec5SDimitry Andric         AddrOfObjs.insert(i);
235*0b57cec5SDimitry Andric         continue;
236*0b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_LargeArray:
237*0b57cec5SDimitry Andric         LargeArrayObjs.insert(i);
238*0b57cec5SDimitry Andric         continue;
239*0b57cec5SDimitry Andric       }
240*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected SSPLayoutKind.");
241*0b57cec5SDimitry Andric     }
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
244*0b57cec5SDimitry Andric                           Offset, MaxAlign);
245*0b57cec5SDimitry Andric     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
246*0b57cec5SDimitry Andric                           Offset, MaxAlign);
247*0b57cec5SDimitry Andric     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
248*0b57cec5SDimitry Andric                           Offset, MaxAlign);
249*0b57cec5SDimitry Andric   }
250*0b57cec5SDimitry Andric 
251*0b57cec5SDimitry Andric   // Then assign frame offsets to stack objects that are not used to spill
252*0b57cec5SDimitry Andric   // callee saved registers.
253*0b57cec5SDimitry Andric   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
254*0b57cec5SDimitry Andric     if (MFI.isDeadObjectIndex(i))
255*0b57cec5SDimitry Andric       continue;
256*0b57cec5SDimitry Andric     if (MFI.getStackProtectorIndex() == (int)i)
257*0b57cec5SDimitry Andric       continue;
258*0b57cec5SDimitry Andric     if (ProtectedObjs.count(i))
259*0b57cec5SDimitry Andric       continue;
260*0b57cec5SDimitry Andric     if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
261*0b57cec5SDimitry Andric       continue;
262*0b57cec5SDimitry Andric 
263*0b57cec5SDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
264*0b57cec5SDimitry Andric   }
265*0b57cec5SDimitry Andric 
266*0b57cec5SDimitry Andric   // Remember how big this blob of stack space is
267*0b57cec5SDimitry Andric   MFI.setLocalFrameSize(Offset);
268*0b57cec5SDimitry Andric   MFI.setLocalFrameMaxAlign(MaxAlign);
269*0b57cec5SDimitry Andric }
270*0b57cec5SDimitry Andric 
271*0b57cec5SDimitry Andric static inline bool
lookupCandidateBaseReg(unsigned BaseReg,int64_t BaseOffset,int64_t FrameSizeAdjust,int64_t LocalFrameOffset,const MachineInstr & MI,const TargetRegisterInfo * TRI)272*0b57cec5SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
273*0b57cec5SDimitry Andric                        int64_t BaseOffset,
274*0b57cec5SDimitry Andric                        int64_t FrameSizeAdjust,
275*0b57cec5SDimitry Andric                        int64_t LocalFrameOffset,
276*0b57cec5SDimitry Andric                        const MachineInstr &MI,
277*0b57cec5SDimitry Andric                        const TargetRegisterInfo *TRI) {
278*0b57cec5SDimitry Andric   // Check if the relative offset from the where the base register references
279*0b57cec5SDimitry Andric   // to the target address is in range for the instruction.
280*0b57cec5SDimitry Andric   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
281*0b57cec5SDimitry Andric   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
282*0b57cec5SDimitry Andric }
283*0b57cec5SDimitry Andric 
insertFrameReferenceRegisters(MachineFunction & Fn)284*0b57cec5SDimitry Andric bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
285*0b57cec5SDimitry Andric   // Scan the function's instructions looking for frame index references.
286*0b57cec5SDimitry Andric   // For each, ask the target if it wants a virtual base register for it
287*0b57cec5SDimitry Andric   // based on what we can tell it about where the local will end up in the
288*0b57cec5SDimitry Andric   // stack frame. If it wants one, re-use a suitable one we've previously
289*0b57cec5SDimitry Andric   // allocated, or if there isn't one that fits the bill, allocate a new one
290*0b57cec5SDimitry Andric   // and ask the target to create a defining instruction for it.
291*0b57cec5SDimitry Andric 
292*0b57cec5SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
293*0b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
294*0b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
295*0b57cec5SDimitry Andric   bool StackGrowsDown =
296*0b57cec5SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
297*0b57cec5SDimitry Andric 
298*0b57cec5SDimitry Andric   // Collect all of the instructions in the block that reference
299*0b57cec5SDimitry Andric   // a frame index. Also store the frame index referenced to ease later
300*0b57cec5SDimitry Andric   // lookup. (For any insn that has more than one FI reference, we arbitrarily
301*0b57cec5SDimitry Andric   // choose the first one).
302*0b57cec5SDimitry Andric   SmallVector<FrameRef, 64> FrameReferenceInsns;
303*0b57cec5SDimitry Andric 
304*0b57cec5SDimitry Andric   unsigned Order = 0;
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric   for (MachineBasicBlock &BB : Fn) {
307*0b57cec5SDimitry Andric     for (MachineInstr &MI : BB) {
308*0b57cec5SDimitry Andric       // Debug value, stackmap and patchpoint instructions can't be out of
309*0b57cec5SDimitry Andric       // range, so they don't need any updates.
310*0b57cec5SDimitry Andric       if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
311*0b57cec5SDimitry Andric           MI.getOpcode() == TargetOpcode::STACKMAP ||
312*0b57cec5SDimitry Andric           MI.getOpcode() == TargetOpcode::PATCHPOINT)
313*0b57cec5SDimitry Andric         continue;
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric       // For now, allocate the base register(s) within the basic block
316*0b57cec5SDimitry Andric       // where they're used, and don't try to keep them around outside
317*0b57cec5SDimitry Andric       // of that. It may be beneficial to try sharing them more broadly
318*0b57cec5SDimitry Andric       // than that, but the increased register pressure makes that a
319*0b57cec5SDimitry Andric       // tricky thing to balance. Investigate if re-materializing these
320*0b57cec5SDimitry Andric       // becomes an issue.
321*0b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
322*0b57cec5SDimitry Andric         // Consider replacing all frame index operands that reference
323*0b57cec5SDimitry Andric         // an object allocated in the local block.
324*0b57cec5SDimitry Andric         if (MO.isFI()) {
325*0b57cec5SDimitry Andric           // Don't try this with values not in the local block.
326*0b57cec5SDimitry Andric           if (!MFI.isObjectPreAllocated(MO.getIndex()))
327*0b57cec5SDimitry Andric             break;
328*0b57cec5SDimitry Andric           int Idx = MO.getIndex();
329*0b57cec5SDimitry Andric           int64_t LocalOffset = LocalOffsets[Idx];
330*0b57cec5SDimitry Andric           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
331*0b57cec5SDimitry Andric             break;
332*0b57cec5SDimitry Andric           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
333*0b57cec5SDimitry Andric           break;
334*0b57cec5SDimitry Andric         }
335*0b57cec5SDimitry Andric       }
336*0b57cec5SDimitry Andric     }
337*0b57cec5SDimitry Andric   }
338*0b57cec5SDimitry Andric 
339*0b57cec5SDimitry Andric   // Sort the frame references by local offset.
340*0b57cec5SDimitry Andric   // Use frame index as a tie-breaker in case MI's have the same offset.
341*0b57cec5SDimitry Andric   llvm::sort(FrameReferenceInsns);
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric   MachineBasicBlock *Entry = &Fn.front();
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric   Register BaseReg;
346*0b57cec5SDimitry Andric   int64_t BaseOffset = 0;
347*0b57cec5SDimitry Andric 
348*0b57cec5SDimitry Andric   // Loop through the frame references and allocate for them as necessary.
349*0b57cec5SDimitry Andric   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
350*0b57cec5SDimitry Andric     FrameRef &FR = FrameReferenceInsns[ref];
351*0b57cec5SDimitry Andric     MachineInstr &MI = *FR.getMachineInstr();
352*0b57cec5SDimitry Andric     int64_t LocalOffset = FR.getLocalOffset();
353*0b57cec5SDimitry Andric     int FrameIdx = FR.getFrameIndex();
354*0b57cec5SDimitry Andric     assert(MFI.isObjectPreAllocated(FrameIdx) &&
355*0b57cec5SDimitry Andric            "Only pre-allocated locals expected!");
356*0b57cec5SDimitry Andric 
357*0b57cec5SDimitry Andric     // We need to keep the references to the stack protector slot through frame
358*0b57cec5SDimitry Andric     // index operands so that it gets resolved by PEI rather than this pass.
359*0b57cec5SDimitry Andric     // This avoids accesses to the stack protector though virtual base
360*0b57cec5SDimitry Andric     // registers, and forces PEI to address it using fp/sp/bp.
361*0b57cec5SDimitry Andric     if (MFI.hasStackProtectorIndex() &&
362*0b57cec5SDimitry Andric         FrameIdx == MFI.getStackProtectorIndex())
363*0b57cec5SDimitry Andric       continue;
364*0b57cec5SDimitry Andric 
365*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Considering: " << MI);
366*0b57cec5SDimitry Andric 
367*0b57cec5SDimitry Andric     unsigned idx = 0;
368*0b57cec5SDimitry Andric     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
369*0b57cec5SDimitry Andric       if (!MI.getOperand(idx).isFI())
370*0b57cec5SDimitry Andric         continue;
371*0b57cec5SDimitry Andric 
372*0b57cec5SDimitry Andric       if (FrameIdx == MI.getOperand(idx).getIndex())
373*0b57cec5SDimitry Andric         break;
374*0b57cec5SDimitry Andric     }
375*0b57cec5SDimitry Andric 
376*0b57cec5SDimitry Andric     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric     int64_t Offset = 0;
379*0b57cec5SDimitry Andric     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
380*0b57cec5SDimitry Andric 
381*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Replacing FI in: " << MI);
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric     // If we have a suitable base register available, use it; otherwise
384*0b57cec5SDimitry Andric     // create a new one. Note that any offset encoded in the
385*0b57cec5SDimitry Andric     // instruction itself will be taken into account by the target,
386*0b57cec5SDimitry Andric     // so we don't have to adjust for it here when reusing a base
387*0b57cec5SDimitry Andric     // register.
388*0b57cec5SDimitry Andric     if (BaseReg.isValid() &&
389*0b57cec5SDimitry Andric         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
390*0b57cec5SDimitry Andric                                LocalOffset, MI, TRI)) {
391*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
392*0b57cec5SDimitry Andric       // We found a register to reuse.
393*0b57cec5SDimitry Andric       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
394*0b57cec5SDimitry Andric     } else {
395*0b57cec5SDimitry Andric       // No previously defined register was in range, so create a new one.
396*0b57cec5SDimitry Andric       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric       int64_t CandBaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
399*0b57cec5SDimitry Andric 
400*0b57cec5SDimitry Andric       // We'd like to avoid creating single-use virtual base registers.
401*0b57cec5SDimitry Andric       // Because the FrameRefs are in sorted order, and we've already
402*0b57cec5SDimitry Andric       // processed all FrameRefs before this one, just check whether or not
403*0b57cec5SDimitry Andric       // the next FrameRef will be able to reuse this new register. If not,
404*0b57cec5SDimitry Andric       // then don't bother creating it.
405*0b57cec5SDimitry Andric       if (ref + 1 >= e ||
406*0b57cec5SDimitry Andric           !lookupCandidateBaseReg(
407*0b57cec5SDimitry Andric               BaseReg, CandBaseOffset, FrameSizeAdjust,
408*0b57cec5SDimitry Andric               FrameReferenceInsns[ref + 1].getLocalOffset(),
409*0b57cec5SDimitry Andric               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI))
410*0b57cec5SDimitry Andric         continue;
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric       // Save the base offset.
413*0b57cec5SDimitry Andric       BaseOffset = CandBaseOffset;
414*0b57cec5SDimitry Andric 
415*0b57cec5SDimitry Andric       // Tell the target to insert the instruction to initialize
416*0b57cec5SDimitry Andric       // the base register.
417*0b57cec5SDimitry Andric       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
418*0b57cec5SDimitry Andric       BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
419*0b57cec5SDimitry Andric 
420*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Materialized base register at frame local offset "
421*0b57cec5SDimitry Andric                         << LocalOffset + InstrOffset
422*0b57cec5SDimitry Andric                         << " into " << printReg(BaseReg, TRI) << '\n');
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric       // The base register already includes any offset specified
425*0b57cec5SDimitry Andric       // by the instruction, so account for that so it doesn't get
426*0b57cec5SDimitry Andric       // applied twice.
427*0b57cec5SDimitry Andric       Offset = -InstrOffset;
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric       ++NumBaseRegisters;
430*0b57cec5SDimitry Andric     }
431*0b57cec5SDimitry Andric     assert(BaseReg && "Unable to allocate virtual base register!");
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric     // Modify the instruction to use the new base register rather
434*0b57cec5SDimitry Andric     // than the frame index operand.
435*0b57cec5SDimitry Andric     TRI->resolveFrameIndex(MI, BaseReg, Offset);
436*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Resolved: " << MI);
437*0b57cec5SDimitry Andric 
438*0b57cec5SDimitry Andric     ++NumReplacements;
439*0b57cec5SDimitry Andric   }
440*0b57cec5SDimitry Andric 
441*0b57cec5SDimitry Andric   return BaseReg.isValid();
442*0b57cec5SDimitry Andric }
443*0b57cec5SDimitry Andric