xref: /src/contrib/llvm-project/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1d39c594dSDimitry Andric //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
2d39c594dSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d39c594dSDimitry Andric //
7d39c594dSDimitry Andric //===----------------------------------------------------------------------===//
8d39c594dSDimitry Andric //
9d39c594dSDimitry Andric // This pass assigns local frame indices to stack slots relative to one another
10d39c594dSDimitry Andric // and allocates additional base registers to access them when the target
11cf099d11SDimitry Andric // estimates they are likely to be out of range of stack pointer and frame
12d39c594dSDimitry Andric // pointer relative addressing.
13d39c594dSDimitry Andric //
14d39c594dSDimitry Andric //===----------------------------------------------------------------------===//
15d39c594dSDimitry Andric 
16ac9a064cSDimitry Andric #include "llvm/CodeGen/LocalStackSlotAllocation.h"
175ca98fd9SDimitry Andric #include "llvm/ADT/SetVector.h"
18d39c594dSDimitry Andric #include "llvm/ADT/SmallSet.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
20d39c594dSDimitry Andric #include "llvm/ADT/Statistic.h"
21044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
22d39c594dSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
23d39c594dSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
24d39c594dSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
25044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
27044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
28044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
29044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
30044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
31706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
324a16efa3SDimitry Andric #include "llvm/Pass.h"
33d39c594dSDimitry Andric #include "llvm/Support/Debug.h"
34d39c594dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
35d39c594dSDimitry Andric #include "llvm/Support/raw_ostream.h"
36044eb2f6SDimitry Andric #include <algorithm>
37044eb2f6SDimitry Andric #include <cassert>
38044eb2f6SDimitry Andric #include <cstdint>
39044eb2f6SDimitry Andric #include <tuple>
40d39c594dSDimitry Andric 
41d39c594dSDimitry Andric using namespace llvm;
42d39c594dSDimitry Andric 
435ca98fd9SDimitry Andric #define DEBUG_TYPE "localstackalloc"
445ca98fd9SDimitry Andric 
45d39c594dSDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
46d39c594dSDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
47d39c594dSDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
48d39c594dSDimitry Andric 
49d39c594dSDimitry Andric namespace {
50044eb2f6SDimitry Andric 
51d39c594dSDimitry Andric   class FrameRef {
52d39c594dSDimitry Andric     MachineBasicBlock::iterator MI; // Instr referencing the frame
53d39c594dSDimitry Andric     int64_t LocalOffset;            // Local offset of the frame idx referenced
5459d6cff9SDimitry Andric     int FrameIdx;                   // The frame index
55b915e9e0SDimitry Andric 
56b915e9e0SDimitry Andric     // Order reference instruction appears in program. Used to ensure
57b915e9e0SDimitry Andric     // deterministic order when multiple instructions may reference the same
58b915e9e0SDimitry Andric     // location.
59b915e9e0SDimitry Andric     unsigned Order;
60b915e9e0SDimitry Andric 
61d39c594dSDimitry Andric   public:
FrameRef(MachineInstr * I,int64_t Offset,int Idx,unsigned Ord)62b915e9e0SDimitry Andric     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
63b915e9e0SDimitry Andric       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
64b915e9e0SDimitry Andric 
operator <(const FrameRef & RHS) const65d39c594dSDimitry Andric     bool operator<(const FrameRef &RHS) const {
66b915e9e0SDimitry Andric       return std::tie(LocalOffset, FrameIdx, Order) <
67b915e9e0SDimitry Andric              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
68d39c594dSDimitry Andric     }
69b915e9e0SDimitry Andric 
getMachineInstr() const7059d6cff9SDimitry Andric     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
getLocalOffset() const7159d6cff9SDimitry Andric     int64_t getLocalOffset() const { return LocalOffset; }
getFrameIndex() const7259d6cff9SDimitry Andric     int getFrameIndex() const { return FrameIdx; }
73d39c594dSDimitry Andric   };
74d39c594dSDimitry Andric 
75ac9a064cSDimitry Andric   class LocalStackSlotImpl {
76d39c594dSDimitry Andric     SmallVector<int64_t, 16> LocalOffsets;
77044eb2f6SDimitry Andric 
785ca98fd9SDimitry Andric     /// StackObjSet - A set of stack object indexes
79044eb2f6SDimitry Andric     using StackObjSet = SmallSetVector<int, 8>;
80d39c594dSDimitry Andric 
81b915e9e0SDimitry Andric     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
82cfca06d7SDimitry Andric                            bool StackGrowsDown, Align &MaxAlign);
835ca98fd9SDimitry Andric     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
845ca98fd9SDimitry Andric                                SmallSet<int, 16> &ProtectedObjs,
85b915e9e0SDimitry Andric                                MachineFrameInfo &MFI, bool StackGrowsDown,
86cfca06d7SDimitry Andric                                int64_t &Offset, Align &MaxAlign);
87d39c594dSDimitry Andric     void calculateFrameObjectOffsets(MachineFunction &Fn);
88d39c594dSDimitry Andric     bool insertFrameReferenceRegisters(MachineFunction &Fn);
89044eb2f6SDimitry Andric 
90d39c594dSDimitry Andric   public:
91ac9a064cSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF);
92ac9a064cSDimitry Andric   };
93ac9a064cSDimitry Andric 
94ac9a064cSDimitry Andric   class LocalStackSlotPass : public MachineFunctionPass {
95ac9a064cSDimitry Andric   public:
96d39c594dSDimitry Andric     static char ID; // Pass identification, replacement for typeid
97044eb2f6SDimitry Andric 
LocalStackSlotPass()985ca98fd9SDimitry Andric     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
995ca98fd9SDimitry Andric       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
1005ca98fd9SDimitry Andric     }
101044eb2f6SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)102ac9a064cSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override {
103ac9a064cSDimitry Andric       return LocalStackSlotImpl().runOnMachineFunction(MF);
104ac9a064cSDimitry Andric     }
105d39c594dSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1065ca98fd9SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
107d39c594dSDimitry Andric       AU.setPreservesCFG();
108d39c594dSDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
109d39c594dSDimitry Andric     }
110d39c594dSDimitry Andric   };
111044eb2f6SDimitry Andric 
112d39c594dSDimitry Andric } // end anonymous namespace
113d39c594dSDimitry Andric 
114ac9a064cSDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager &)115ac9a064cSDimitry Andric LocalStackSlotAllocationPass::run(MachineFunction &MF,
116ac9a064cSDimitry Andric                                   MachineFunctionAnalysisManager &) {
117ac9a064cSDimitry Andric   bool Changed = LocalStackSlotImpl().runOnMachineFunction(MF);
118ac9a064cSDimitry Andric   if (!Changed)
119ac9a064cSDimitry Andric     return PreservedAnalyses::all();
120ac9a064cSDimitry Andric   auto PA = getMachineFunctionPassPreservedAnalyses();
121ac9a064cSDimitry Andric   PA.preserveSet<CFGAnalyses>();
122ac9a064cSDimitry Andric   return PA;
123ac9a064cSDimitry Andric }
124ac9a064cSDimitry Andric 
125d39c594dSDimitry Andric char LocalStackSlotPass::ID = 0;
126044eb2f6SDimitry Andric 
12763faed5bSDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
128eb11fae6SDimitry Andric INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
1295ca98fd9SDimitry Andric                 "Local Stack Slot Allocation", false, false)
1305ca98fd9SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)131ac9a064cSDimitry Andric bool LocalStackSlotImpl::runOnMachineFunction(MachineFunction &MF) {
132b915e9e0SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
13367c32a98SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
134b915e9e0SDimitry Andric   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
135d39c594dSDimitry Andric 
136d39c594dSDimitry Andric   // If the target doesn't want/need this pass, or if there are no locals
137d39c594dSDimitry Andric   // to consider, early exit.
138b60736ecSDimitry Andric   if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
139145449b1SDimitry Andric     return false;
140d39c594dSDimitry Andric 
141d39c594dSDimitry Andric   // Make sure we have enough space to store the local offsets.
142b915e9e0SDimitry Andric   LocalOffsets.resize(MFI.getObjectIndexEnd());
143d39c594dSDimitry Andric 
144d39c594dSDimitry Andric   // Lay out the local blob.
145d39c594dSDimitry Andric   calculateFrameObjectOffsets(MF);
146d39c594dSDimitry Andric 
147d39c594dSDimitry Andric   // Insert virtual base registers to resolve frame index references.
148d39c594dSDimitry Andric   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
149d39c594dSDimitry Andric 
150d39c594dSDimitry Andric   // Tell MFI whether any base registers were allocated. PEI will only
151d39c594dSDimitry Andric   // want to use the local block allocations from this pass if there were any.
152d39c594dSDimitry Andric   // Otherwise, PEI can do a bit better job of getting the alignment right
153d39c594dSDimitry Andric   // without a hole at the start since it knows the alignment of the stack
154d39c594dSDimitry Andric   // at the start of local allocation, and this pass doesn't.
155b915e9e0SDimitry Andric   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
156d39c594dSDimitry Andric 
157d39c594dSDimitry Andric   return true;
158d39c594dSDimitry Andric }
159d39c594dSDimitry Andric 
160d39c594dSDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
AdjustStackOffset(MachineFrameInfo & MFI,int FrameIdx,int64_t & Offset,bool StackGrowsDown,Align & MaxAlign)161ac9a064cSDimitry Andric void LocalStackSlotImpl::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
162cfca06d7SDimitry Andric                                            int64_t &Offset, bool StackGrowsDown,
163cfca06d7SDimitry Andric                                            Align &MaxAlign) {
164d39c594dSDimitry Andric   // If the stack grows down, add the object size to find the lowest address.
165d39c594dSDimitry Andric   if (StackGrowsDown)
166b915e9e0SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
167d39c594dSDimitry Andric 
168cfca06d7SDimitry Andric   Align Alignment = MFI.getObjectAlign(FrameIdx);
169d39c594dSDimitry Andric 
170d39c594dSDimitry Andric   // If the alignment of this object is greater than that of the stack, then
171d39c594dSDimitry Andric   // increase the stack alignment to match.
172cfca06d7SDimitry Andric   MaxAlign = std::max(MaxAlign, Alignment);
173d39c594dSDimitry Andric 
174d39c594dSDimitry Andric   // Adjust to alignment boundary.
175cfca06d7SDimitry Andric   Offset = alignTo(Offset, Alignment);
176d39c594dSDimitry Andric 
177d39c594dSDimitry Andric   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
178eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
179d39c594dSDimitry Andric                     << LocalOffset << "\n");
180d39c594dSDimitry Andric   // Keep the offset available for base register allocation
181d39c594dSDimitry Andric   LocalOffsets[FrameIdx] = LocalOffset;
182d39c594dSDimitry Andric   // And tell MFI about it for PEI to use later
183b915e9e0SDimitry Andric   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
184d39c594dSDimitry Andric 
185d39c594dSDimitry Andric   if (!StackGrowsDown)
186b915e9e0SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
187d39c594dSDimitry Andric 
188d39c594dSDimitry Andric   ++NumAllocations;
189d39c594dSDimitry Andric }
190d39c594dSDimitry Andric 
1915ca98fd9SDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
1925ca98fd9SDimitry 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)193ac9a064cSDimitry Andric void LocalStackSlotImpl::AssignProtectedObjSet(
194cfca06d7SDimitry Andric     const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
195cfca06d7SDimitry Andric     MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
196cfca06d7SDimitry Andric     Align &MaxAlign) {
197344a3780SDimitry Andric   for (int i : UnassignedObjs) {
1985ca98fd9SDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
1995ca98fd9SDimitry Andric     ProtectedObjs.insert(i);
2005ca98fd9SDimitry Andric   }
2015ca98fd9SDimitry Andric }
2025ca98fd9SDimitry Andric 
203d39c594dSDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
204d39c594dSDimitry Andric /// abstract stack objects.
calculateFrameObjectOffsets(MachineFunction & Fn)205ac9a064cSDimitry Andric void LocalStackSlotImpl::calculateFrameObjectOffsets(MachineFunction &Fn) {
206d39c594dSDimitry Andric   // Loop over all of the stack objects, assigning sequential addresses...
207b915e9e0SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
20867c32a98SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
209d39c594dSDimitry Andric   bool StackGrowsDown =
210cf099d11SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
211d39c594dSDimitry Andric   int64_t Offset = 0;
212cfca06d7SDimitry Andric   Align MaxAlign;
213d39c594dSDimitry Andric 
214d39c594dSDimitry Andric   // Make sure that the stack protector comes before the local variables on the
215d39c594dSDimitry Andric   // stack.
2165ca98fd9SDimitry Andric   SmallSet<int, 16> ProtectedObjs;
217e6d15924SDimitry Andric   if (MFI.hasStackProtectorIndex()) {
218e6d15924SDimitry Andric     int StackProtectorFI = MFI.getStackProtectorIndex();
219e6d15924SDimitry Andric 
220e6d15924SDimitry Andric     // We need to make sure we didn't pre-allocate the stack protector when
221e6d15924SDimitry Andric     // doing this.
222e6d15924SDimitry Andric     // If we already have a stack protector, this will re-assign it to a slot
223e6d15924SDimitry Andric     // that is **not** covering the protected objects.
224e6d15924SDimitry Andric     assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
225e6d15924SDimitry Andric            "Stack protector pre-allocated in LocalStackSlotAllocation");
226e6d15924SDimitry Andric 
2275ca98fd9SDimitry Andric     StackObjSet LargeArrayObjs;
2285ca98fd9SDimitry Andric     StackObjSet SmallArrayObjs;
2295ca98fd9SDimitry Andric     StackObjSet AddrOfObjs;
2305ca98fd9SDimitry Andric 
23177fc4c14SDimitry Andric     // Only place the stack protector in the local stack area if the target
23277fc4c14SDimitry Andric     // allows it.
23377fc4c14SDimitry Andric     if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
23477fc4c14SDimitry Andric       AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
23577fc4c14SDimitry Andric                         MaxAlign);
236d39c594dSDimitry Andric 
237d39c594dSDimitry Andric     // Assign large stack objects first.
238b915e9e0SDimitry Andric     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
239b915e9e0SDimitry Andric       if (MFI.isDeadObjectIndex(i))
240d39c594dSDimitry Andric         continue;
241e6d15924SDimitry Andric       if (StackProtectorFI == (int)i)
242d39c594dSDimitry Andric         continue;
243b60736ecSDimitry Andric       if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
244b60736ecSDimitry Andric         continue;
245d39c594dSDimitry Andric 
246eb11fae6SDimitry Andric       switch (MFI.getObjectSSPLayout(i)) {
247eb11fae6SDimitry Andric       case MachineFrameInfo::SSPLK_None:
2485ca98fd9SDimitry Andric         continue;
249eb11fae6SDimitry Andric       case MachineFrameInfo::SSPLK_SmallArray:
2505ca98fd9SDimitry Andric         SmallArrayObjs.insert(i);
2515ca98fd9SDimitry Andric         continue;
252eb11fae6SDimitry Andric       case MachineFrameInfo::SSPLK_AddrOf:
2535ca98fd9SDimitry Andric         AddrOfObjs.insert(i);
2545ca98fd9SDimitry Andric         continue;
255eb11fae6SDimitry Andric       case MachineFrameInfo::SSPLK_LargeArray:
2565ca98fd9SDimitry Andric         LargeArrayObjs.insert(i);
2575ca98fd9SDimitry Andric         continue;
258d39c594dSDimitry Andric       }
2595ca98fd9SDimitry Andric       llvm_unreachable("Unexpected SSPLayoutKind.");
2605ca98fd9SDimitry Andric     }
2615ca98fd9SDimitry Andric 
2625ca98fd9SDimitry Andric     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2635ca98fd9SDimitry Andric                           Offset, MaxAlign);
2645ca98fd9SDimitry Andric     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2655ca98fd9SDimitry Andric                           Offset, MaxAlign);
2665ca98fd9SDimitry Andric     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
2675ca98fd9SDimitry Andric                           Offset, MaxAlign);
268d39c594dSDimitry Andric   }
269d39c594dSDimitry Andric 
270d39c594dSDimitry Andric   // Then assign frame offsets to stack objects that are not used to spill
271d39c594dSDimitry Andric   // callee saved registers.
272b915e9e0SDimitry Andric   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
273b915e9e0SDimitry Andric     if (MFI.isDeadObjectIndex(i))
274d39c594dSDimitry Andric       continue;
275b915e9e0SDimitry Andric     if (MFI.getStackProtectorIndex() == (int)i)
276d39c594dSDimitry Andric       continue;
2775ca98fd9SDimitry Andric     if (ProtectedObjs.count(i))
278d39c594dSDimitry Andric       continue;
279b60736ecSDimitry Andric     if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
280b60736ecSDimitry Andric       continue;
281d39c594dSDimitry Andric 
282d39c594dSDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
283d39c594dSDimitry Andric   }
284d39c594dSDimitry Andric 
285d39c594dSDimitry Andric   // Remember how big this blob of stack space is
286b915e9e0SDimitry Andric   MFI.setLocalFrameSize(Offset);
287cfca06d7SDimitry Andric   MFI.setLocalFrameMaxAlign(MaxAlign);
288d39c594dSDimitry Andric }
289d39c594dSDimitry Andric 
290d39c594dSDimitry Andric static inline bool
lookupCandidateBaseReg(unsigned BaseReg,int64_t BaseOffset,int64_t FrameSizeAdjust,int64_t LocalFrameOffset,const MachineInstr & MI,const TargetRegisterInfo * TRI)2915a5ac124SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
2925a5ac124SDimitry Andric                        int64_t BaseOffset,
293d39c594dSDimitry Andric                        int64_t FrameSizeAdjust,
294d39c594dSDimitry Andric                        int64_t LocalFrameOffset,
29501095a5dSDimitry Andric                        const MachineInstr &MI,
296d39c594dSDimitry Andric                        const TargetRegisterInfo *TRI) {
297d39c594dSDimitry Andric   // Check if the relative offset from the where the base register references
298d39c594dSDimitry Andric   // to the target address is in range for the instruction.
29959d6cff9SDimitry Andric   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
30001095a5dSDimitry Andric   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
301d39c594dSDimitry Andric }
302d39c594dSDimitry Andric 
insertFrameReferenceRegisters(MachineFunction & Fn)303ac9a064cSDimitry Andric bool LocalStackSlotImpl::insertFrameReferenceRegisters(MachineFunction &Fn) {
304d39c594dSDimitry Andric   // Scan the function's instructions looking for frame index references.
305d39c594dSDimitry Andric   // For each, ask the target if it wants a virtual base register for it
306d39c594dSDimitry Andric   // based on what we can tell it about where the local will end up in the
307d39c594dSDimitry Andric   // stack frame. If it wants one, re-use a suitable one we've previously
308d39c594dSDimitry Andric   // allocated, or if there isn't one that fits the bill, allocate a new one
309d39c594dSDimitry Andric   // and ask the target to create a defining instruction for it.
310d39c594dSDimitry Andric 
311b915e9e0SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
31267c32a98SDimitry Andric   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
31367c32a98SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
314d39c594dSDimitry Andric   bool StackGrowsDown =
315cf099d11SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
316d39c594dSDimitry Andric 
317d39c594dSDimitry Andric   // Collect all of the instructions in the block that reference
318d39c594dSDimitry Andric   // a frame index. Also store the frame index referenced to ease later
319d39c594dSDimitry Andric   // lookup. (For any insn that has more than one FI reference, we arbitrarily
320d39c594dSDimitry Andric   // choose the first one).
321d39c594dSDimitry Andric   SmallVector<FrameRef, 64> FrameReferenceInsns;
322cf099d11SDimitry Andric 
323b915e9e0SDimitry Andric   unsigned Order = 0;
324b915e9e0SDimitry Andric 
32501095a5dSDimitry Andric   for (MachineBasicBlock &BB : Fn) {
32601095a5dSDimitry Andric     for (MachineInstr &MI : BB) {
3275ca98fd9SDimitry Andric       // Debug value, stackmap and patchpoint instructions can't be out of
3285ca98fd9SDimitry Andric       // range, so they don't need any updates.
329eb11fae6SDimitry Andric       if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
33001095a5dSDimitry Andric           MI.getOpcode() == TargetOpcode::STACKMAP ||
33101095a5dSDimitry Andric           MI.getOpcode() == TargetOpcode::PATCHPOINT)
332d39c594dSDimitry Andric         continue;
333cf099d11SDimitry Andric 
334d39c594dSDimitry Andric       // For now, allocate the base register(s) within the basic block
335d39c594dSDimitry Andric       // where they're used, and don't try to keep them around outside
336d39c594dSDimitry Andric       // of that. It may be beneficial to try sharing them more broadly
337d39c594dSDimitry Andric       // than that, but the increased register pressure makes that a
338d39c594dSDimitry Andric       // tricky thing to balance. Investigate if re-materializing these
339d39c594dSDimitry Andric       // becomes an issue.
340f65dcba8SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
341d39c594dSDimitry Andric         // Consider replacing all frame index operands that reference
342d39c594dSDimitry Andric         // an object allocated in the local block.
343f65dcba8SDimitry Andric         if (MO.isFI()) {
344d39c594dSDimitry Andric           // Don't try this with values not in the local block.
345f65dcba8SDimitry Andric           if (!MFI.isObjectPreAllocated(MO.getIndex()))
346d39c594dSDimitry Andric             break;
347f65dcba8SDimitry Andric           int Idx = MO.getIndex();
34859d6cff9SDimitry Andric           int64_t LocalOffset = LocalOffsets[Idx];
34901095a5dSDimitry Andric           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
35059d6cff9SDimitry Andric             break;
351b915e9e0SDimitry Andric           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
352d39c594dSDimitry Andric           break;
353d39c594dSDimitry Andric         }
354d39c594dSDimitry Andric       }
355d39c594dSDimitry Andric     }
356d39c594dSDimitry Andric   }
357cf099d11SDimitry Andric 
358b915e9e0SDimitry Andric   // Sort the frame references by local offset.
359b915e9e0SDimitry Andric   // Use frame index as a tie-breaker in case MI's have the same offset.
360d8e91e46SDimitry Andric   llvm::sort(FrameReferenceInsns);
361d39c594dSDimitry Andric 
362dd58ef01SDimitry Andric   MachineBasicBlock *Entry = &Fn.front();
363d39c594dSDimitry Andric 
364145449b1SDimitry Andric   Register BaseReg;
36559d6cff9SDimitry Andric   int64_t BaseOffset = 0;
36659d6cff9SDimitry Andric 
367cf099d11SDimitry Andric   // Loop through the frame references and allocate for them as necessary.
368d39c594dSDimitry Andric   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
36959d6cff9SDimitry Andric     FrameRef &FR = FrameReferenceInsns[ref];
37001095a5dSDimitry Andric     MachineInstr &MI = *FR.getMachineInstr();
37159d6cff9SDimitry Andric     int64_t LocalOffset = FR.getLocalOffset();
37259d6cff9SDimitry Andric     int FrameIdx = FR.getFrameIndex();
373b915e9e0SDimitry Andric     assert(MFI.isObjectPreAllocated(FrameIdx) &&
374d39c594dSDimitry Andric            "Only pre-allocated locals expected!");
375d39c594dSDimitry Andric 
3761d5ae102SDimitry Andric     // We need to keep the references to the stack protector slot through frame
3771d5ae102SDimitry Andric     // index operands so that it gets resolved by PEI rather than this pass.
3781d5ae102SDimitry Andric     // This avoids accesses to the stack protector though virtual base
3791d5ae102SDimitry Andric     // registers, and forces PEI to address it using fp/sp/bp.
3801d5ae102SDimitry Andric     if (MFI.hasStackProtectorIndex() &&
3811d5ae102SDimitry Andric         FrameIdx == MFI.getStackProtectorIndex())
3821d5ae102SDimitry Andric       continue;
3831d5ae102SDimitry Andric 
384eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Considering: " << MI);
38559d6cff9SDimitry Andric 
38659d6cff9SDimitry Andric     unsigned idx = 0;
38701095a5dSDimitry Andric     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
38801095a5dSDimitry Andric       if (!MI.getOperand(idx).isFI())
38959d6cff9SDimitry Andric         continue;
39059d6cff9SDimitry Andric 
39101095a5dSDimitry Andric       if (FrameIdx == MI.getOperand(idx).getIndex())
39259d6cff9SDimitry Andric         break;
39359d6cff9SDimitry Andric     }
39459d6cff9SDimitry Andric 
39501095a5dSDimitry Andric     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
39659d6cff9SDimitry Andric 
397d39c594dSDimitry Andric     int64_t Offset = 0;
398b915e9e0SDimitry Andric     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
399d39c594dSDimitry Andric 
400eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "  Replacing FI in: " << MI);
401d39c594dSDimitry Andric 
402d39c594dSDimitry Andric     // If we have a suitable base register available, use it; otherwise
403d39c594dSDimitry Andric     // create a new one. Note that any offset encoded in the
404d39c594dSDimitry Andric     // instruction itself will be taken into account by the target,
405d39c594dSDimitry Andric     // so we don't have to adjust for it here when reusing a base
406d39c594dSDimitry Andric     // register.
407e3b55780SDimitry Andric     if (BaseReg.isValid() &&
40801095a5dSDimitry Andric         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
40901095a5dSDimitry Andric                                LocalOffset, MI, TRI)) {
410eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
411d39c594dSDimitry Andric       // We found a register to reuse.
41259d6cff9SDimitry Andric       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
413d39c594dSDimitry Andric     } else {
41401095a5dSDimitry Andric       // No previously defined register was in range, so create a new one.
41501095a5dSDimitry Andric       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
41659d6cff9SDimitry Andric 
417e3b55780SDimitry Andric       int64_t CandBaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
41859d6cff9SDimitry Andric 
41959d6cff9SDimitry Andric       // We'd like to avoid creating single-use virtual base registers.
42059d6cff9SDimitry Andric       // Because the FrameRefs are in sorted order, and we've already
42159d6cff9SDimitry Andric       // processed all FrameRefs before this one, just check whether or not
42259d6cff9SDimitry Andric       // the next FrameRef will be able to reuse this new register. If not,
42359d6cff9SDimitry Andric       // then don't bother creating it.
4245ca98fd9SDimitry Andric       if (ref + 1 >= e ||
4255ca98fd9SDimitry Andric           !lookupCandidateBaseReg(
426e3b55780SDimitry Andric               BaseReg, CandBaseOffset, FrameSizeAdjust,
4275ca98fd9SDimitry Andric               FrameReferenceInsns[ref + 1].getLocalOffset(),
428e3b55780SDimitry Andric               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI))
42959d6cff9SDimitry Andric         continue;
430e3b55780SDimitry Andric 
431e3b55780SDimitry Andric       // Save the base offset.
432e3b55780SDimitry Andric       BaseOffset = CandBaseOffset;
43359d6cff9SDimitry Andric 
434d39c594dSDimitry Andric       // Tell the target to insert the instruction to initialize
435d39c594dSDimitry Andric       // the base register.
436cf099d11SDimitry Andric       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
437b60736ecSDimitry Andric       BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
438b60736ecSDimitry Andric 
439145449b1SDimitry Andric       LLVM_DEBUG(dbgs() << "  Materialized base register at frame local offset "
440145449b1SDimitry Andric                         << LocalOffset + InstrOffset
441145449b1SDimitry Andric                         << " into " << printReg(BaseReg, TRI) << '\n');
442d39c594dSDimitry Andric 
443d39c594dSDimitry Andric       // The base register already includes any offset specified
444d39c594dSDimitry Andric       // by the instruction, so account for that so it doesn't get
445d39c594dSDimitry Andric       // applied twice.
446d39c594dSDimitry Andric       Offset = -InstrOffset;
447d39c594dSDimitry Andric 
448d39c594dSDimitry Andric       ++NumBaseRegisters;
449d39c594dSDimitry Andric     }
450145449b1SDimitry Andric     assert(BaseReg && "Unable to allocate virtual base register!");
451d39c594dSDimitry Andric 
452d39c594dSDimitry Andric     // Modify the instruction to use the new base register rather
453d39c594dSDimitry Andric     // than the frame index operand.
45401095a5dSDimitry Andric     TRI->resolveFrameIndex(MI, BaseReg, Offset);
455eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Resolved: " << MI);
456d39c594dSDimitry Andric 
457d39c594dSDimitry Andric     ++NumReplacements;
458d39c594dSDimitry Andric   }
45959d6cff9SDimitry Andric 
460e3b55780SDimitry Andric   return BaseReg.isValid();
461d39c594dSDimitry Andric }
462