LocalStackSlotAllocation.cpp 17 KB

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