1 //===-- SILowerSGPRSPills.cpp ---------------------------------------------===//
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 // Handle SGPR spills. This pass takes the place of PrologEpilogInserter for all
10 // SGPR spills, so must insert CSR SGPR spills as well as expand them.
11 //
12 // This pass must never create new SGPR virtual registers.
13 //
14 // FIXME: Must stop RegScavenger spills in later passes.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "AMDGPU.h"
19 #include "GCNSubtarget.h"
20 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/InitializePasses.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "si-lower-sgpr-spills"
29 
30 using MBBVector = SmallVector<MachineBasicBlock *, 4>;
31 
32 namespace {
33 
34 static cl::opt<bool> EnableSpillVGPRToAGPR(
35   "amdgpu-spill-vgpr-to-agpr",
36   cl::desc("Enable spilling VGPRs to AGPRs"),
37   cl::ReallyHidden,
38   cl::init(true));
39 
40 class SILowerSGPRSpills : public MachineFunctionPass {
41 private:
42   const SIRegisterInfo *TRI = nullptr;
43   const SIInstrInfo *TII = nullptr;
44   VirtRegMap *VRM = nullptr;
45   LiveIntervals *LIS = nullptr;
46 
47   // Save and Restore blocks of the current function. Typically there is a
48   // single save block, unless Windows EH funclets are involved.
49   MBBVector SaveBlocks;
50   MBBVector RestoreBlocks;
51 
52 public:
53   static char ID;
54 
55   SILowerSGPRSpills() : MachineFunctionPass(ID) {}
56 
57   void calculateSaveRestoreBlocks(MachineFunction &MF);
58   bool spillCalleeSavedRegs(MachineFunction &MF);
59 
60   bool runOnMachineFunction(MachineFunction &MF) override;
61 
62   void getAnalysisUsage(AnalysisUsage &AU) const override {
63     AU.setPreservesAll();
64     MachineFunctionPass::getAnalysisUsage(AU);
65   }
66 };
67 
68 } // end anonymous namespace
69 
70 char SILowerSGPRSpills::ID = 0;
71 
72 INITIALIZE_PASS_BEGIN(SILowerSGPRSpills, DEBUG_TYPE,
73                       "SI lower SGPR spill instructions", false, false)
74 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
75 INITIALIZE_PASS_END(SILowerSGPRSpills, DEBUG_TYPE,
76                     "SI lower SGPR spill instructions", false, false)
77 
78 char &llvm::SILowerSGPRSpillsID = SILowerSGPRSpills::ID;
79 
80 /// Insert restore code for the callee-saved registers used in the function.
81 static void insertCSRSaves(MachineBasicBlock &SaveBlock,
82                            ArrayRef<CalleeSavedInfo> CSI,
83                            LiveIntervals *LIS) {
84   MachineFunction &MF = *SaveBlock.getParent();
85   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
86   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
87   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
88 
89   MachineBasicBlock::iterator I = SaveBlock.begin();
90   if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
91     for (const CalleeSavedInfo &CS : CSI) {
92       // Insert the spill to the stack frame.
93       MCRegister Reg = CS.getReg();
94 
95       MachineInstrSpan MIS(I, &SaveBlock);
96       const TargetRegisterClass *RC =
97         TRI->getMinimalPhysRegClass(Reg, MVT::i32);
98 
99       TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC,
100                               TRI);
101 
102       if (LIS) {
103         assert(std::distance(MIS.begin(), I) == 1);
104         MachineInstr &Inst = *std::prev(I);
105 
106         LIS->InsertMachineInstrInMaps(Inst);
107         LIS->removeAllRegUnitsForPhysReg(Reg);
108       }
109     }
110   }
111 }
112 
113 /// Insert restore code for the callee-saved registers used in the function.
114 static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
115                               MutableArrayRef<CalleeSavedInfo> CSI,
116                               LiveIntervals *LIS) {
117   MachineFunction &MF = *RestoreBlock.getParent();
118   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
119   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
120   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
121 
122   // Restore all registers immediately before the return and any
123   // terminators that precede it.
124   MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator();
125 
126   // FIXME: Just emit the readlane/writelane directly
127   if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
128     for (const CalleeSavedInfo &CI : reverse(CSI)) {
129       unsigned Reg = CI.getReg();
130       const TargetRegisterClass *RC =
131         TRI->getMinimalPhysRegClass(Reg, MVT::i32);
132 
133       TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI);
134       assert(I != RestoreBlock.begin() &&
135              "loadRegFromStackSlot didn't insert any code!");
136       // Insert in reverse order.  loadRegFromStackSlot can insert
137       // multiple instructions.
138 
139       if (LIS) {
140         MachineInstr &Inst = *std::prev(I);
141         LIS->InsertMachineInstrInMaps(Inst);
142         LIS->removeAllRegUnitsForPhysReg(Reg);
143       }
144     }
145   }
146 }
147 
148 /// Compute the sets of entry and return blocks for saving and restoring
149 /// callee-saved registers, and placing prolog and epilog code.
150 void SILowerSGPRSpills::calculateSaveRestoreBlocks(MachineFunction &MF) {
151   const MachineFrameInfo &MFI = MF.getFrameInfo();
152 
153   // Even when we do not change any CSR, we still want to insert the
154   // prologue and epilogue of the function.
155   // So set the save points for those.
156 
157   // Use the points found by shrink-wrapping, if any.
158   if (MFI.getSavePoint()) {
159     SaveBlocks.push_back(MFI.getSavePoint());
160     assert(MFI.getRestorePoint() && "Both restore and save must be set");
161     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
162     // If RestoreBlock does not have any successor and is not a return block
163     // then the end point is unreachable and we do not need to insert any
164     // epilogue.
165     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
166       RestoreBlocks.push_back(RestoreBlock);
167     return;
168   }
169 
170   // Save refs to entry and return blocks.
171   SaveBlocks.push_back(&MF.front());
172   for (MachineBasicBlock &MBB : MF) {
173     if (MBB.isEHFuncletEntry())
174       SaveBlocks.push_back(&MBB);
175     if (MBB.isReturnBlock())
176       RestoreBlocks.push_back(&MBB);
177   }
178 }
179 
180 // TODO: To support shrink wrapping, this would need to copy
181 // PrologEpilogInserter's updateLiveness.
182 static void updateLiveness(MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI) {
183   MachineBasicBlock &EntryBB = MF.front();
184 
185   for (const CalleeSavedInfo &CSIReg : CSI)
186     EntryBB.addLiveIn(CSIReg.getReg());
187   EntryBB.sortUniqueLiveIns();
188 }
189 
190 bool SILowerSGPRSpills::spillCalleeSavedRegs(MachineFunction &MF) {
191   MachineRegisterInfo &MRI = MF.getRegInfo();
192   const Function &F = MF.getFunction();
193   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
194   const SIFrameLowering *TFI = ST.getFrameLowering();
195   MachineFrameInfo &MFI = MF.getFrameInfo();
196   RegScavenger *RS = nullptr;
197 
198   // Determine which of the registers in the callee save list should be saved.
199   BitVector SavedRegs;
200   TFI->determineCalleeSavesSGPR(MF, SavedRegs, RS);
201 
202   // Add the code to save and restore the callee saved registers.
203   if (!F.hasFnAttribute(Attribute::Naked)) {
204     // FIXME: This is a lie. The CalleeSavedInfo is incomplete, but this is
205     // necessary for verifier liveness checks.
206     MFI.setCalleeSavedInfoValid(true);
207 
208     std::vector<CalleeSavedInfo> CSI;
209     const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
210 
211     for (unsigned I = 0; CSRegs[I]; ++I) {
212       MCRegister Reg = CSRegs[I];
213 
214       if (SavedRegs.test(Reg)) {
215         const TargetRegisterClass *RC =
216           TRI->getMinimalPhysRegClass(Reg, MVT::i32);
217         int JunkFI = MFI.CreateStackObject(TRI->getSpillSize(*RC),
218                                            TRI->getSpillAlign(*RC), true);
219 
220         CSI.push_back(CalleeSavedInfo(Reg, JunkFI));
221       }
222     }
223 
224     if (!CSI.empty()) {
225       for (MachineBasicBlock *SaveBlock : SaveBlocks)
226         insertCSRSaves(*SaveBlock, CSI, LIS);
227 
228       // Add live ins to save blocks.
229       assert(SaveBlocks.size() == 1 && "shrink wrapping not fully implemented");
230       updateLiveness(MF, CSI);
231 
232       for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
233         insertCSRRestores(*RestoreBlock, CSI, LIS);
234       return true;
235     }
236   }
237 
238   return false;
239 }
240 
241 // Find lowest available VGPR and use it as VGPR reserved for SGPR spills.
242 static bool lowerShiftReservedVGPR(MachineFunction &MF,
243                                    const GCNSubtarget &ST) {
244   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
245   const Register PreReservedVGPR = FuncInfo->VGPRReservedForSGPRSpill;
246   // Early out if pre-reservation of a VGPR for SGPR spilling is disabled.
247   if (!PreReservedVGPR)
248     return false;
249 
250   // If there are no free lower VGPRs available, default to using the
251   // pre-reserved register instead.
252   const SIRegisterInfo *TRI = ST.getRegisterInfo();
253   Register LowestAvailableVGPR =
254       TRI->findUnusedRegister(MF.getRegInfo(), &AMDGPU::VGPR_32RegClass, MF);
255   if (!LowestAvailableVGPR)
256     LowestAvailableVGPR = PreReservedVGPR;
257 
258   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
259   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
260   Optional<int> FI;
261   // Check if we are reserving a CSR. Create a stack object for a possible spill
262   // in the function prologue.
263   if (FuncInfo->isCalleeSavedReg(CSRegs, LowestAvailableVGPR))
264     FI = FrameInfo.CreateSpillStackObject(4, Align(4));
265 
266   // Find saved info about the pre-reserved register.
267   const auto *ReservedVGPRInfoItr =
268       llvm::find_if(FuncInfo->getSGPRSpillVGPRs(),
269                     [PreReservedVGPR](const auto &SpillRegInfo) {
270                       return SpillRegInfo.VGPR == PreReservedVGPR;
271                     });
272 
273   assert(ReservedVGPRInfoItr != FuncInfo->getSGPRSpillVGPRs().end());
274   auto Index =
275       std::distance(FuncInfo->getSGPRSpillVGPRs().begin(), ReservedVGPRInfoItr);
276 
277   FuncInfo->setSGPRSpillVGPRs(LowestAvailableVGPR, FI, Index);
278 
279   for (MachineBasicBlock &MBB : MF) {
280     assert(LowestAvailableVGPR.isValid() && "Did not find an available VGPR");
281     MBB.addLiveIn(LowestAvailableVGPR);
282     MBB.sortUniqueLiveIns();
283   }
284 
285   return true;
286 }
287 
288 bool SILowerSGPRSpills::runOnMachineFunction(MachineFunction &MF) {
289   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
290   TII = ST.getInstrInfo();
291   TRI = &TII->getRegisterInfo();
292 
293   VRM = getAnalysisIfAvailable<VirtRegMap>();
294 
295   assert(SaveBlocks.empty() && RestoreBlocks.empty());
296 
297   // First, expose any CSR SGPR spills. This is mostly the same as what PEI
298   // does, but somewhat simpler.
299   calculateSaveRestoreBlocks(MF);
300   bool HasCSRs = spillCalleeSavedRegs(MF);
301 
302   MachineFrameInfo &MFI = MF.getFrameInfo();
303   if (!MFI.hasStackObjects() && !HasCSRs) {
304     SaveBlocks.clear();
305     RestoreBlocks.clear();
306     return false;
307   }
308 
309   MachineRegisterInfo &MRI = MF.getRegInfo();
310   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
311   const bool SpillVGPRToAGPR = ST.hasMAIInsts() && FuncInfo->hasSpilledVGPRs()
312     && EnableSpillVGPRToAGPR;
313 
314   bool MadeChange = false;
315 
316   const bool SpillToAGPR = EnableSpillVGPRToAGPR && ST.hasMAIInsts();
317   std::unique_ptr<RegScavenger> RS;
318 
319   bool NewReservedRegs = false;
320 
321   // TODO: CSR VGPRs will never be spilled to AGPRs. These can probably be
322   // handled as SpilledToReg in regular PrologEpilogInserter.
323   const bool HasSGPRSpillToVGPR = TRI->spillSGPRToVGPR() &&
324                                   (HasCSRs || FuncInfo->hasSpilledSGPRs());
325   if (HasSGPRSpillToVGPR || SpillVGPRToAGPR) {
326     // Process all SGPR spills before frame offsets are finalized. Ideally SGPRs
327     // are spilled to VGPRs, in which case we can eliminate the stack usage.
328     //
329     // This operates under the assumption that only other SGPR spills are users
330     // of the frame index.
331 
332     lowerShiftReservedVGPR(MF, ST);
333 
334     for (MachineBasicBlock &MBB : MF) {
335       MachineBasicBlock::iterator Next;
336       for (auto I = MBB.begin(), E = MBB.end(); I != E; I = Next) {
337         MachineInstr &MI = *I;
338         Next = std::next(I);
339 
340         if (SpillToAGPR && TII->isVGPRSpill(MI)) {
341           // Try to eliminate stack used by VGPR spills before frame
342           // finalization.
343           unsigned FIOp = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
344                                                      AMDGPU::OpName::vaddr);
345           int FI = MI.getOperand(FIOp).getIndex();
346           Register VReg =
347               TII->getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
348           if (FuncInfo->allocateVGPRSpillToAGPR(MF, FI,
349                                                 TRI->isAGPR(MRI, VReg))) {
350             NewReservedRegs = true;
351             if (!RS)
352               RS.reset(new RegScavenger());
353 
354             // FIXME: change to enterBasicBlockEnd()
355             RS->enterBasicBlock(MBB);
356             TRI->eliminateFrameIndex(MI, 0, FIOp, RS.get());
357             continue;
358           }
359         }
360 
361         if (!TII->isSGPRSpill(MI))
362           continue;
363 
364         int FI = TII->getNamedOperand(MI, AMDGPU::OpName::addr)->getIndex();
365         assert(MFI.getStackID(FI) == TargetStackID::SGPRSpill);
366         if (FuncInfo->allocateSGPRSpillToVGPR(MF, FI)) {
367           NewReservedRegs = true;
368           bool Spilled = TRI->eliminateSGPRToVGPRSpillFrameIndex(MI, FI, nullptr);
369           (void)Spilled;
370           assert(Spilled && "failed to spill SGPR to VGPR when allocated");
371         }
372       }
373     }
374 
375     for (MachineBasicBlock &MBB : MF) {
376       for (auto SSpill : FuncInfo->getSGPRSpillVGPRs())
377         MBB.addLiveIn(SSpill.VGPR);
378 
379       for (MCPhysReg Reg : FuncInfo->getVGPRSpillAGPRs())
380         MBB.addLiveIn(Reg);
381 
382       for (MCPhysReg Reg : FuncInfo->getAGPRSpillVGPRs())
383         MBB.addLiveIn(Reg);
384 
385       MBB.sortUniqueLiveIns();
386     }
387 
388     MadeChange = true;
389   } else if (FuncInfo->VGPRReservedForSGPRSpill) {
390     FuncInfo->removeVGPRForSGPRSpill(FuncInfo->VGPRReservedForSGPRSpill, MF);
391   }
392 
393   SaveBlocks.clear();
394   RestoreBlocks.clear();
395 
396   // Updated the reserved registers with any VGPRs added for SGPR spills.
397   if (NewReservedRegs)
398     MRI.freezeReservedRegs(MF);
399 
400   return MadeChange;
401 }
402