1e580952dSDimitry Andric //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
2e580952dSDimitry Andric //
3e580952dSDimitry Andric //                     The LLVM Compiler Infrastructure
4e580952dSDimitry Andric //
5e580952dSDimitry Andric // This file is distributed under the University of Illinois Open Source
6e580952dSDimitry Andric // License. See LICENSE.TXT for details.
7e580952dSDimitry Andric //
8e580952dSDimitry Andric //===----------------------------------------------------------------------===//
9e580952dSDimitry Andric //
10e580952dSDimitry Andric // This pass assigns local frame indices to stack slots relative to one another
11e580952dSDimitry Andric // and allocates additional base registers to access them when the target
122754fe60SDimitry Andric // estimates they are likely to be out of range of stack pointer and frame
13e580952dSDimitry Andric // pointer relative addressing.
14e580952dSDimitry Andric //
15e580952dSDimitry Andric //===----------------------------------------------------------------------===//
16e580952dSDimitry Andric 
1791bc56edSDimitry Andric #include "llvm/ADT/SetVector.h"
18e580952dSDimitry Andric #include "llvm/ADT/SmallSet.h"
192cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
20e580952dSDimitry Andric #include "llvm/ADT/Statistic.h"
212cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
22e580952dSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
23e580952dSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
24e580952dSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
252cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
27e580952dSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
2891bc56edSDimitry Andric #include "llvm/CodeGen/StackProtector.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
302cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
322cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
33139f7f9bSDimitry Andric #include "llvm/Pass.h"
34e580952dSDimitry Andric #include "llvm/Support/Debug.h"
35e580952dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
36e580952dSDimitry Andric #include "llvm/Support/raw_ostream.h"
372cab237bSDimitry Andric #include <algorithm>
382cab237bSDimitry Andric #include <cassert>
392cab237bSDimitry Andric #include <cstdint>
402cab237bSDimitry Andric #include <tuple>
41e580952dSDimitry Andric 
42e580952dSDimitry Andric using namespace llvm;
43e580952dSDimitry Andric 
4491bc56edSDimitry Andric #define DEBUG_TYPE "localstackalloc"
4591bc56edSDimitry Andric 
46e580952dSDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
47e580952dSDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
48e580952dSDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
49e580952dSDimitry Andric 
50e580952dSDimitry Andric namespace {
512cab237bSDimitry Andric 
52e580952dSDimitry Andric   class FrameRef {
53e580952dSDimitry Andric     MachineBasicBlock::iterator MI; // Instr referencing the frame
54e580952dSDimitry Andric     int64_t LocalOffset;            // Local offset of the frame idx referenced
55284c1978SDimitry Andric     int FrameIdx;                   // The frame index
56d88c1a5aSDimitry Andric 
57d88c1a5aSDimitry Andric     // Order reference instruction appears in program. Used to ensure
58d88c1a5aSDimitry Andric     // deterministic order when multiple instructions may reference the same
59d88c1a5aSDimitry Andric     // location.
60d88c1a5aSDimitry Andric     unsigned Order;
61d88c1a5aSDimitry Andric 
62e580952dSDimitry Andric   public:
63d88c1a5aSDimitry Andric     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
64d88c1a5aSDimitry Andric       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
65d88c1a5aSDimitry Andric 
66e580952dSDimitry Andric     bool operator<(const FrameRef &RHS) const {
67d88c1a5aSDimitry Andric       return std::tie(LocalOffset, FrameIdx, Order) <
68d88c1a5aSDimitry Andric              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
69e580952dSDimitry Andric     }
70d88c1a5aSDimitry Andric 
71284c1978SDimitry Andric     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
72284c1978SDimitry Andric     int64_t getLocalOffset() const { return LocalOffset; }
73284c1978SDimitry Andric     int getFrameIndex() const { return FrameIdx; }
74e580952dSDimitry Andric   };
75e580952dSDimitry Andric 
76e580952dSDimitry Andric   class LocalStackSlotPass: public MachineFunctionPass {
77e580952dSDimitry Andric     SmallVector<int64_t, 16> LocalOffsets;
782cab237bSDimitry Andric 
7991bc56edSDimitry Andric     /// StackObjSet - A set of stack object indexes
802cab237bSDimitry Andric     using StackObjSet = SmallSetVector<int, 8>;
81e580952dSDimitry Andric 
82d88c1a5aSDimitry Andric     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
83e580952dSDimitry Andric                            bool StackGrowsDown, unsigned &MaxAlign);
8491bc56edSDimitry Andric     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
8591bc56edSDimitry Andric                                SmallSet<int, 16> &ProtectedObjs,
86d88c1a5aSDimitry Andric                                MachineFrameInfo &MFI, bool StackGrowsDown,
8791bc56edSDimitry Andric                                int64_t &Offset, unsigned &MaxAlign);
88e580952dSDimitry Andric     void calculateFrameObjectOffsets(MachineFunction &Fn);
89e580952dSDimitry Andric     bool insertFrameReferenceRegisters(MachineFunction &Fn);
902cab237bSDimitry Andric 
91e580952dSDimitry Andric   public:
92e580952dSDimitry Andric     static char ID; // Pass identification, replacement for typeid
932cab237bSDimitry Andric 
9491bc56edSDimitry Andric     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
9591bc56edSDimitry Andric       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
9691bc56edSDimitry Andric     }
972cab237bSDimitry Andric 
9891bc56edSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
99e580952dSDimitry Andric 
10091bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
101e580952dSDimitry Andric       AU.setPreservesCFG();
10291bc56edSDimitry Andric       AU.addRequired<StackProtector>();
103e580952dSDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
104e580952dSDimitry Andric     }
105e580952dSDimitry Andric   };
1062cab237bSDimitry Andric 
107e580952dSDimitry Andric } // end anonymous namespace
108e580952dSDimitry Andric 
109e580952dSDimitry Andric char LocalStackSlotPass::ID = 0;
1102cab237bSDimitry Andric 
111dff0c46cSDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
1122cab237bSDimitry Andric 
113302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(LocalStackSlotPass, DEBUG_TYPE,
114dff0c46cSDimitry Andric                       "Local Stack Slot Allocation", false, false)
11591bc56edSDimitry Andric INITIALIZE_PASS_DEPENDENCY(StackProtector)
116302affcbSDimitry Andric INITIALIZE_PASS_END(LocalStackSlotPass, DEBUG_TYPE,
11791bc56edSDimitry Andric                     "Local Stack Slot Allocation", false, false)
11891bc56edSDimitry Andric 
119e580952dSDimitry Andric bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
120d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
12139d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
122d88c1a5aSDimitry Andric   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
123e580952dSDimitry Andric 
124e580952dSDimitry Andric   // If the target doesn't want/need this pass, or if there are no locals
125e580952dSDimitry Andric   // to consider, early exit.
126e580952dSDimitry Andric   if (!TRI->requiresVirtualBaseRegisters(MF) || LocalObjectCount == 0)
127e580952dSDimitry Andric     return true;
128e580952dSDimitry Andric 
129e580952dSDimitry Andric   // Make sure we have enough space to store the local offsets.
130d88c1a5aSDimitry Andric   LocalOffsets.resize(MFI.getObjectIndexEnd());
131e580952dSDimitry Andric 
132e580952dSDimitry Andric   // Lay out the local blob.
133e580952dSDimitry Andric   calculateFrameObjectOffsets(MF);
134e580952dSDimitry Andric 
135e580952dSDimitry Andric   // Insert virtual base registers to resolve frame index references.
136e580952dSDimitry Andric   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
137e580952dSDimitry Andric 
138e580952dSDimitry Andric   // Tell MFI whether any base registers were allocated. PEI will only
139e580952dSDimitry Andric   // want to use the local block allocations from this pass if there were any.
140e580952dSDimitry Andric   // Otherwise, PEI can do a bit better job of getting the alignment right
141e580952dSDimitry Andric   // without a hole at the start since it knows the alignment of the stack
142e580952dSDimitry Andric   // at the start of local allocation, and this pass doesn't.
143d88c1a5aSDimitry Andric   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
144e580952dSDimitry Andric 
145e580952dSDimitry Andric   return true;
146e580952dSDimitry Andric }
147e580952dSDimitry Andric 
148e580952dSDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
149d88c1a5aSDimitry Andric void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI,
150e580952dSDimitry Andric                                            int FrameIdx, int64_t &Offset,
151e580952dSDimitry Andric                                            bool StackGrowsDown,
152e580952dSDimitry Andric                                            unsigned &MaxAlign) {
153e580952dSDimitry Andric   // If the stack grows down, add the object size to find the lowest address.
154e580952dSDimitry Andric   if (StackGrowsDown)
155d88c1a5aSDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
156e580952dSDimitry Andric 
157d88c1a5aSDimitry Andric   unsigned Align = MFI.getObjectAlignment(FrameIdx);
158e580952dSDimitry Andric 
159e580952dSDimitry Andric   // If the alignment of this object is greater than that of the stack, then
160e580952dSDimitry Andric   // increase the stack alignment to match.
161e580952dSDimitry Andric   MaxAlign = std::max(MaxAlign, Align);
162e580952dSDimitry Andric 
163e580952dSDimitry Andric   // Adjust to alignment boundary.
164e580952dSDimitry Andric   Offset = (Offset + Align - 1) / Align * Align;
165e580952dSDimitry Andric 
166e580952dSDimitry Andric   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
167e580952dSDimitry Andric   DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
168e580952dSDimitry Andric         << LocalOffset << "\n");
169e580952dSDimitry Andric   // Keep the offset available for base register allocation
170e580952dSDimitry Andric   LocalOffsets[FrameIdx] = LocalOffset;
171e580952dSDimitry Andric   // And tell MFI about it for PEI to use later
172d88c1a5aSDimitry Andric   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
173e580952dSDimitry Andric 
174e580952dSDimitry Andric   if (!StackGrowsDown)
175d88c1a5aSDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
176e580952dSDimitry Andric 
177e580952dSDimitry Andric   ++NumAllocations;
178e580952dSDimitry Andric }
179e580952dSDimitry Andric 
18091bc56edSDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
18191bc56edSDimitry Andric /// those required to be close to the Stack Protector) to stack offsets.
18291bc56edSDimitry Andric void LocalStackSlotPass::AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
18391bc56edSDimitry Andric                                            SmallSet<int, 16> &ProtectedObjs,
184d88c1a5aSDimitry Andric                                            MachineFrameInfo &MFI,
18591bc56edSDimitry Andric                                            bool StackGrowsDown, int64_t &Offset,
18691bc56edSDimitry Andric                                            unsigned &MaxAlign) {
18791bc56edSDimitry Andric   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
18891bc56edSDimitry Andric         E = UnassignedObjs.end(); I != E; ++I) {
18991bc56edSDimitry Andric     int i = *I;
19091bc56edSDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
19191bc56edSDimitry Andric     ProtectedObjs.insert(i);
19291bc56edSDimitry Andric   }
19391bc56edSDimitry Andric }
19491bc56edSDimitry Andric 
195e580952dSDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
196e580952dSDimitry Andric /// abstract stack objects.
197e580952dSDimitry Andric void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
198e580952dSDimitry Andric   // Loop over all of the stack objects, assigning sequential addresses...
199d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
20039d628a0SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
201e580952dSDimitry Andric   bool StackGrowsDown =
2022754fe60SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
203e580952dSDimitry Andric   int64_t Offset = 0;
204e580952dSDimitry Andric   unsigned MaxAlign = 0;
20591bc56edSDimitry Andric   StackProtector *SP = &getAnalysis<StackProtector>();
206e580952dSDimitry Andric 
207e580952dSDimitry Andric   // Make sure that the stack protector comes before the local variables on the
208e580952dSDimitry Andric   // stack.
20991bc56edSDimitry Andric   SmallSet<int, 16> ProtectedObjs;
210d88c1a5aSDimitry Andric   if (MFI.getStackProtectorIndex() >= 0) {
21191bc56edSDimitry Andric     StackObjSet LargeArrayObjs;
21291bc56edSDimitry Andric     StackObjSet SmallArrayObjs;
21391bc56edSDimitry Andric     StackObjSet AddrOfObjs;
21491bc56edSDimitry Andric 
215d88c1a5aSDimitry Andric     AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), Offset,
216e580952dSDimitry Andric                       StackGrowsDown, MaxAlign);
217e580952dSDimitry Andric 
218e580952dSDimitry Andric     // Assign large stack objects first.
219d88c1a5aSDimitry Andric     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
220d88c1a5aSDimitry Andric       if (MFI.isDeadObjectIndex(i))
221e580952dSDimitry Andric         continue;
222d88c1a5aSDimitry Andric       if (MFI.getStackProtectorIndex() == (int)i)
223e580952dSDimitry Andric         continue;
224e580952dSDimitry Andric 
225d88c1a5aSDimitry Andric       switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
22691bc56edSDimitry Andric       case StackProtector::SSPLK_None:
22791bc56edSDimitry Andric         continue;
22891bc56edSDimitry Andric       case StackProtector::SSPLK_SmallArray:
22991bc56edSDimitry Andric         SmallArrayObjs.insert(i);
23091bc56edSDimitry Andric         continue;
23191bc56edSDimitry Andric       case StackProtector::SSPLK_AddrOf:
23291bc56edSDimitry Andric         AddrOfObjs.insert(i);
23391bc56edSDimitry Andric         continue;
23491bc56edSDimitry Andric       case StackProtector::SSPLK_LargeArray:
23591bc56edSDimitry Andric         LargeArrayObjs.insert(i);
23691bc56edSDimitry Andric         continue;
237e580952dSDimitry Andric       }
23891bc56edSDimitry Andric       llvm_unreachable("Unexpected SSPLayoutKind.");
23991bc56edSDimitry Andric     }
24091bc56edSDimitry Andric 
24191bc56edSDimitry Andric     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
24291bc56edSDimitry Andric                           Offset, MaxAlign);
24391bc56edSDimitry Andric     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
24491bc56edSDimitry Andric                           Offset, MaxAlign);
24591bc56edSDimitry Andric     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
24691bc56edSDimitry Andric                           Offset, MaxAlign);
247e580952dSDimitry Andric   }
248e580952dSDimitry Andric 
249e580952dSDimitry Andric   // Then assign frame offsets to stack objects that are not used to spill
250e580952dSDimitry Andric   // callee saved registers.
251d88c1a5aSDimitry Andric   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
252d88c1a5aSDimitry Andric     if (MFI.isDeadObjectIndex(i))
253e580952dSDimitry Andric       continue;
254d88c1a5aSDimitry Andric     if (MFI.getStackProtectorIndex() == (int)i)
255e580952dSDimitry Andric       continue;
25691bc56edSDimitry Andric     if (ProtectedObjs.count(i))
257e580952dSDimitry Andric       continue;
258e580952dSDimitry Andric 
259e580952dSDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
260e580952dSDimitry Andric   }
261e580952dSDimitry Andric 
262e580952dSDimitry Andric   // Remember how big this blob of stack space is
263d88c1a5aSDimitry Andric   MFI.setLocalFrameSize(Offset);
264d88c1a5aSDimitry Andric   MFI.setLocalFrameMaxAlign(MaxAlign);
265e580952dSDimitry Andric }
266e580952dSDimitry Andric 
267e580952dSDimitry Andric static inline bool
268ff0cc061SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
269ff0cc061SDimitry Andric                        int64_t BaseOffset,
270e580952dSDimitry Andric                        int64_t FrameSizeAdjust,
271e580952dSDimitry Andric                        int64_t LocalFrameOffset,
2723ca95b02SDimitry Andric                        const MachineInstr &MI,
273e580952dSDimitry Andric                        const TargetRegisterInfo *TRI) {
274e580952dSDimitry Andric   // Check if the relative offset from the where the base register references
275e580952dSDimitry Andric   // to the target address is in range for the instruction.
276284c1978SDimitry Andric   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
2773ca95b02SDimitry Andric   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
278e580952dSDimitry Andric }
279e580952dSDimitry Andric 
280e580952dSDimitry Andric bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
281e580952dSDimitry Andric   // Scan the function's instructions looking for frame index references.
282e580952dSDimitry Andric   // For each, ask the target if it wants a virtual base register for it
283e580952dSDimitry Andric   // based on what we can tell it about where the local will end up in the
284e580952dSDimitry Andric   // stack frame. If it wants one, re-use a suitable one we've previously
285e580952dSDimitry Andric   // allocated, or if there isn't one that fits the bill, allocate a new one
286e580952dSDimitry Andric   // and ask the target to create a defining instruction for it.
287e580952dSDimitry Andric   bool UsedBaseReg = false;
288e580952dSDimitry Andric 
289d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
29039d628a0SDimitry Andric   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
29139d628a0SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
292e580952dSDimitry Andric   bool StackGrowsDown =
2932754fe60SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
294e580952dSDimitry Andric 
295e580952dSDimitry Andric   // Collect all of the instructions in the block that reference
296e580952dSDimitry Andric   // a frame index. Also store the frame index referenced to ease later
297e580952dSDimitry Andric   // lookup. (For any insn that has more than one FI reference, we arbitrarily
298e580952dSDimitry Andric   // choose the first one).
299e580952dSDimitry Andric   SmallVector<FrameRef, 64> FrameReferenceInsns;
3002754fe60SDimitry Andric 
301d88c1a5aSDimitry Andric   unsigned Order = 0;
302d88c1a5aSDimitry Andric 
3033ca95b02SDimitry Andric   for (MachineBasicBlock &BB : Fn) {
3043ca95b02SDimitry Andric     for (MachineInstr &MI : BB) {
30591bc56edSDimitry Andric       // Debug value, stackmap and patchpoint instructions can't be out of
30691bc56edSDimitry Andric       // range, so they don't need any updates.
3073ca95b02SDimitry Andric       if (MI.isDebugValue() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
3083ca95b02SDimitry Andric           MI.getOpcode() == TargetOpcode::STACKMAP ||
3093ca95b02SDimitry Andric           MI.getOpcode() == TargetOpcode::PATCHPOINT)
310e580952dSDimitry Andric         continue;
3112754fe60SDimitry Andric 
312e580952dSDimitry Andric       // For now, allocate the base register(s) within the basic block
313e580952dSDimitry Andric       // where they're used, and don't try to keep them around outside
314e580952dSDimitry Andric       // of that. It may be beneficial to try sharing them more broadly
315e580952dSDimitry Andric       // than that, but the increased register pressure makes that a
316e580952dSDimitry Andric       // tricky thing to balance. Investigate if re-materializing these
317e580952dSDimitry Andric       // becomes an issue.
3183ca95b02SDimitry Andric       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
319e580952dSDimitry Andric         // Consider replacing all frame index operands that reference
320e580952dSDimitry Andric         // an object allocated in the local block.
3213ca95b02SDimitry Andric         if (MI.getOperand(i).isFI()) {
322e580952dSDimitry Andric           // Don't try this with values not in the local block.
323d88c1a5aSDimitry Andric           if (!MFI.isObjectPreAllocated(MI.getOperand(i).getIndex()))
324e580952dSDimitry Andric             break;
3253ca95b02SDimitry Andric           int Idx = MI.getOperand(i).getIndex();
326284c1978SDimitry Andric           int64_t LocalOffset = LocalOffsets[Idx];
3273ca95b02SDimitry Andric           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
328284c1978SDimitry Andric             break;
329d88c1a5aSDimitry Andric           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
330e580952dSDimitry Andric           break;
331e580952dSDimitry Andric         }
332e580952dSDimitry Andric       }
333e580952dSDimitry Andric     }
334e580952dSDimitry Andric   }
3352754fe60SDimitry Andric 
336d88c1a5aSDimitry Andric   // Sort the frame references by local offset.
337d88c1a5aSDimitry Andric   // Use frame index as a tie-breaker in case MI's have the same offset.
338d88c1a5aSDimitry Andric   std::sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
339e580952dSDimitry Andric 
3407d523365SDimitry Andric   MachineBasicBlock *Entry = &Fn.front();
341e580952dSDimitry Andric 
342284c1978SDimitry Andric   unsigned BaseReg = 0;
343284c1978SDimitry Andric   int64_t BaseOffset = 0;
344284c1978SDimitry Andric 
3452754fe60SDimitry Andric   // Loop through the frame references and allocate for them as necessary.
346e580952dSDimitry Andric   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
347284c1978SDimitry Andric     FrameRef &FR = FrameReferenceInsns[ref];
3483ca95b02SDimitry Andric     MachineInstr &MI = *FR.getMachineInstr();
349284c1978SDimitry Andric     int64_t LocalOffset = FR.getLocalOffset();
350284c1978SDimitry Andric     int FrameIdx = FR.getFrameIndex();
351d88c1a5aSDimitry Andric     assert(MFI.isObjectPreAllocated(FrameIdx) &&
352e580952dSDimitry Andric            "Only pre-allocated locals expected!");
353e580952dSDimitry Andric 
3543ca95b02SDimitry Andric     DEBUG(dbgs() << "Considering: " << MI);
355284c1978SDimitry Andric 
356284c1978SDimitry Andric     unsigned idx = 0;
3573ca95b02SDimitry Andric     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
3583ca95b02SDimitry Andric       if (!MI.getOperand(idx).isFI())
359284c1978SDimitry Andric         continue;
360284c1978SDimitry Andric 
3613ca95b02SDimitry Andric       if (FrameIdx == MI.getOperand(idx).getIndex())
362284c1978SDimitry Andric         break;
363284c1978SDimitry Andric     }
364284c1978SDimitry Andric 
3653ca95b02SDimitry Andric     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
366284c1978SDimitry Andric 
367e580952dSDimitry Andric     int64_t Offset = 0;
368d88c1a5aSDimitry Andric     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
369e580952dSDimitry Andric 
3703ca95b02SDimitry Andric     DEBUG(dbgs() << "  Replacing FI in: " << MI);
371e580952dSDimitry Andric 
372e580952dSDimitry Andric     // If we have a suitable base register available, use it; otherwise
373e580952dSDimitry Andric     // create a new one. Note that any offset encoded in the
374e580952dSDimitry Andric     // instruction itself will be taken into account by the target,
375e580952dSDimitry Andric     // so we don't have to adjust for it here when reusing a base
376e580952dSDimitry Andric     // register.
3773ca95b02SDimitry Andric     if (UsedBaseReg &&
3783ca95b02SDimitry Andric         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
3793ca95b02SDimitry Andric                                LocalOffset, MI, TRI)) {
380284c1978SDimitry Andric       DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
381e580952dSDimitry Andric       // We found a register to reuse.
382284c1978SDimitry Andric       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
383e580952dSDimitry Andric     } else {
3843ca95b02SDimitry Andric       // No previously defined register was in range, so create a new one.
3853ca95b02SDimitry Andric       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
386284c1978SDimitry Andric 
387284c1978SDimitry Andric       int64_t PrevBaseOffset = BaseOffset;
388284c1978SDimitry Andric       BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
389284c1978SDimitry Andric 
390284c1978SDimitry Andric       // We'd like to avoid creating single-use virtual base registers.
391284c1978SDimitry Andric       // Because the FrameRefs are in sorted order, and we've already
392284c1978SDimitry Andric       // processed all FrameRefs before this one, just check whether or not
393284c1978SDimitry Andric       // the next FrameRef will be able to reuse this new register. If not,
394284c1978SDimitry Andric       // then don't bother creating it.
39591bc56edSDimitry Andric       if (ref + 1 >= e ||
39691bc56edSDimitry Andric           !lookupCandidateBaseReg(
397ff0cc061SDimitry Andric               BaseReg, BaseOffset, FrameSizeAdjust,
39891bc56edSDimitry Andric               FrameReferenceInsns[ref + 1].getLocalOffset(),
3993ca95b02SDimitry Andric               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
400284c1978SDimitry Andric         BaseOffset = PrevBaseOffset;
401284c1978SDimitry Andric         continue;
402284c1978SDimitry Andric       }
403284c1978SDimitry Andric 
4042cab237bSDimitry Andric       const MachineFunction *MF = MI.getMF();
4057ae0e2c9SDimitry Andric       const TargetRegisterClass *RC = TRI->getPointerRegClass(*MF);
406e580952dSDimitry Andric       BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
407e580952dSDimitry Andric 
408e580952dSDimitry Andric       DEBUG(dbgs() << "  Materializing base register " << BaseReg <<
409284c1978SDimitry Andric             " at frame local offset " << LocalOffset + InstrOffset << "\n");
4102754fe60SDimitry Andric 
411e580952dSDimitry Andric       // Tell the target to insert the instruction to initialize
412e580952dSDimitry Andric       // the base register.
4132754fe60SDimitry Andric       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
4142754fe60SDimitry Andric       TRI->materializeFrameBaseRegister(Entry, BaseReg, FrameIdx,
4152754fe60SDimitry Andric                                         InstrOffset);
416e580952dSDimitry Andric 
417e580952dSDimitry Andric       // The base register already includes any offset specified
418e580952dSDimitry Andric       // by the instruction, so account for that so it doesn't get
419e580952dSDimitry Andric       // applied twice.
420e580952dSDimitry Andric       Offset = -InstrOffset;
421e580952dSDimitry Andric 
422e580952dSDimitry Andric       ++NumBaseRegisters;
423e580952dSDimitry Andric       UsedBaseReg = true;
424e580952dSDimitry Andric     }
425e580952dSDimitry Andric     assert(BaseReg != 0 && "Unable to allocate virtual base register!");
426e580952dSDimitry Andric 
427e580952dSDimitry Andric     // Modify the instruction to use the new base register rather
428e580952dSDimitry Andric     // than the frame index operand.
4293ca95b02SDimitry Andric     TRI->resolveFrameIndex(MI, BaseReg, Offset);
4303ca95b02SDimitry Andric     DEBUG(dbgs() << "Resolved: " << MI);
431e580952dSDimitry Andric 
432e580952dSDimitry Andric     ++NumReplacements;
433e580952dSDimitry Andric   }
434284c1978SDimitry Andric 
435e580952dSDimitry Andric   return UsedBaseReg;
436e580952dSDimitry Andric }
437