1 //===----------------------- SIFrameLowering.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 #include "SIFrameLowering.h"
10 #include "AMDGPU.h"
11 #include "GCNSubtarget.h"
12 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
13 #include "SIMachineFunctionInfo.h"
14 #include "llvm/CodeGen/LivePhysRegs.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/RegisterScavenging.h"
17 #include "llvm/Target/TargetMachine.h"
18 
19 using namespace llvm;
20 
21 #define DEBUG_TYPE "frame-info"
22 
23 // Find a scratch register that we can use in the prologue. We avoid using
24 // callee-save registers since they may appear to be free when this is called
25 // from canUseAsPrologue (during shrink wrapping), but then no longer be free
26 // when this is called from emitPrologue.
27 static MCRegister findScratchNonCalleeSaveRegister(MachineRegisterInfo &MRI,
28                                                    LivePhysRegs &LiveRegs,
29                                                    const TargetRegisterClass &RC,
30                                                    bool Unused = false) {
31   // Mark callee saved registers as used so we will not choose them.
32   const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
33   for (unsigned i = 0; CSRegs[i]; ++i)
34     LiveRegs.addReg(CSRegs[i]);
35 
36   if (Unused) {
37     // We are looking for a register that can be used throughout the entire
38     // function, so any use is unacceptable.
39     for (MCRegister Reg : RC) {
40       if (!MRI.isPhysRegUsed(Reg) && LiveRegs.available(MRI, Reg))
41         return Reg;
42     }
43   } else {
44     for (MCRegister Reg : RC) {
45       if (LiveRegs.available(MRI, Reg))
46         return Reg;
47     }
48   }
49 
50   return MCRegister();
51 }
52 
53 static void getVGPRSpillLaneOrTempRegister(MachineFunction &MF,
54                                            LivePhysRegs &LiveRegs,
55                                            Register &TempSGPR,
56                                            Optional<int> &FrameIndex,
57                                            bool IsFP) {
58   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
59   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
60 
61   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
62   const SIRegisterInfo *TRI = ST.getRegisterInfo();
63 
64   // We need to save and restore the current FP/BP.
65 
66   // 1: If there is already a VGPR with free lanes, use it. We
67   // may already have to pay the penalty for spilling a CSR VGPR.
68   if (MFI->haveFreeLanesForSGPRSpill(MF, 1)) {
69     int NewFI = FrameInfo.CreateStackObject(4, Align(4), true, nullptr,
70                                             TargetStackID::SGPRSpill);
71 
72     if (!MFI->allocateSGPRSpillToVGPR(MF, NewFI))
73       llvm_unreachable("allocate SGPR spill should have worked");
74 
75     FrameIndex = NewFI;
76 
77     LLVM_DEBUG(auto Spill = MFI->getSGPRToVGPRSpills(NewFI).front();
78                dbgs() << "Spilling " << (IsFP ? "FP" : "BP") << " to  "
79                       << printReg(Spill.VGPR, TRI) << ':' << Spill.Lane
80                       << '\n');
81     return;
82   }
83 
84   // 2: Next, try to save the FP/BP in an unused SGPR.
85   TempSGPR = findScratchNonCalleeSaveRegister(
86       MF.getRegInfo(), LiveRegs, AMDGPU::SReg_32_XM0_XEXECRegClass, true);
87 
88   if (!TempSGPR) {
89     int NewFI = FrameInfo.CreateStackObject(4, Align(4), true, nullptr,
90                                             TargetStackID::SGPRSpill);
91 
92     if (TRI->spillSGPRToVGPR() && MFI->allocateSGPRSpillToVGPR(MF, NewFI)) {
93       // 3: There's no free lane to spill, and no free register to save FP/BP,
94       // so we're forced to spill another VGPR to use for the spill.
95       FrameIndex = NewFI;
96 
97       LLVM_DEBUG(
98           auto Spill = MFI->getSGPRToVGPRSpills(NewFI).front();
99           dbgs() << (IsFP ? "FP" : "BP") << " requires fallback spill to "
100                  << printReg(Spill.VGPR, TRI) << ':' << Spill.Lane << '\n';);
101     } else {
102       // Remove dead <NewFI> index
103       MF.getFrameInfo().RemoveStackObject(NewFI);
104       // 4: If all else fails, spill the FP/BP to memory.
105       FrameIndex = FrameInfo.CreateSpillStackObject(4, Align(4));
106       LLVM_DEBUG(dbgs() << "Reserved FI " << FrameIndex << " for spilling "
107                         << (IsFP ? "FP" : "BP") << '\n');
108     }
109   } else {
110     LLVM_DEBUG(dbgs() << "Saving " << (IsFP ? "FP" : "BP") << " with copy to "
111                       << printReg(TempSGPR, TRI) << '\n');
112   }
113 }
114 
115 // We need to specially emit stack operations here because a different frame
116 // register is used than in the rest of the function, as getFrameRegister would
117 // use.
118 static void buildPrologSpill(const GCNSubtarget &ST, const SIRegisterInfo &TRI,
119                              const SIMachineFunctionInfo &FuncInfo,
120                              LivePhysRegs &LiveRegs, MachineFunction &MF,
121                              MachineBasicBlock &MBB,
122                              MachineBasicBlock::iterator I, Register SpillReg,
123                              int FI) {
124   unsigned Opc = ST.enableFlatScratch() ? AMDGPU::SCRATCH_STORE_DWORD_SADDR
125                                         : AMDGPU::BUFFER_STORE_DWORD_OFFSET;
126 
127   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
128   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
129   MachineMemOperand *MMO = MF.getMachineMemOperand(
130       PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FI),
131       FrameInfo.getObjectAlign(FI));
132   LiveRegs.addReg(SpillReg);
133   TRI.buildSpillLoadStore(MBB, I, Opc, FI, SpillReg, true,
134                           FuncInfo.getStackPtrOffsetReg(), 0, MMO, nullptr,
135                           &LiveRegs);
136   LiveRegs.removeReg(SpillReg);
137 }
138 
139 static void buildEpilogRestore(const GCNSubtarget &ST,
140                                const SIRegisterInfo &TRI,
141                                const SIMachineFunctionInfo &FuncInfo,
142                                LivePhysRegs &LiveRegs, MachineFunction &MF,
143                                MachineBasicBlock &MBB,
144                                MachineBasicBlock::iterator I, Register SpillReg,
145                                int FI) {
146   unsigned Opc = ST.enableFlatScratch() ? AMDGPU::SCRATCH_LOAD_DWORD_SADDR
147                                         : AMDGPU::BUFFER_LOAD_DWORD_OFFSET;
148 
149   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
150   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
151   MachineMemOperand *MMO = MF.getMachineMemOperand(
152       PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FI),
153       FrameInfo.getObjectAlign(FI));
154   TRI.buildSpillLoadStore(MBB, I, Opc, FI, SpillReg, false,
155                           FuncInfo.getStackPtrOffsetReg(), 0, MMO, nullptr,
156                           &LiveRegs);
157 }
158 
159 static void buildGitPtr(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
160                         const DebugLoc &DL, const SIInstrInfo *TII,
161                         Register TargetReg) {
162   MachineFunction *MF = MBB.getParent();
163   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
164   const SIRegisterInfo *TRI = &TII->getRegisterInfo();
165   const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
166   Register TargetLo = TRI->getSubReg(TargetReg, AMDGPU::sub0);
167   Register TargetHi = TRI->getSubReg(TargetReg, AMDGPU::sub1);
168 
169   if (MFI->getGITPtrHigh() != 0xffffffff) {
170     BuildMI(MBB, I, DL, SMovB32, TargetHi)
171         .addImm(MFI->getGITPtrHigh())
172         .addReg(TargetReg, RegState::ImplicitDefine);
173   } else {
174     const MCInstrDesc &GetPC64 = TII->get(AMDGPU::S_GETPC_B64);
175     BuildMI(MBB, I, DL, GetPC64, TargetReg);
176   }
177   Register GitPtrLo = MFI->getGITPtrLoReg(*MF);
178   MF->getRegInfo().addLiveIn(GitPtrLo);
179   MBB.addLiveIn(GitPtrLo);
180   BuildMI(MBB, I, DL, SMovB32, TargetLo)
181     .addReg(GitPtrLo);
182 }
183 
184 // Emit flat scratch setup code, assuming `MFI->hasFlatScratchInit()`
185 void SIFrameLowering::emitEntryFunctionFlatScratchInit(
186     MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
187     const DebugLoc &DL, Register ScratchWaveOffsetReg) const {
188   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
189   const SIInstrInfo *TII = ST.getInstrInfo();
190   const SIRegisterInfo *TRI = &TII->getRegisterInfo();
191   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
192 
193   // We don't need this if we only have spills since there is no user facing
194   // scratch.
195 
196   // TODO: If we know we don't have flat instructions earlier, we can omit
197   // this from the input registers.
198   //
199   // TODO: We only need to know if we access scratch space through a flat
200   // pointer. Because we only detect if flat instructions are used at all,
201   // this will be used more often than necessary on VI.
202 
203   Register FlatScrInitLo;
204   Register FlatScrInitHi;
205 
206   if (ST.isAmdPalOS()) {
207     // Extract the scratch offset from the descriptor in the GIT
208     LivePhysRegs LiveRegs;
209     LiveRegs.init(*TRI);
210     LiveRegs.addLiveIns(MBB);
211 
212     // Find unused reg to load flat scratch init into
213     MachineRegisterInfo &MRI = MF.getRegInfo();
214     Register FlatScrInit = AMDGPU::NoRegister;
215     ArrayRef<MCPhysReg> AllSGPR64s = TRI->getAllSGPR64(MF);
216     unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 1) / 2;
217     AllSGPR64s = AllSGPR64s.slice(
218         std::min(static_cast<unsigned>(AllSGPR64s.size()), NumPreloaded));
219     Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
220     for (MCPhysReg Reg : AllSGPR64s) {
221       if (LiveRegs.available(MRI, Reg) && MRI.isAllocatable(Reg) &&
222           !TRI->isSubRegisterEq(Reg, GITPtrLoReg)) {
223         FlatScrInit = Reg;
224         break;
225       }
226     }
227     assert(FlatScrInit && "Failed to find free register for scratch init");
228 
229     FlatScrInitLo = TRI->getSubReg(FlatScrInit, AMDGPU::sub0);
230     FlatScrInitHi = TRI->getSubReg(FlatScrInit, AMDGPU::sub1);
231 
232     buildGitPtr(MBB, I, DL, TII, FlatScrInit);
233 
234     // We now have the GIT ptr - now get the scratch descriptor from the entry
235     // at offset 0 (or offset 16 for a compute shader).
236     MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
237     const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
238     auto *MMO = MF.getMachineMemOperand(
239         PtrInfo,
240         MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
241             MachineMemOperand::MODereferenceable,
242         8, Align(4));
243     unsigned Offset =
244         MF.getFunction().getCallingConv() == CallingConv::AMDGPU_CS ? 16 : 0;
245     const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
246     unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
247     BuildMI(MBB, I, DL, LoadDwordX2, FlatScrInit)
248         .addReg(FlatScrInit)
249         .addImm(EncodedOffset) // offset
250         .addImm(0)             // cpol
251         .addMemOperand(MMO);
252 
253     // Mask the offset in [47:0] of the descriptor
254     const MCInstrDesc &SAndB32 = TII->get(AMDGPU::S_AND_B32);
255     BuildMI(MBB, I, DL, SAndB32, FlatScrInitHi)
256         .addReg(FlatScrInitHi)
257         .addImm(0xffff);
258   } else {
259     Register FlatScratchInitReg =
260         MFI->getPreloadedReg(AMDGPUFunctionArgInfo::FLAT_SCRATCH_INIT);
261     assert(FlatScratchInitReg);
262 
263     MachineRegisterInfo &MRI = MF.getRegInfo();
264     MRI.addLiveIn(FlatScratchInitReg);
265     MBB.addLiveIn(FlatScratchInitReg);
266 
267     FlatScrInitLo = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub0);
268     FlatScrInitHi = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub1);
269   }
270 
271   // Do a 64-bit pointer add.
272   if (ST.flatScratchIsPointer()) {
273     if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
274       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), FlatScrInitLo)
275         .addReg(FlatScrInitLo)
276         .addReg(ScratchWaveOffsetReg);
277       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32), FlatScrInitHi)
278         .addReg(FlatScrInitHi)
279         .addImm(0);
280       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32)).
281         addReg(FlatScrInitLo).
282         addImm(int16_t(AMDGPU::Hwreg::ID_FLAT_SCR_LO |
283                        (31 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_)));
284       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32)).
285         addReg(FlatScrInitHi).
286         addImm(int16_t(AMDGPU::Hwreg::ID_FLAT_SCR_HI |
287                        (31 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_)));
288       return;
289     }
290 
291     // For GFX9.
292     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), AMDGPU::FLAT_SCR_LO)
293       .addReg(FlatScrInitLo)
294       .addReg(ScratchWaveOffsetReg);
295     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32), AMDGPU::FLAT_SCR_HI)
296       .addReg(FlatScrInitHi)
297       .addImm(0);
298 
299     return;
300   }
301 
302   assert(ST.getGeneration() < AMDGPUSubtarget::GFX9);
303 
304   // Copy the size in bytes.
305   BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::FLAT_SCR_LO)
306     .addReg(FlatScrInitHi, RegState::Kill);
307 
308   // Add wave offset in bytes to private base offset.
309   // See comment in AMDKernelCodeT.h for enable_sgpr_flat_scratch_init.
310   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), FlatScrInitLo)
311     .addReg(FlatScrInitLo)
312     .addReg(ScratchWaveOffsetReg);
313 
314   // Convert offset to 256-byte units.
315   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_LSHR_B32), AMDGPU::FLAT_SCR_HI)
316     .addReg(FlatScrInitLo, RegState::Kill)
317     .addImm(8);
318 }
319 
320 // Note SGPRSpill stack IDs should only be used for SGPR spilling to VGPRs, not
321 // memory. They should have been removed by now.
322 static bool allStackObjectsAreDead(const MachineFrameInfo &MFI) {
323   for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
324        I != E; ++I) {
325     if (!MFI.isDeadObjectIndex(I))
326       return false;
327   }
328 
329   return true;
330 }
331 
332 // Shift down registers reserved for the scratch RSRC.
333 Register SIFrameLowering::getEntryFunctionReservedScratchRsrcReg(
334     MachineFunction &MF) const {
335 
336   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
337   const SIInstrInfo *TII = ST.getInstrInfo();
338   const SIRegisterInfo *TRI = &TII->getRegisterInfo();
339   MachineRegisterInfo &MRI = MF.getRegInfo();
340   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
341 
342   assert(MFI->isEntryFunction());
343 
344   Register ScratchRsrcReg = MFI->getScratchRSrcReg();
345 
346   if (!ScratchRsrcReg || (!MRI.isPhysRegUsed(ScratchRsrcReg) &&
347                           allStackObjectsAreDead(MF.getFrameInfo())))
348     return Register();
349 
350   if (ST.hasSGPRInitBug() ||
351       ScratchRsrcReg != TRI->reservedPrivateSegmentBufferReg(MF))
352     return ScratchRsrcReg;
353 
354   // We reserved the last registers for this. Shift it down to the end of those
355   // which were actually used.
356   //
357   // FIXME: It might be safer to use a pseudoregister before replacement.
358 
359   // FIXME: We should be able to eliminate unused input registers. We only
360   // cannot do this for the resources required for scratch access. For now we
361   // skip over user SGPRs and may leave unused holes.
362 
363   unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 3) / 4;
364   ArrayRef<MCPhysReg> AllSGPR128s = TRI->getAllSGPR128(MF);
365   AllSGPR128s = AllSGPR128s.slice(std::min(static_cast<unsigned>(AllSGPR128s.size()), NumPreloaded));
366 
367   // Skip the last N reserved elements because they should have already been
368   // reserved for VCC etc.
369   Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
370   for (MCPhysReg Reg : AllSGPR128s) {
371     // Pick the first unallocated one. Make sure we don't clobber the other
372     // reserved input we needed. Also for PAL, make sure we don't clobber
373     // the GIT pointer passed in SGPR0 or SGPR8.
374     if (!MRI.isPhysRegUsed(Reg) && MRI.isAllocatable(Reg) &&
375         !TRI->isSubRegisterEq(Reg, GITPtrLoReg)) {
376       MRI.replaceRegWith(ScratchRsrcReg, Reg);
377       MFI->setScratchRSrcReg(Reg);
378       return Reg;
379     }
380   }
381 
382   return ScratchRsrcReg;
383 }
384 
385 static unsigned getScratchScaleFactor(const GCNSubtarget &ST) {
386   return ST.enableFlatScratch() ? 1 : ST.getWavefrontSize();
387 }
388 
389 void SIFrameLowering::emitEntryFunctionPrologue(MachineFunction &MF,
390                                                 MachineBasicBlock &MBB) const {
391   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
392 
393   // FIXME: If we only have SGPR spills, we won't actually be using scratch
394   // memory since these spill to VGPRs. We should be cleaning up these unused
395   // SGPR spill frame indices somewhere.
396 
397   // FIXME: We still have implicit uses on SGPR spill instructions in case they
398   // need to spill to vector memory. It's likely that will not happen, but at
399   // this point it appears we need the setup. This part of the prolog should be
400   // emitted after frame indices are eliminated.
401 
402   // FIXME: Remove all of the isPhysRegUsed checks
403 
404   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
405   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
406   const SIInstrInfo *TII = ST.getInstrInfo();
407   const SIRegisterInfo *TRI = &TII->getRegisterInfo();
408   MachineRegisterInfo &MRI = MF.getRegInfo();
409   const Function &F = MF.getFunction();
410 
411   assert(MFI->isEntryFunction());
412 
413   Register PreloadedScratchWaveOffsetReg = MFI->getPreloadedReg(
414       AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
415   // FIXME: Hack to not crash in situations which emitted an error.
416   if (!PreloadedScratchWaveOffsetReg)
417     return;
418 
419   // We need to do the replacement of the private segment buffer register even
420   // if there are no stack objects. There could be stores to undef or a
421   // constant without an associated object.
422   //
423   // This will return `Register()` in cases where there are no actual
424   // uses of the SRSRC.
425   Register ScratchRsrcReg;
426   if (!ST.enableFlatScratch())
427     ScratchRsrcReg = getEntryFunctionReservedScratchRsrcReg(MF);
428 
429   // Make the selected register live throughout the function.
430   if (ScratchRsrcReg) {
431     for (MachineBasicBlock &OtherBB : MF) {
432       if (&OtherBB != &MBB) {
433         OtherBB.addLiveIn(ScratchRsrcReg);
434       }
435     }
436   }
437 
438   // Now that we have fixed the reserved SRSRC we need to locate the
439   // (potentially) preloaded SRSRC.
440   Register PreloadedScratchRsrcReg;
441   if (ST.isAmdHsaOrMesa(F)) {
442     PreloadedScratchRsrcReg =
443         MFI->getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
444     if (ScratchRsrcReg && PreloadedScratchRsrcReg) {
445       // We added live-ins during argument lowering, but since they were not
446       // used they were deleted. We're adding the uses now, so add them back.
447       MRI.addLiveIn(PreloadedScratchRsrcReg);
448       MBB.addLiveIn(PreloadedScratchRsrcReg);
449     }
450   }
451 
452   // Debug location must be unknown since the first debug location is used to
453   // determine the end of the prologue.
454   DebugLoc DL;
455   MachineBasicBlock::iterator I = MBB.begin();
456 
457   // We found the SRSRC first because it needs four registers and has an
458   // alignment requirement. If the SRSRC that we found is clobbering with
459   // the scratch wave offset, which may be in a fixed SGPR or a free SGPR
460   // chosen by SITargetLowering::allocateSystemSGPRs, COPY the scratch
461   // wave offset to a free SGPR.
462   Register ScratchWaveOffsetReg;
463   if (TRI->isSubRegisterEq(ScratchRsrcReg, PreloadedScratchWaveOffsetReg)) {
464     ArrayRef<MCPhysReg> AllSGPRs = TRI->getAllSGPR32(MF);
465     unsigned NumPreloaded = MFI->getNumPreloadedSGPRs();
466     AllSGPRs = AllSGPRs.slice(
467         std::min(static_cast<unsigned>(AllSGPRs.size()), NumPreloaded));
468     Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
469     for (MCPhysReg Reg : AllSGPRs) {
470       if (!MRI.isPhysRegUsed(Reg) && MRI.isAllocatable(Reg) &&
471           !TRI->isSubRegisterEq(ScratchRsrcReg, Reg) && GITPtrLoReg != Reg) {
472         ScratchWaveOffsetReg = Reg;
473         BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchWaveOffsetReg)
474             .addReg(PreloadedScratchWaveOffsetReg, RegState::Kill);
475         break;
476       }
477     }
478   } else {
479     ScratchWaveOffsetReg = PreloadedScratchWaveOffsetReg;
480   }
481   assert(ScratchWaveOffsetReg);
482 
483   if (requiresStackPointerReference(MF)) {
484     Register SPReg = MFI->getStackPtrOffsetReg();
485     assert(SPReg != AMDGPU::SP_REG);
486     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), SPReg)
487         .addImm(MF.getFrameInfo().getStackSize() * getScratchScaleFactor(ST));
488   }
489 
490   if (hasFP(MF)) {
491     Register FPReg = MFI->getFrameOffsetReg();
492     assert(FPReg != AMDGPU::FP_REG);
493     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), FPReg).addImm(0);
494   }
495 
496   if ((MFI->hasFlatScratchInit() || ScratchRsrcReg) &&
497       !ST.flatScratchIsArchitected()) {
498     MRI.addLiveIn(PreloadedScratchWaveOffsetReg);
499     MBB.addLiveIn(PreloadedScratchWaveOffsetReg);
500   }
501 
502   if (MFI->hasFlatScratchInit()) {
503     emitEntryFunctionFlatScratchInit(MF, MBB, I, DL, ScratchWaveOffsetReg);
504   }
505 
506   if (ScratchRsrcReg) {
507     emitEntryFunctionScratchRsrcRegSetup(MF, MBB, I, DL,
508                                          PreloadedScratchRsrcReg,
509                                          ScratchRsrcReg, ScratchWaveOffsetReg);
510   }
511 }
512 
513 // Emit scratch RSRC setup code, assuming `ScratchRsrcReg != AMDGPU::NoReg`
514 void SIFrameLowering::emitEntryFunctionScratchRsrcRegSetup(
515     MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
516     const DebugLoc &DL, Register PreloadedScratchRsrcReg,
517     Register ScratchRsrcReg, Register ScratchWaveOffsetReg) const {
518 
519   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
520   const SIInstrInfo *TII = ST.getInstrInfo();
521   const SIRegisterInfo *TRI = &TII->getRegisterInfo();
522   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
523   const Function &Fn = MF.getFunction();
524 
525   if (ST.isAmdPalOS()) {
526     // The pointer to the GIT is formed from the offset passed in and either
527     // the amdgpu-git-ptr-high function attribute or the top part of the PC
528     Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
529     Register Rsrc03 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
530 
531     buildGitPtr(MBB, I, DL, TII, Rsrc01);
532 
533     // We now have the GIT ptr - now get the scratch descriptor from the entry
534     // at offset 0 (or offset 16 for a compute shader).
535     MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
536     const MCInstrDesc &LoadDwordX4 = TII->get(AMDGPU::S_LOAD_DWORDX4_IMM);
537     auto MMO = MF.getMachineMemOperand(PtrInfo,
538                                        MachineMemOperand::MOLoad |
539                                            MachineMemOperand::MOInvariant |
540                                            MachineMemOperand::MODereferenceable,
541                                        16, Align(4));
542     unsigned Offset = Fn.getCallingConv() == CallingConv::AMDGPU_CS ? 16 : 0;
543     const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
544     unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
545     BuildMI(MBB, I, DL, LoadDwordX4, ScratchRsrcReg)
546       .addReg(Rsrc01)
547       .addImm(EncodedOffset) // offset
548       .addImm(0) // cpol
549       .addReg(ScratchRsrcReg, RegState::ImplicitDefine)
550       .addMemOperand(MMO);
551 
552     // The driver will always set the SRD for wave 64 (bits 118:117 of
553     // descriptor / bits 22:21 of third sub-reg will be 0b11)
554     // If the shader is actually wave32 we have to modify the const_index_stride
555     // field of the descriptor 3rd sub-reg (bits 22:21) to 0b10 (stride=32). The
556     // reason the driver does this is that there can be cases where it presents
557     // 2 shaders with different wave size (e.g. VsFs).
558     // TODO: convert to using SCRATCH instructions or multiple SRD buffers
559     if (ST.isWave32()) {
560       const MCInstrDesc &SBitsetB32 = TII->get(AMDGPU::S_BITSET0_B32);
561       BuildMI(MBB, I, DL, SBitsetB32, Rsrc03)
562           .addImm(21)
563           .addReg(Rsrc03);
564     }
565   } else if (ST.isMesaGfxShader(Fn) || !PreloadedScratchRsrcReg) {
566     assert(!ST.isAmdHsaOrMesa(Fn));
567     const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
568 
569     Register Rsrc2 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub2);
570     Register Rsrc3 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
571 
572     // Use relocations to get the pointer, and setup the other bits manually.
573     uint64_t Rsrc23 = TII->getScratchRsrcWords23();
574 
575     if (MFI->hasImplicitBufferPtr()) {
576       Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
577 
578       if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
579         const MCInstrDesc &Mov64 = TII->get(AMDGPU::S_MOV_B64);
580 
581         BuildMI(MBB, I, DL, Mov64, Rsrc01)
582           .addReg(MFI->getImplicitBufferPtrUserSGPR())
583           .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
584       } else {
585         const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
586 
587         MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
588         auto MMO = MF.getMachineMemOperand(
589             PtrInfo,
590             MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
591                 MachineMemOperand::MODereferenceable,
592             8, Align(4));
593         BuildMI(MBB, I, DL, LoadDwordX2, Rsrc01)
594           .addReg(MFI->getImplicitBufferPtrUserSGPR())
595           .addImm(0) // offset
596           .addImm(0) // cpol
597           .addMemOperand(MMO)
598           .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
599 
600         MF.getRegInfo().addLiveIn(MFI->getImplicitBufferPtrUserSGPR());
601         MBB.addLiveIn(MFI->getImplicitBufferPtrUserSGPR());
602       }
603     } else {
604       Register Rsrc0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
605       Register Rsrc1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
606 
607       BuildMI(MBB, I, DL, SMovB32, Rsrc0)
608         .addExternalSymbol("SCRATCH_RSRC_DWORD0")
609         .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
610 
611       BuildMI(MBB, I, DL, SMovB32, Rsrc1)
612         .addExternalSymbol("SCRATCH_RSRC_DWORD1")
613         .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
614 
615     }
616 
617     BuildMI(MBB, I, DL, SMovB32, Rsrc2)
618       .addImm(Rsrc23 & 0xffffffff)
619       .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
620 
621     BuildMI(MBB, I, DL, SMovB32, Rsrc3)
622       .addImm(Rsrc23 >> 32)
623       .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
624   } else if (ST.isAmdHsaOrMesa(Fn)) {
625     assert(PreloadedScratchRsrcReg);
626 
627     if (ScratchRsrcReg != PreloadedScratchRsrcReg) {
628       BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchRsrcReg)
629           .addReg(PreloadedScratchRsrcReg, RegState::Kill);
630     }
631   }
632 
633   // Add the scratch wave offset into the scratch RSRC.
634   //
635   // We only want to update the first 48 bits, which is the base address
636   // pointer, without touching the adjacent 16 bits of flags. We know this add
637   // cannot carry-out from bit 47, otherwise the scratch allocation would be
638   // impossible to fit in the 48-bit global address space.
639   //
640   // TODO: Evaluate if it is better to just construct an SRD using the flat
641   // scratch init and some constants rather than update the one we are passed.
642   Register ScratchRsrcSub0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
643   Register ScratchRsrcSub1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
644 
645   // We cannot Kill ScratchWaveOffsetReg here because we allow it to be used in
646   // the kernel body via inreg arguments.
647   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), ScratchRsrcSub0)
648       .addReg(ScratchRsrcSub0)
649       .addReg(ScratchWaveOffsetReg)
650       .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
651   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32), ScratchRsrcSub1)
652       .addReg(ScratchRsrcSub1)
653       .addImm(0)
654       .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
655 }
656 
657 bool SIFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
658   switch (ID) {
659   case TargetStackID::Default:
660   case TargetStackID::NoAlloc:
661   case TargetStackID::SGPRSpill:
662     return true;
663   case TargetStackID::ScalableVector:
664     return false;
665   default:
666     break;
667   }
668   llvm_unreachable("Invalid TargetStackID::Value");
669 }
670 
671 static void initLiveRegs(LivePhysRegs &LiveRegs, const SIRegisterInfo &TRI,
672                          const SIMachineFunctionInfo *FuncInfo,
673                          MachineFunction &MF, MachineBasicBlock &MBB,
674                          MachineBasicBlock::iterator MBBI, bool IsProlog) {
675   if (LiveRegs.empty()) {
676     LiveRegs.init(TRI);
677     if (IsProlog) {
678       LiveRegs.addLiveIns(MBB);
679     } else {
680       // In epilog.
681       LiveRegs.addLiveOuts(MBB);
682       LiveRegs.stepBackward(*MBBI);
683     }
684   }
685 }
686 
687 // Activate all lanes, returns saved exec.
688 static Register buildScratchExecCopy(LivePhysRegs &LiveRegs,
689                                      MachineFunction &MF,
690                                      MachineBasicBlock &MBB,
691                                      MachineBasicBlock::iterator MBBI,
692                                      bool IsProlog) {
693   Register ScratchExecCopy;
694   MachineRegisterInfo &MRI = MF.getRegInfo();
695   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
696   const SIInstrInfo *TII = ST.getInstrInfo();
697   const SIRegisterInfo &TRI = TII->getRegisterInfo();
698   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
699   DebugLoc DL;
700 
701   initLiveRegs(LiveRegs, TRI, FuncInfo, MF, MBB, MBBI, IsProlog);
702 
703   ScratchExecCopy = findScratchNonCalleeSaveRegister(
704       MRI, LiveRegs, *TRI.getWaveMaskRegClass());
705   if (!ScratchExecCopy)
706     report_fatal_error("failed to find free scratch register");
707 
708   LiveRegs.addReg(ScratchExecCopy);
709 
710   const unsigned OrSaveExec =
711       ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64;
712   BuildMI(MBB, MBBI, DL, TII->get(OrSaveExec), ScratchExecCopy).addImm(-1);
713 
714   return ScratchExecCopy;
715 }
716 
717 // A StackID of SGPRSpill implies that this is a spill from SGPR to VGPR.
718 // Otherwise we are spilling to memory.
719 static bool spilledToMemory(const MachineFunction &MF, int SaveIndex) {
720   const MachineFrameInfo &MFI = MF.getFrameInfo();
721   return MFI.getStackID(SaveIndex) != TargetStackID::SGPRSpill;
722 }
723 
724 void SIFrameLowering::emitPrologue(MachineFunction &MF,
725                                    MachineBasicBlock &MBB) const {
726   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
727   if (FuncInfo->isEntryFunction()) {
728     emitEntryFunctionPrologue(MF, MBB);
729     return;
730   }
731 
732   const MachineFrameInfo &MFI = MF.getFrameInfo();
733   MachineRegisterInfo &MRI = MF.getRegInfo();
734   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
735   const SIInstrInfo *TII = ST.getInstrInfo();
736   const SIRegisterInfo &TRI = TII->getRegisterInfo();
737 
738   Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
739   Register FramePtrReg = FuncInfo->getFrameOffsetReg();
740   Register BasePtrReg =
741       TRI.hasBasePointer(MF) ? TRI.getBaseRegister() : Register();
742   LivePhysRegs LiveRegs;
743 
744   MachineBasicBlock::iterator MBBI = MBB.begin();
745   DebugLoc DL;
746 
747   bool HasFP = false;
748   bool HasBP = false;
749   uint32_t NumBytes = MFI.getStackSize();
750   uint32_t RoundedSize = NumBytes;
751   // To avoid clobbering VGPRs in lanes that weren't active on function entry,
752   // turn on all lanes before doing the spill to memory.
753   Register ScratchExecCopy;
754 
755   Optional<int> FPSaveIndex = FuncInfo->FramePointerSaveIndex;
756   Optional<int> BPSaveIndex = FuncInfo->BasePointerSaveIndex;
757 
758   // VGPRs used for SGPR->VGPR spills
759   for (const SIMachineFunctionInfo::SGPRSpillVGPR &Reg :
760        FuncInfo->getSGPRSpillVGPRs()) {
761     if (!Reg.FI)
762       continue;
763 
764     if (!ScratchExecCopy)
765       ScratchExecCopy = buildScratchExecCopy(LiveRegs, MF, MBB, MBBI,
766                                              /*IsProlog*/ true);
767 
768     buildPrologSpill(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, Reg.VGPR,
769                      *Reg.FI);
770   }
771 
772   // VGPRs used for Whole Wave Mode
773   for (const auto &Reg : FuncInfo->WWMReservedRegs) {
774     auto VGPR = Reg.first;
775     auto FI = Reg.second;
776     if (!FI)
777       continue;
778 
779     if (!ScratchExecCopy)
780       ScratchExecCopy =
781           buildScratchExecCopy(LiveRegs, MF, MBB, MBBI, /*IsProlog*/ true);
782 
783     buildPrologSpill(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, VGPR, *FI);
784   }
785 
786   if (ScratchExecCopy) {
787     // FIXME: Split block and make terminator.
788     unsigned ExecMov = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
789     MCRegister Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
790     BuildMI(MBB, MBBI, DL, TII->get(ExecMov), Exec)
791         .addReg(ScratchExecCopy, RegState::Kill);
792     LiveRegs.addReg(ScratchExecCopy);
793   }
794 
795   if (FPSaveIndex && spilledToMemory(MF, *FPSaveIndex)) {
796     const int FramePtrFI = *FPSaveIndex;
797     assert(!MFI.isDeadObjectIndex(FramePtrFI));
798 
799     initLiveRegs(LiveRegs, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ true);
800 
801     MCPhysReg TmpVGPR = findScratchNonCalleeSaveRegister(
802         MRI, LiveRegs, AMDGPU::VGPR_32RegClass);
803     if (!TmpVGPR)
804       report_fatal_error("failed to find free scratch register");
805 
806     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_MOV_B32_e32), TmpVGPR)
807         .addReg(FramePtrReg);
808 
809     buildPrologSpill(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, TmpVGPR,
810                      FramePtrFI);
811   }
812 
813   if (BPSaveIndex && spilledToMemory(MF, *BPSaveIndex)) {
814     const int BasePtrFI = *BPSaveIndex;
815     assert(!MFI.isDeadObjectIndex(BasePtrFI));
816 
817     initLiveRegs(LiveRegs, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ true);
818 
819     MCPhysReg TmpVGPR = findScratchNonCalleeSaveRegister(
820         MRI, LiveRegs, AMDGPU::VGPR_32RegClass);
821     if (!TmpVGPR)
822       report_fatal_error("failed to find free scratch register");
823 
824     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_MOV_B32_e32), TmpVGPR)
825         .addReg(BasePtrReg);
826 
827     buildPrologSpill(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, TmpVGPR,
828                      BasePtrFI);
829   }
830 
831   // In this case, spill the FP to a reserved VGPR.
832   if (FPSaveIndex && !spilledToMemory(MF, *FPSaveIndex)) {
833     const int FramePtrFI = *FPSaveIndex;
834     assert(!MFI.isDeadObjectIndex(FramePtrFI));
835 
836     assert(MFI.getStackID(FramePtrFI) == TargetStackID::SGPRSpill);
837     ArrayRef<SIMachineFunctionInfo::SpilledReg> Spill =
838         FuncInfo->getSGPRToVGPRSpills(FramePtrFI);
839     assert(Spill.size() == 1);
840 
841     // Save FP before setting it up.
842     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_WRITELANE_B32), Spill[0].VGPR)
843         .addReg(FramePtrReg)
844         .addImm(Spill[0].Lane)
845         .addReg(Spill[0].VGPR, RegState::Undef);
846   }
847 
848   // In this case, spill the BP to a reserved VGPR.
849   if (BPSaveIndex && !spilledToMemory(MF, *BPSaveIndex)) {
850     const int BasePtrFI = *BPSaveIndex;
851     assert(!MFI.isDeadObjectIndex(BasePtrFI));
852 
853     assert(MFI.getStackID(BasePtrFI) == TargetStackID::SGPRSpill);
854     ArrayRef<SIMachineFunctionInfo::SpilledReg> Spill =
855         FuncInfo->getSGPRToVGPRSpills(BasePtrFI);
856     assert(Spill.size() == 1);
857 
858     // Save BP before setting it up.
859     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_WRITELANE_B32), Spill[0].VGPR)
860         .addReg(BasePtrReg)
861         .addImm(Spill[0].Lane)
862         .addReg(Spill[0].VGPR, RegState::Undef);
863   }
864 
865   // Emit the copy if we need an FP, and are using a free SGPR to save it.
866   if (FuncInfo->SGPRForFPSaveRestoreCopy) {
867     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY),
868             FuncInfo->SGPRForFPSaveRestoreCopy)
869         .addReg(FramePtrReg)
870         .setMIFlag(MachineInstr::FrameSetup);
871   }
872 
873   // Emit the copy if we need a BP, and are using a free SGPR to save it.
874   if (FuncInfo->SGPRForBPSaveRestoreCopy) {
875     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY),
876             FuncInfo->SGPRForBPSaveRestoreCopy)
877         .addReg(BasePtrReg)
878         .setMIFlag(MachineInstr::FrameSetup);
879   }
880 
881   // If a copy has been emitted for FP and/or BP, Make the SGPRs
882   // used in the copy instructions live throughout the function.
883   SmallVector<MCPhysReg, 2> TempSGPRs;
884   if (FuncInfo->SGPRForFPSaveRestoreCopy)
885     TempSGPRs.push_back(FuncInfo->SGPRForFPSaveRestoreCopy);
886 
887   if (FuncInfo->SGPRForBPSaveRestoreCopy)
888     TempSGPRs.push_back(FuncInfo->SGPRForBPSaveRestoreCopy);
889 
890   if (!TempSGPRs.empty()) {
891     for (MachineBasicBlock &MBB : MF) {
892       for (MCPhysReg Reg : TempSGPRs)
893         MBB.addLiveIn(Reg);
894 
895       MBB.sortUniqueLiveIns();
896     }
897     if (!LiveRegs.empty()) {
898       LiveRegs.addReg(FuncInfo->SGPRForFPSaveRestoreCopy);
899       LiveRegs.addReg(FuncInfo->SGPRForBPSaveRestoreCopy);
900     }
901   }
902 
903   if (TRI.hasStackRealignment(MF)) {
904     HasFP = true;
905     const unsigned Alignment = MFI.getMaxAlign().value();
906 
907     RoundedSize += Alignment;
908     if (LiveRegs.empty()) {
909       LiveRegs.init(TRI);
910       LiveRegs.addLiveIns(MBB);
911     }
912 
913     // s_add_u32 s33, s32, NumBytes
914     // s_and_b32 s33, s33, 0b111...0000
915     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_U32), FramePtrReg)
916         .addReg(StackPtrReg)
917         .addImm((Alignment - 1) * getScratchScaleFactor(ST))
918         .setMIFlag(MachineInstr::FrameSetup);
919     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_AND_B32), FramePtrReg)
920         .addReg(FramePtrReg, RegState::Kill)
921         .addImm(-Alignment * getScratchScaleFactor(ST))
922         .setMIFlag(MachineInstr::FrameSetup);
923     FuncInfo->setIsStackRealigned(true);
924   } else if ((HasFP = hasFP(MF))) {
925     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
926         .addReg(StackPtrReg)
927         .setMIFlag(MachineInstr::FrameSetup);
928   }
929 
930   // If we need a base pointer, set it up here. It's whatever the value of
931   // the stack pointer is at this point. Any variable size objects will be
932   // allocated after this, so we can still use the base pointer to reference
933   // the incoming arguments.
934   if ((HasBP = TRI.hasBasePointer(MF))) {
935     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), BasePtrReg)
936         .addReg(StackPtrReg)
937         .setMIFlag(MachineInstr::FrameSetup);
938   }
939 
940   if (HasFP && RoundedSize != 0) {
941     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_U32), StackPtrReg)
942         .addReg(StackPtrReg)
943         .addImm(RoundedSize * getScratchScaleFactor(ST))
944         .setMIFlag(MachineInstr::FrameSetup);
945   }
946 
947   assert((!HasFP || (FuncInfo->SGPRForFPSaveRestoreCopy ||
948                      FuncInfo->FramePointerSaveIndex)) &&
949          "Needed to save FP but didn't save it anywhere");
950 
951   assert((HasFP || (!FuncInfo->SGPRForFPSaveRestoreCopy &&
952                     !FuncInfo->FramePointerSaveIndex)) &&
953          "Saved FP but didn't need it");
954 
955   assert((!HasBP || (FuncInfo->SGPRForBPSaveRestoreCopy ||
956                      FuncInfo->BasePointerSaveIndex)) &&
957          "Needed to save BP but didn't save it anywhere");
958 
959   assert((HasBP || (!FuncInfo->SGPRForBPSaveRestoreCopy &&
960                     !FuncInfo->BasePointerSaveIndex)) &&
961          "Saved BP but didn't need it");
962 }
963 
964 void SIFrameLowering::emitEpilogue(MachineFunction &MF,
965                                    MachineBasicBlock &MBB) const {
966   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
967   if (FuncInfo->isEntryFunction())
968     return;
969 
970   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
971   const SIInstrInfo *TII = ST.getInstrInfo();
972   MachineRegisterInfo &MRI = MF.getRegInfo();
973   const SIRegisterInfo &TRI = TII->getRegisterInfo();
974   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
975   LivePhysRegs LiveRegs;
976   DebugLoc DL;
977 
978   const MachineFrameInfo &MFI = MF.getFrameInfo();
979   uint32_t NumBytes = MFI.getStackSize();
980   uint32_t RoundedSize = FuncInfo->isStackRealigned()
981                              ? NumBytes + MFI.getMaxAlign().value()
982                              : NumBytes;
983   const Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
984   const Register FramePtrReg = FuncInfo->getFrameOffsetReg();
985   const Register BasePtrReg =
986       TRI.hasBasePointer(MF) ? TRI.getBaseRegister() : Register();
987 
988   Optional<int> FPSaveIndex = FuncInfo->FramePointerSaveIndex;
989   Optional<int> BPSaveIndex = FuncInfo->BasePointerSaveIndex;
990 
991   if (RoundedSize != 0 && hasFP(MF)) {
992     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_SUB_U32), StackPtrReg)
993       .addReg(StackPtrReg)
994       .addImm(RoundedSize * getScratchScaleFactor(ST))
995       .setMIFlag(MachineInstr::FrameDestroy);
996   }
997 
998   if (FuncInfo->SGPRForFPSaveRestoreCopy) {
999     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
1000         .addReg(FuncInfo->SGPRForFPSaveRestoreCopy)
1001         .setMIFlag(MachineInstr::FrameDestroy);
1002   }
1003 
1004   if (FuncInfo->SGPRForBPSaveRestoreCopy) {
1005     BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), BasePtrReg)
1006         .addReg(FuncInfo->SGPRForBPSaveRestoreCopy)
1007         .setMIFlag(MachineInstr::FrameDestroy);
1008   }
1009 
1010   if (FPSaveIndex) {
1011     const int FramePtrFI = *FPSaveIndex;
1012     assert(!MFI.isDeadObjectIndex(FramePtrFI));
1013     if (spilledToMemory(MF, FramePtrFI)) {
1014       initLiveRegs(LiveRegs, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ false);
1015 
1016       MCPhysReg TmpVGPR = findScratchNonCalleeSaveRegister(
1017           MRI, LiveRegs, AMDGPU::VGPR_32RegClass);
1018       if (!TmpVGPR)
1019         report_fatal_error("failed to find free scratch register");
1020       buildEpilogRestore(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, TmpVGPR,
1021                          FramePtrFI);
1022       BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), FramePtrReg)
1023           .addReg(TmpVGPR, RegState::Kill);
1024     } else {
1025       // Reload from VGPR spill.
1026       assert(MFI.getStackID(FramePtrFI) == TargetStackID::SGPRSpill);
1027       ArrayRef<SIMachineFunctionInfo::SpilledReg> Spill =
1028           FuncInfo->getSGPRToVGPRSpills(FramePtrFI);
1029       assert(Spill.size() == 1);
1030       BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_READLANE_B32), FramePtrReg)
1031           .addReg(Spill[0].VGPR)
1032           .addImm(Spill[0].Lane);
1033     }
1034   }
1035 
1036   if (BPSaveIndex) {
1037     const int BasePtrFI = *BPSaveIndex;
1038     assert(!MFI.isDeadObjectIndex(BasePtrFI));
1039     if (spilledToMemory(MF, BasePtrFI)) {
1040       initLiveRegs(LiveRegs, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ false);
1041 
1042       MCPhysReg TmpVGPR = findScratchNonCalleeSaveRegister(
1043           MRI, LiveRegs, AMDGPU::VGPR_32RegClass);
1044       if (!TmpVGPR)
1045         report_fatal_error("failed to find free scratch register");
1046       buildEpilogRestore(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, TmpVGPR,
1047                          BasePtrFI);
1048       BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), BasePtrReg)
1049           .addReg(TmpVGPR, RegState::Kill);
1050     } else {
1051       // Reload from VGPR spill.
1052       assert(MFI.getStackID(BasePtrFI) == TargetStackID::SGPRSpill);
1053       ArrayRef<SIMachineFunctionInfo::SpilledReg> Spill =
1054           FuncInfo->getSGPRToVGPRSpills(BasePtrFI);
1055       assert(Spill.size() == 1);
1056       BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::V_READLANE_B32), BasePtrReg)
1057           .addReg(Spill[0].VGPR)
1058           .addImm(Spill[0].Lane);
1059     }
1060   }
1061 
1062   Register ScratchExecCopy;
1063   for (const SIMachineFunctionInfo::SGPRSpillVGPR &Reg :
1064        FuncInfo->getSGPRSpillVGPRs()) {
1065     if (!Reg.FI)
1066       continue;
1067 
1068     if (!ScratchExecCopy)
1069       ScratchExecCopy =
1070           buildScratchExecCopy(LiveRegs, MF, MBB, MBBI, /*IsProlog*/ false);
1071 
1072     buildEpilogRestore(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, Reg.VGPR,
1073                        *Reg.FI);
1074   }
1075 
1076   for (const auto &Reg : FuncInfo->WWMReservedRegs) {
1077     auto VGPR = Reg.first;
1078     auto FI = Reg.second;
1079     if (!FI)
1080       continue;
1081 
1082     if (!ScratchExecCopy)
1083       ScratchExecCopy =
1084           buildScratchExecCopy(LiveRegs, MF, MBB, MBBI, /*IsProlog*/ false);
1085 
1086     buildEpilogRestore(ST, TRI, *FuncInfo, LiveRegs, MF, MBB, MBBI, VGPR, *FI);
1087   }
1088 
1089   if (ScratchExecCopy) {
1090     // FIXME: Split block and make terminator.
1091     unsigned ExecMov = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1092     MCRegister Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1093     BuildMI(MBB, MBBI, DL, TII->get(ExecMov), Exec)
1094         .addReg(ScratchExecCopy, RegState::Kill);
1095   }
1096 }
1097 
1098 #ifndef NDEBUG
1099 static bool allSGPRSpillsAreDead(const MachineFunction &MF) {
1100   const MachineFrameInfo &MFI = MF.getFrameInfo();
1101   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1102   for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
1103        I != E; ++I) {
1104     if (!MFI.isDeadObjectIndex(I) &&
1105         MFI.getStackID(I) == TargetStackID::SGPRSpill &&
1106         (I != FuncInfo->FramePointerSaveIndex &&
1107          I != FuncInfo->BasePointerSaveIndex)) {
1108       return false;
1109     }
1110   }
1111 
1112   return true;
1113 }
1114 #endif
1115 
1116 StackOffset SIFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1117                                                     int FI,
1118                                                     Register &FrameReg) const {
1119   const SIRegisterInfo *RI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1120 
1121   FrameReg = RI->getFrameRegister(MF);
1122   return StackOffset::getFixed(MF.getFrameInfo().getObjectOffset(FI));
1123 }
1124 
1125 void SIFrameLowering::processFunctionBeforeFrameFinalized(
1126   MachineFunction &MF,
1127   RegScavenger *RS) const {
1128   MachineFrameInfo &MFI = MF.getFrameInfo();
1129 
1130   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1131   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1132   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1133 
1134   FuncInfo->removeDeadFrameIndices(MFI);
1135   assert(allSGPRSpillsAreDead(MF) &&
1136          "SGPR spill should have been removed in SILowerSGPRSpills");
1137 
1138   // FIXME: The other checks should be redundant with allStackObjectsAreDead,
1139   // but currently hasNonSpillStackObjects is set only from source
1140   // allocas. Stack temps produced from legalization are not counted currently.
1141   if (!allStackObjectsAreDead(MFI)) {
1142     assert(RS && "RegScavenger required if spilling");
1143 
1144     // Add an emergency spill slot
1145     RS->addScavengingFrameIndex(FuncInfo->getScavengeFI(MFI, *TRI));
1146   }
1147 }
1148 
1149 // Only report VGPRs to generic code.
1150 void SIFrameLowering::determineCalleeSaves(MachineFunction &MF,
1151                                            BitVector &SavedVGPRs,
1152                                            RegScavenger *RS) const {
1153   TargetFrameLowering::determineCalleeSaves(MF, SavedVGPRs, RS);
1154   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1155   if (MFI->isEntryFunction())
1156     return;
1157 
1158   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1159   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1160   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1161 
1162   // Ignore the SGPRs the default implementation found.
1163   SavedVGPRs.clearBitsNotInMask(TRI->getAllVectorRegMask());
1164 
1165   // Do not save AGPRs prior to GFX90A because there was no easy way to do so.
1166   // In gfx908 there was do AGPR loads and stores and thus spilling also
1167   // require a temporary VGPR.
1168   if (!ST.hasGFX90AInsts())
1169     SavedVGPRs.clearBitsInMask(TRI->getAllAGPRRegMask());
1170 
1171   // hasFP only knows about stack objects that already exist. We're now
1172   // determining the stack slots that will be created, so we have to predict
1173   // them. Stack objects force FP usage with calls.
1174   //
1175   // Note a new VGPR CSR may be introduced if one is used for the spill, but we
1176   // don't want to report it here.
1177   //
1178   // FIXME: Is this really hasReservedCallFrame?
1179   const bool WillHaveFP =
1180       FrameInfo.hasCalls() &&
1181       (SavedVGPRs.any() || !allStackObjectsAreDead(FrameInfo));
1182 
1183   // VGPRs used for SGPR spilling need to be specially inserted in the prolog,
1184   // so don't allow the default insertion to handle them.
1185   for (auto SSpill : MFI->getSGPRSpillVGPRs())
1186     SavedVGPRs.reset(SSpill.VGPR);
1187 
1188   LivePhysRegs LiveRegs;
1189   LiveRegs.init(*TRI);
1190 
1191   if (WillHaveFP || hasFP(MF)) {
1192     assert(!MFI->SGPRForFPSaveRestoreCopy && !MFI->FramePointerSaveIndex &&
1193            "Re-reserving spill slot for FP");
1194     getVGPRSpillLaneOrTempRegister(MF, LiveRegs, MFI->SGPRForFPSaveRestoreCopy,
1195                                    MFI->FramePointerSaveIndex, true);
1196   }
1197 
1198   if (TRI->hasBasePointer(MF)) {
1199     if (MFI->SGPRForFPSaveRestoreCopy)
1200       LiveRegs.addReg(MFI->SGPRForFPSaveRestoreCopy);
1201 
1202     assert(!MFI->SGPRForBPSaveRestoreCopy &&
1203            !MFI->BasePointerSaveIndex && "Re-reserving spill slot for BP");
1204     getVGPRSpillLaneOrTempRegister(MF, LiveRegs, MFI->SGPRForBPSaveRestoreCopy,
1205                                    MFI->BasePointerSaveIndex, false);
1206   }
1207 }
1208 
1209 void SIFrameLowering::determineCalleeSavesSGPR(MachineFunction &MF,
1210                                                BitVector &SavedRegs,
1211                                                RegScavenger *RS) const {
1212   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1213   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1214   if (MFI->isEntryFunction())
1215     return;
1216 
1217   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1218   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1219 
1220   // The SP is specifically managed and we don't want extra spills of it.
1221   SavedRegs.reset(MFI->getStackPtrOffsetReg());
1222 
1223   const BitVector AllSavedRegs = SavedRegs;
1224   SavedRegs.clearBitsInMask(TRI->getAllVectorRegMask());
1225 
1226   // If clearing VGPRs changed the mask, we will have some CSR VGPR spills.
1227   const bool HaveAnyCSRVGPR = SavedRegs != AllSavedRegs;
1228 
1229   // We have to anticipate introducing CSR VGPR spills if we don't have any
1230   // stack objects already, since we require an FP if there is a call and stack.
1231   MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1232   const bool WillHaveFP = FrameInfo.hasCalls() && HaveAnyCSRVGPR;
1233 
1234   // FP will be specially managed like SP.
1235   if (WillHaveFP || hasFP(MF))
1236     SavedRegs.reset(MFI->getFrameOffsetReg());
1237 }
1238 
1239 bool SIFrameLowering::assignCalleeSavedSpillSlots(
1240     MachineFunction &MF, const TargetRegisterInfo *TRI,
1241     std::vector<CalleeSavedInfo> &CSI) const {
1242   if (CSI.empty())
1243     return true; // Early exit if no callee saved registers are modified!
1244 
1245   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1246   if (!FuncInfo->SGPRForFPSaveRestoreCopy &&
1247       !FuncInfo->SGPRForBPSaveRestoreCopy)
1248     return false;
1249 
1250   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1251   const SIRegisterInfo *RI = ST.getRegisterInfo();
1252   Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1253   Register BasePtrReg = RI->getBaseRegister();
1254   unsigned NumModifiedRegs = 0;
1255 
1256   if (FuncInfo->SGPRForFPSaveRestoreCopy)
1257     NumModifiedRegs++;
1258   if (FuncInfo->SGPRForBPSaveRestoreCopy)
1259     NumModifiedRegs++;
1260 
1261   for (auto &CS : CSI) {
1262     if (CS.getReg() == FramePtrReg && FuncInfo->SGPRForFPSaveRestoreCopy) {
1263       CS.setDstReg(FuncInfo->SGPRForFPSaveRestoreCopy);
1264       if (--NumModifiedRegs)
1265         break;
1266     } else if (CS.getReg() == BasePtrReg &&
1267                FuncInfo->SGPRForBPSaveRestoreCopy) {
1268       CS.setDstReg(FuncInfo->SGPRForBPSaveRestoreCopy);
1269       if (--NumModifiedRegs)
1270         break;
1271     }
1272   }
1273 
1274   return false;
1275 }
1276 
1277 MachineBasicBlock::iterator SIFrameLowering::eliminateCallFramePseudoInstr(
1278   MachineFunction &MF,
1279   MachineBasicBlock &MBB,
1280   MachineBasicBlock::iterator I) const {
1281   int64_t Amount = I->getOperand(0).getImm();
1282   if (Amount == 0)
1283     return MBB.erase(I);
1284 
1285   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1286   const SIInstrInfo *TII = ST.getInstrInfo();
1287   const DebugLoc &DL = I->getDebugLoc();
1288   unsigned Opc = I->getOpcode();
1289   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
1290   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
1291 
1292   if (!hasReservedCallFrame(MF)) {
1293     Amount = alignTo(Amount, getStackAlign());
1294     assert(isUInt<32>(Amount) && "exceeded stack address space size");
1295     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1296     Register SPReg = MFI->getStackPtrOffsetReg();
1297 
1298     unsigned Op = IsDestroy ? AMDGPU::S_SUB_U32 : AMDGPU::S_ADD_U32;
1299     BuildMI(MBB, I, DL, TII->get(Op), SPReg)
1300       .addReg(SPReg)
1301       .addImm(Amount * getScratchScaleFactor(ST));
1302   } else if (CalleePopAmount != 0) {
1303     llvm_unreachable("is this used?");
1304   }
1305 
1306   return MBB.erase(I);
1307 }
1308 
1309 /// Returns true if the frame will require a reference to the stack pointer.
1310 ///
1311 /// This is the set of conditions common to setting up the stack pointer in a
1312 /// kernel, and for using a frame pointer in a callable function.
1313 ///
1314 /// FIXME: Should also check hasOpaqueSPAdjustment and if any inline asm
1315 /// references SP.
1316 static bool frameTriviallyRequiresSP(const MachineFrameInfo &MFI) {
1317   return MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint();
1318 }
1319 
1320 // The FP for kernels is always known 0, so we never really need to setup an
1321 // explicit register for it. However, DisableFramePointerElim will force us to
1322 // use a register for it.
1323 bool SIFrameLowering::hasFP(const MachineFunction &MF) const {
1324   const MachineFrameInfo &MFI = MF.getFrameInfo();
1325 
1326   // For entry functions we can use an immediate offset in most cases, so the
1327   // presence of calls doesn't imply we need a distinct frame pointer.
1328   if (MFI.hasCalls() &&
1329       !MF.getInfo<SIMachineFunctionInfo>()->isEntryFunction()) {
1330     // All offsets are unsigned, so need to be addressed in the same direction
1331     // as stack growth.
1332 
1333     // FIXME: This function is pretty broken, since it can be called before the
1334     // frame layout is determined or CSR spills are inserted.
1335     return MFI.getStackSize() != 0;
1336   }
1337 
1338   return frameTriviallyRequiresSP(MFI) || MFI.isFrameAddressTaken() ||
1339          MF.getSubtarget<GCNSubtarget>().getRegisterInfo()->hasStackRealignment(
1340              MF) ||
1341          MF.getTarget().Options.DisableFramePointerElim(MF);
1342 }
1343 
1344 // This is essentially a reduced version of hasFP for entry functions. Since the
1345 // stack pointer is known 0 on entry to kernels, we never really need an FP
1346 // register. We may need to initialize the stack pointer depending on the frame
1347 // properties, which logically overlaps many of the cases where an ordinary
1348 // function would require an FP.
1349 bool SIFrameLowering::requiresStackPointerReference(
1350     const MachineFunction &MF) const {
1351   // Callable functions always require a stack pointer reference.
1352   assert(MF.getInfo<SIMachineFunctionInfo>()->isEntryFunction() &&
1353          "only expected to call this for entry points");
1354 
1355   const MachineFrameInfo &MFI = MF.getFrameInfo();
1356 
1357   // Entry points ordinarily don't need to initialize SP. We have to set it up
1358   // for callees if there are any. Also note tail calls are impossible/don't
1359   // make any sense for kernels.
1360   if (MFI.hasCalls())
1361     return true;
1362 
1363   // We still need to initialize the SP if we're doing anything weird that
1364   // references the SP, like variable sized stack objects.
1365   return frameTriviallyRequiresSP(MFI);
1366 }
1367