LocalStackSlotAllocation.cpp 17 KB

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