LocalStackSlotAllocation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass assigns local frame indices to stack slots relative to one another
  10. // and allocates additional base registers to access them when the target
  11. // estimates they are likely to be out of range of stack pointer and frame
  12. // pointer relative addressing.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/CodeGen/MachineBasicBlock.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineFunction.h"
  22. #include "llvm/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineOperand.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/TargetFrameLowering.h"
  27. #include "llvm/CodeGen/TargetOpcodes.h"
  28. #include "llvm/CodeGen/TargetRegisterInfo.h"
  29. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  30. #include "llvm/InitializePasses.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, Align &MaxAlign);
  70. void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
  71. SmallSet<int, 16> &ProtectedObjs,
  72. MachineFrameInfo &MFI, bool StackGrowsDown,
  73. int64_t &Offset, Align &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 (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
  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, int FrameIdx,
  116. int64_t &Offset, bool StackGrowsDown,
  117. Align &MaxAlign) {
  118. // If the stack grows down, add the object size to find the lowest address.
  119. if (StackGrowsDown)
  120. Offset += MFI.getObjectSize(FrameIdx);
  121. Align Alignment = MFI.getObjectAlign(FrameIdx);
  122. // If the alignment of this object is greater than that of the stack, then
  123. // increase the stack alignment to match.
  124. MaxAlign = std::max(MaxAlign, Alignment);
  125. // Adjust to alignment boundary.
  126. Offset = alignTo(Offset, Alignment);
  127. int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
  128. LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
  129. << LocalOffset << "\n");
  130. // Keep the offset available for base register allocation
  131. LocalOffsets[FrameIdx] = LocalOffset;
  132. // And tell MFI about it for PEI to use later
  133. MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
  134. if (!StackGrowsDown)
  135. Offset += MFI.getObjectSize(FrameIdx);
  136. ++NumAllocations;
  137. }
  138. /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
  139. /// those required to be close to the Stack Protector) to stack offsets.
  140. void LocalStackSlotPass::AssignProtectedObjSet(
  141. const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
  142. MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
  143. Align &MaxAlign) {
  144. for (int i : UnassignedObjs) {
  145. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  146. ProtectedObjs.insert(i);
  147. }
  148. }
  149. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  150. /// abstract stack objects.
  151. void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
  152. // Loop over all of the stack objects, assigning sequential addresses...
  153. MachineFrameInfo &MFI = Fn.getFrameInfo();
  154. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  155. bool StackGrowsDown =
  156. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  157. int64_t Offset = 0;
  158. Align MaxAlign;
  159. // Make sure that the stack protector comes before the local variables on the
  160. // stack.
  161. SmallSet<int, 16> ProtectedObjs;
  162. if (MFI.hasStackProtectorIndex()) {
  163. int StackProtectorFI = MFI.getStackProtectorIndex();
  164. // We need to make sure we didn't pre-allocate the stack protector when
  165. // doing this.
  166. // If we already have a stack protector, this will re-assign it to a slot
  167. // that is **not** covering the protected objects.
  168. assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
  169. "Stack protector pre-allocated in LocalStackSlotAllocation");
  170. StackObjSet LargeArrayObjs;
  171. StackObjSet SmallArrayObjs;
  172. StackObjSet AddrOfObjs;
  173. // Only place the stack protector in the local stack area if the target
  174. // allows it.
  175. if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
  176. AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
  177. MaxAlign);
  178. // Assign large stack objects first.
  179. for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
  180. if (MFI.isDeadObjectIndex(i))
  181. continue;
  182. if (StackProtectorFI == (int)i)
  183. continue;
  184. if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
  185. continue;
  186. switch (MFI.getObjectSSPLayout(i)) {
  187. case MachineFrameInfo::SSPLK_None:
  188. continue;
  189. case MachineFrameInfo::SSPLK_SmallArray:
  190. SmallArrayObjs.insert(i);
  191. continue;
  192. case MachineFrameInfo::SSPLK_AddrOf:
  193. AddrOfObjs.insert(i);
  194. continue;
  195. case MachineFrameInfo::SSPLK_LargeArray:
  196. LargeArrayObjs.insert(i);
  197. continue;
  198. }
  199. llvm_unreachable("Unexpected SSPLayoutKind.");
  200. }
  201. AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  202. Offset, MaxAlign);
  203. AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  204. Offset, MaxAlign);
  205. AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
  206. Offset, MaxAlign);
  207. }
  208. // Then assign frame offsets to stack objects that are not used to spill
  209. // callee saved registers.
  210. for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
  211. if (MFI.isDeadObjectIndex(i))
  212. continue;
  213. if (MFI.getStackProtectorIndex() == (int)i)
  214. continue;
  215. if (ProtectedObjs.count(i))
  216. continue;
  217. if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
  218. continue;
  219. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  220. }
  221. // Remember how big this blob of stack space is
  222. MFI.setLocalFrameSize(Offset);
  223. MFI.setLocalFrameMaxAlign(MaxAlign);
  224. }
  225. static inline bool
  226. lookupCandidateBaseReg(unsigned BaseReg,
  227. int64_t BaseOffset,
  228. int64_t FrameSizeAdjust,
  229. int64_t LocalFrameOffset,
  230. const MachineInstr &MI,
  231. const TargetRegisterInfo *TRI) {
  232. // Check if the relative offset from the where the base register references
  233. // to the target address is in range for the instruction.
  234. int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
  235. return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
  236. }
  237. bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
  238. // Scan the function's instructions looking for frame index references.
  239. // For each, ask the target if it wants a virtual base register for it
  240. // based on what we can tell it about where the local will end up in the
  241. // stack frame. If it wants one, re-use a suitable one we've previously
  242. // allocated, or if there isn't one that fits the bill, allocate a new one
  243. // and ask the target to create a defining instruction for it.
  244. bool UsedBaseReg = false;
  245. MachineFrameInfo &MFI = Fn.getFrameInfo();
  246. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  247. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  248. bool StackGrowsDown =
  249. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  250. // Collect all of the instructions in the block that reference
  251. // a frame index. Also store the frame index referenced to ease later
  252. // lookup. (For any insn that has more than one FI reference, we arbitrarily
  253. // choose the first one).
  254. SmallVector<FrameRef, 64> FrameReferenceInsns;
  255. unsigned Order = 0;
  256. for (MachineBasicBlock &BB : Fn) {
  257. for (MachineInstr &MI : BB) {
  258. // Debug value, stackmap and patchpoint instructions can't be out of
  259. // range, so they don't need any updates.
  260. if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
  261. MI.getOpcode() == TargetOpcode::STACKMAP ||
  262. MI.getOpcode() == TargetOpcode::PATCHPOINT)
  263. continue;
  264. // For now, allocate the base register(s) within the basic block
  265. // where they're used, and don't try to keep them around outside
  266. // of that. It may be beneficial to try sharing them more broadly
  267. // than that, but the increased register pressure makes that a
  268. // tricky thing to balance. Investigate if re-materializing these
  269. // becomes an issue.
  270. for (const MachineOperand &MO : MI.operands()) {
  271. // Consider replacing all frame index operands that reference
  272. // an object allocated in the local block.
  273. if (MO.isFI()) {
  274. // Don't try this with values not in the local block.
  275. if (!MFI.isObjectPreAllocated(MO.getIndex()))
  276. break;
  277. int Idx = MO.getIndex();
  278. int64_t LocalOffset = LocalOffsets[Idx];
  279. if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
  280. break;
  281. FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. // Sort the frame references by local offset.
  288. // Use frame index as a tie-breaker in case MI's have the same offset.
  289. llvm::sort(FrameReferenceInsns);
  290. MachineBasicBlock *Entry = &Fn.front();
  291. unsigned BaseReg = 0;
  292. int64_t BaseOffset = 0;
  293. // Loop through the frame references and allocate for them as necessary.
  294. for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
  295. FrameRef &FR = FrameReferenceInsns[ref];
  296. MachineInstr &MI = *FR.getMachineInstr();
  297. int64_t LocalOffset = FR.getLocalOffset();
  298. int FrameIdx = FR.getFrameIndex();
  299. assert(MFI.isObjectPreAllocated(FrameIdx) &&
  300. "Only pre-allocated locals expected!");
  301. // We need to keep the references to the stack protector slot through frame
  302. // index operands so that it gets resolved by PEI rather than this pass.
  303. // This avoids accesses to the stack protector though virtual base
  304. // registers, and forces PEI to address it using fp/sp/bp.
  305. if (MFI.hasStackProtectorIndex() &&
  306. FrameIdx == MFI.getStackProtectorIndex())
  307. continue;
  308. LLVM_DEBUG(dbgs() << "Considering: " << MI);
  309. unsigned idx = 0;
  310. for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
  311. if (!MI.getOperand(idx).isFI())
  312. continue;
  313. if (FrameIdx == MI.getOperand(idx).getIndex())
  314. break;
  315. }
  316. assert(idx < MI.getNumOperands() && "Cannot find FI operand");
  317. int64_t Offset = 0;
  318. int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
  319. LLVM_DEBUG(dbgs() << " Replacing FI in: " << MI);
  320. // If we have a suitable base register available, use it; otherwise
  321. // create a new one. Note that any offset encoded in the
  322. // instruction itself will be taken into account by the target,
  323. // so we don't have to adjust for it here when reusing a base
  324. // register.
  325. if (UsedBaseReg &&
  326. lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
  327. LocalOffset, MI, TRI)) {
  328. LLVM_DEBUG(dbgs() << " Reusing base register " << BaseReg << "\n");
  329. // We found a register to reuse.
  330. Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
  331. } else {
  332. // No previously defined register was in range, so create a new one.
  333. int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
  334. int64_t PrevBaseOffset = BaseOffset;
  335. BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
  336. // We'd like to avoid creating single-use virtual base registers.
  337. // Because the FrameRefs are in sorted order, and we've already
  338. // processed all FrameRefs before this one, just check whether or not
  339. // the next FrameRef will be able to reuse this new register. If not,
  340. // then don't bother creating it.
  341. if (ref + 1 >= e ||
  342. !lookupCandidateBaseReg(
  343. BaseReg, BaseOffset, FrameSizeAdjust,
  344. FrameReferenceInsns[ref + 1].getLocalOffset(),
  345. *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
  346. BaseOffset = PrevBaseOffset;
  347. continue;
  348. }
  349. const MachineFunction *MF = MI.getMF();
  350. const TargetRegisterClass *RC = TRI->getPointerRegClass(*MF);
  351. BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
  352. LLVM_DEBUG(dbgs() << " Materializing base register"
  353. << " at frame local offset "
  354. << LocalOffset + InstrOffset);
  355. // Tell the target to insert the instruction to initialize
  356. // the base register.
  357. // MachineBasicBlock::iterator InsertionPt = Entry->begin();
  358. BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
  359. LLVM_DEBUG(dbgs() << " into " << printReg(BaseReg, TRI) << '\n');
  360. // The base register already includes any offset specified
  361. // by the instruction, so account for that so it doesn't get
  362. // applied twice.
  363. Offset = -InstrOffset;
  364. ++NumBaseRegisters;
  365. UsedBaseReg = true;
  366. }
  367. assert(BaseReg != 0 && "Unable to allocate virtual base register!");
  368. // Modify the instruction to use the new base register rather
  369. // than the frame index operand.
  370. TRI->resolveFrameIndex(MI, BaseReg, Offset);
  371. LLVM_DEBUG(dbgs() << "Resolved: " << MI);
  372. ++NumReplacements;
  373. }
  374. return UsedBaseReg;
  375. }