xref: /freebsd/contrib/llvm-project/llvm/lib/Target/SystemZ/SystemZFrameLowering.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===-- SystemZFrameLowering.cpp - Frame lowering for SystemZ -------------===//
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 "SystemZFrameLowering.h"
10 #include "SystemZCallingConv.h"
11 #include "SystemZInstrBuilder.h"
12 #include "SystemZInstrInfo.h"
13 #include "SystemZMachineFunctionInfo.h"
14 #include "SystemZRegisterInfo.h"
15 #include "SystemZSubtarget.h"
16 #include "llvm/CodeGen/LivePhysRegs.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/RegisterScavenging.h"
20 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/Target/TargetMachine.h"
23 
24 using namespace llvm;
25 
26 namespace {
27 // The ABI-defined register save slots, relative to the CFA (i.e.
28 // incoming stack pointer + SystemZMC::ELFCallFrameSize).
29 static const TargetFrameLowering::SpillSlot ELFSpillOffsetTable[] = {
30   { SystemZ::R2D,  0x10 },
31   { SystemZ::R3D,  0x18 },
32   { SystemZ::R4D,  0x20 },
33   { SystemZ::R5D,  0x28 },
34   { SystemZ::R6D,  0x30 },
35   { SystemZ::R7D,  0x38 },
36   { SystemZ::R8D,  0x40 },
37   { SystemZ::R9D,  0x48 },
38   { SystemZ::R10D, 0x50 },
39   { SystemZ::R11D, 0x58 },
40   { SystemZ::R12D, 0x60 },
41   { SystemZ::R13D, 0x68 },
42   { SystemZ::R14D, 0x70 },
43   { SystemZ::R15D, 0x78 },
44   { SystemZ::F0D,  0x80 },
45   { SystemZ::F2D,  0x88 },
46   { SystemZ::F4D,  0x90 },
47   { SystemZ::F6D,  0x98 }
48 };
49 
50 static const TargetFrameLowering::SpillSlot XPLINKSpillOffsetTable[] = {
51     {SystemZ::R4D, 0x00},  {SystemZ::R5D, 0x08},  {SystemZ::R6D, 0x10},
52     {SystemZ::R7D, 0x18},  {SystemZ::R8D, 0x20},  {SystemZ::R9D, 0x28},
53     {SystemZ::R10D, 0x30}, {SystemZ::R11D, 0x38}, {SystemZ::R12D, 0x40},
54     {SystemZ::R13D, 0x48}, {SystemZ::R14D, 0x50}, {SystemZ::R15D, 0x58}};
55 } // end anonymous namespace
56 
57 SystemZFrameLowering::SystemZFrameLowering(StackDirection D, Align StackAl,
58                                            int LAO, Align TransAl,
59                                            bool StackReal)
60     : TargetFrameLowering(D, StackAl, LAO, TransAl, StackReal) {}
61 
62 std::unique_ptr<SystemZFrameLowering>
63 SystemZFrameLowering::create(const SystemZSubtarget &STI) {
64   if (STI.isTargetXPLINK64())
65     return std::make_unique<SystemZXPLINKFrameLowering>();
66   return std::make_unique<SystemZELFFrameLowering>();
67 }
68 
69 MachineBasicBlock::iterator SystemZFrameLowering::eliminateCallFramePseudoInstr(
70     MachineFunction &MF, MachineBasicBlock &MBB,
71     MachineBasicBlock::iterator MI) const {
72   switch (MI->getOpcode()) {
73   case SystemZ::ADJCALLSTACKDOWN:
74   case SystemZ::ADJCALLSTACKUP:
75     assert(hasReservedCallFrame(MF) &&
76            "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
77     return MBB.erase(MI);
78     break;
79 
80   default:
81     llvm_unreachable("Unexpected call frame instruction");
82   }
83 }
84 
85 namespace {
86 struct SZFrameSortingObj {
87   bool IsValid = false;     // True if we care about this Object.
88   uint32_t ObjectIndex = 0; // Index of Object into MFI list.
89   uint64_t ObjectSize = 0;  // Size of Object in bytes.
90   uint32_t D12Count = 0;    // 12-bit displacement only.
91   uint32_t DPairCount = 0;  // 12 or 20 bit displacement.
92 };
93 typedef std::vector<SZFrameSortingObj> SZFrameObjVec;
94 } // namespace
95 
96 // TODO: Move to base class.
97 void SystemZELFFrameLowering::orderFrameObjects(
98     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
99   const MachineFrameInfo &MFI = MF.getFrameInfo();
100   auto *TII = MF.getSubtarget<SystemZSubtarget>().getInstrInfo();
101 
102   // Make a vector of sorting objects to track all MFI objects and mark those
103   // to be sorted as valid.
104   if (ObjectsToAllocate.size() <= 1)
105     return;
106   SZFrameObjVec SortingObjects(MFI.getObjectIndexEnd());
107   for (auto &Obj : ObjectsToAllocate) {
108     SortingObjects[Obj].IsValid = true;
109     SortingObjects[Obj].ObjectIndex = Obj;
110     SortingObjects[Obj].ObjectSize = MFI.getObjectSize(Obj);
111   }
112 
113   // Examine uses for each object and record short (12-bit) and "pair"
114   // displacement types.
115   for (auto &MBB : MF)
116     for (auto &MI : MBB) {
117       if (MI.isDebugInstr())
118         continue;
119       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
120         const MachineOperand &MO = MI.getOperand(I);
121         if (!MO.isFI())
122           continue;
123         int Index = MO.getIndex();
124         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
125             SortingObjects[Index].IsValid) {
126           if (TII->hasDisplacementPairInsn(MI.getOpcode()))
127             SortingObjects[Index].DPairCount++;
128           else if (!(MI.getDesc().TSFlags & SystemZII::Has20BitOffset))
129             SortingObjects[Index].D12Count++;
130         }
131       }
132     }
133 
134   // Sort all objects for short/paired displacements, which should be
135   // sufficient as it seems like all frame objects typically are within the
136   // long displacement range.  Sorting works by computing the "density" as
137   // Count / ObjectSize. The comparisons of two such fractions are refactored
138   // by multiplying both sides with A.ObjectSize * B.ObjectSize, in order to
139   // eliminate the (fp) divisions.  A higher density object needs to go after
140   // in the list in order for it to end up lower on the stack.
141   auto CmpD12 = [](const SZFrameSortingObj &A, const SZFrameSortingObj &B) {
142     // Put all invalid and variable sized objects at the end.
143     if (!A.IsValid || !B.IsValid)
144       return A.IsValid;
145     if (!A.ObjectSize || !B.ObjectSize)
146       return A.ObjectSize > 0;
147     uint64_t ADensityCmp = A.D12Count * B.ObjectSize;
148     uint64_t BDensityCmp = B.D12Count * A.ObjectSize;
149     if (ADensityCmp != BDensityCmp)
150       return ADensityCmp < BDensityCmp;
151     return A.DPairCount * B.ObjectSize < B.DPairCount * A.ObjectSize;
152   };
153   std::stable_sort(SortingObjects.begin(), SortingObjects.end(), CmpD12);
154 
155   // Now modify the original list to represent the final order that
156   // we want.
157   unsigned Idx = 0;
158   for (auto &Obj : SortingObjects) {
159     // All invalid items are sorted at the end, so it's safe to stop.
160     if (!Obj.IsValid)
161       break;
162     ObjectsToAllocate[Idx++] = Obj.ObjectIndex;
163   }
164 }
165 
166 bool SystemZFrameLowering::hasReservedCallFrame(
167     const MachineFunction &MF) const {
168   // The ELF ABI requires us to allocate 160 bytes of stack space for the
169   // callee, with any outgoing stack arguments being placed above that. It
170   // seems better to make that area a permanent feature of the frame even if
171   // we're using a frame pointer. Similarly, 64-bit XPLINK requires 96 bytes
172   // of stack space for the register save area.
173   return true;
174 }
175 
176 bool SystemZELFFrameLowering::assignCalleeSavedSpillSlots(
177     MachineFunction &MF, const TargetRegisterInfo *TRI,
178     std::vector<CalleeSavedInfo> &CSI) const {
179   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
180   MachineFrameInfo &MFFrame = MF.getFrameInfo();
181   bool IsVarArg = MF.getFunction().isVarArg();
182   if (CSI.empty())
183     return true; // Early exit if no callee saved registers are modified!
184 
185   unsigned LowGPR = 0;
186   unsigned HighGPR = SystemZ::R15D;
187   int StartSPOffset = SystemZMC::ELFCallFrameSize;
188   for (auto &CS : CSI) {
189     Register Reg = CS.getReg();
190     int Offset = getRegSpillOffset(MF, Reg);
191     if (Offset) {
192       if (SystemZ::GR64BitRegClass.contains(Reg) && StartSPOffset > Offset) {
193         LowGPR = Reg;
194         StartSPOffset = Offset;
195       }
196       Offset -= SystemZMC::ELFCallFrameSize;
197       int FrameIdx = MFFrame.CreateFixedSpillStackObject(8, Offset);
198       CS.setFrameIdx(FrameIdx);
199     } else
200       CS.setFrameIdx(INT32_MAX);
201   }
202 
203   // Save the range of call-saved registers, for use by the
204   // prologue/epilogue inserters.
205   ZFI->setRestoreGPRRegs(LowGPR, HighGPR, StartSPOffset);
206   if (IsVarArg) {
207     // Also save the GPR varargs, if any.  R6D is call-saved, so would
208     // already be included, but we also need to handle the call-clobbered
209     // argument registers.
210     Register FirstGPR = ZFI->getVarArgsFirstGPR();
211     if (FirstGPR < SystemZ::ELFNumArgGPRs) {
212       unsigned Reg = SystemZ::ELFArgGPRs[FirstGPR];
213       int Offset = getRegSpillOffset(MF, Reg);
214       if (StartSPOffset > Offset) {
215         LowGPR = Reg; StartSPOffset = Offset;
216       }
217     }
218   }
219   ZFI->setSpillGPRRegs(LowGPR, HighGPR, StartSPOffset);
220 
221   // Create fixed stack objects for the remaining registers.
222   int CurrOffset = -SystemZMC::ELFCallFrameSize;
223   if (usePackedStack(MF))
224     CurrOffset += StartSPOffset;
225 
226   for (auto &CS : CSI) {
227     if (CS.getFrameIdx() != INT32_MAX)
228       continue;
229     Register Reg = CS.getReg();
230     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
231     unsigned Size = TRI->getSpillSize(*RC);
232     CurrOffset -= Size;
233     assert(CurrOffset % 8 == 0 &&
234            "8-byte alignment required for for all register save slots");
235     int FrameIdx = MFFrame.CreateFixedSpillStackObject(Size, CurrOffset);
236     CS.setFrameIdx(FrameIdx);
237   }
238 
239   return true;
240 }
241 
242 void SystemZELFFrameLowering::determineCalleeSaves(MachineFunction &MF,
243                                                    BitVector &SavedRegs,
244                                                    RegScavenger *RS) const {
245   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
246 
247   MachineFrameInfo &MFFrame = MF.getFrameInfo();
248   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
249   bool HasFP = hasFP(MF);
250   SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
251   bool IsVarArg = MF.getFunction().isVarArg();
252 
253   // va_start stores incoming FPR varargs in the normal way, but delegates
254   // the saving of incoming GPR varargs to spillCalleeSavedRegisters().
255   // Record these pending uses, which typically include the call-saved
256   // argument register R6D.
257   if (IsVarArg)
258     for (unsigned I = MFI->getVarArgsFirstGPR(); I < SystemZ::ELFNumArgGPRs; ++I)
259       SavedRegs.set(SystemZ::ELFArgGPRs[I]);
260 
261   // If there are any landing pads, entering them will modify r6/r7.
262   if (!MF.getLandingPads().empty()) {
263     SavedRegs.set(SystemZ::R6D);
264     SavedRegs.set(SystemZ::R7D);
265   }
266 
267   // If the function requires a frame pointer, record that the hard
268   // frame pointer will be clobbered.
269   if (HasFP)
270     SavedRegs.set(SystemZ::R11D);
271 
272   // If the function calls other functions, record that the return
273   // address register will be clobbered.
274   if (MFFrame.hasCalls())
275     SavedRegs.set(SystemZ::R14D);
276 
277   // If we are saving GPRs other than the stack pointer, we might as well
278   // save and restore the stack pointer at the same time, via STMG and LMG.
279   // This allows the deallocation to be done by the LMG, rather than needing
280   // a separate %r15 addition.
281   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
282   for (unsigned I = 0; CSRegs[I]; ++I) {
283     unsigned Reg = CSRegs[I];
284     if (SystemZ::GR64BitRegClass.contains(Reg) && SavedRegs.test(Reg)) {
285       SavedRegs.set(SystemZ::R15D);
286       break;
287     }
288   }
289 }
290 
291 SystemZELFFrameLowering::SystemZELFFrameLowering()
292     : SystemZFrameLowering(TargetFrameLowering::StackGrowsDown, Align(8), 0,
293                            Align(8), /* StackRealignable */ false),
294       RegSpillOffsets(0) {
295 
296   // Due to the SystemZ ABI, the DWARF CFA (Canonical Frame Address) is not
297   // equal to the incoming stack pointer, but to incoming stack pointer plus
298   // 160.  Instead of using a Local Area Offset, the Register save area will
299   // be occupied by fixed frame objects, and all offsets are actually
300   // relative to CFA.
301 
302   // Create a mapping from register number to save slot offset.
303   // These offsets are relative to the start of the register save area.
304   RegSpillOffsets.grow(SystemZ::NUM_TARGET_REGS);
305   for (const auto &Entry : ELFSpillOffsetTable)
306     RegSpillOffsets[Entry.Reg] = Entry.Offset;
307 }
308 
309 // Add GPR64 to the save instruction being built by MIB, which is in basic
310 // block MBB.  IsImplicit says whether this is an explicit operand to the
311 // instruction, or an implicit one that comes between the explicit start
312 // and end registers.
313 static void addSavedGPR(MachineBasicBlock &MBB, MachineInstrBuilder &MIB,
314                         unsigned GPR64, bool IsImplicit) {
315   const TargetRegisterInfo *RI =
316       MBB.getParent()->getSubtarget().getRegisterInfo();
317   Register GPR32 = RI->getSubReg(GPR64, SystemZ::subreg_l32);
318   bool IsLive = MBB.isLiveIn(GPR64) || MBB.isLiveIn(GPR32);
319   if (!IsLive || !IsImplicit) {
320     MIB.addReg(GPR64, getImplRegState(IsImplicit) | getKillRegState(!IsLive));
321     if (!IsLive)
322       MBB.addLiveIn(GPR64);
323   }
324 }
325 
326 bool SystemZELFFrameLowering::spillCalleeSavedRegisters(
327     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
328     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
329   if (CSI.empty())
330     return false;
331 
332   MachineFunction &MF = *MBB.getParent();
333   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
334   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
335   bool IsVarArg = MF.getFunction().isVarArg();
336   DebugLoc DL;
337 
338   // Save GPRs
339   SystemZ::GPRRegs SpillGPRs = ZFI->getSpillGPRRegs();
340   if (SpillGPRs.LowGPR) {
341     assert(SpillGPRs.LowGPR != SpillGPRs.HighGPR &&
342            "Should be saving %r15 and something else");
343 
344     // Build an STMG instruction.
345     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STMG));
346 
347     // Add the explicit register operands.
348     addSavedGPR(MBB, MIB, SpillGPRs.LowGPR, false);
349     addSavedGPR(MBB, MIB, SpillGPRs.HighGPR, false);
350 
351     // Add the address.
352     MIB.addReg(SystemZ::R15D).addImm(SpillGPRs.GPROffset);
353 
354     // Make sure all call-saved GPRs are included as operands and are
355     // marked as live on entry.
356     for (const CalleeSavedInfo &I : CSI) {
357       Register Reg = I.getReg();
358       if (SystemZ::GR64BitRegClass.contains(Reg))
359         addSavedGPR(MBB, MIB, Reg, true);
360     }
361 
362     // ...likewise GPR varargs.
363     if (IsVarArg)
364       for (unsigned I = ZFI->getVarArgsFirstGPR(); I < SystemZ::ELFNumArgGPRs; ++I)
365         addSavedGPR(MBB, MIB, SystemZ::ELFArgGPRs[I], true);
366   }
367 
368   // Save FPRs/VRs in the normal TargetInstrInfo way.
369   for (const CalleeSavedInfo &I : CSI) {
370     Register Reg = I.getReg();
371     if (SystemZ::FP64BitRegClass.contains(Reg)) {
372       MBB.addLiveIn(Reg);
373       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, I.getFrameIdx(),
374                                &SystemZ::FP64BitRegClass, TRI, Register());
375     }
376     if (SystemZ::VR128BitRegClass.contains(Reg)) {
377       MBB.addLiveIn(Reg);
378       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, I.getFrameIdx(),
379                                &SystemZ::VR128BitRegClass, TRI, Register());
380     }
381   }
382 
383   return true;
384 }
385 
386 bool SystemZELFFrameLowering::restoreCalleeSavedRegisters(
387     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
388     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
389   if (CSI.empty())
390     return false;
391 
392   MachineFunction &MF = *MBB.getParent();
393   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
394   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
395   bool HasFP = hasFP(MF);
396   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
397 
398   // Restore FPRs/VRs in the normal TargetInstrInfo way.
399   for (const CalleeSavedInfo &I : CSI) {
400     Register Reg = I.getReg();
401     if (SystemZ::FP64BitRegClass.contains(Reg))
402       TII->loadRegFromStackSlot(MBB, MBBI, Reg, I.getFrameIdx(),
403                                 &SystemZ::FP64BitRegClass, TRI, Register());
404     if (SystemZ::VR128BitRegClass.contains(Reg))
405       TII->loadRegFromStackSlot(MBB, MBBI, Reg, I.getFrameIdx(),
406                                 &SystemZ::VR128BitRegClass, TRI, Register());
407   }
408 
409   // Restore call-saved GPRs (but not call-clobbered varargs, which at
410   // this point might hold return values).
411   SystemZ::GPRRegs RestoreGPRs = ZFI->getRestoreGPRRegs();
412   if (RestoreGPRs.LowGPR) {
413     // If we saved any of %r2-%r5 as varargs, we should also be saving
414     // and restoring %r6.  If we're saving %r6 or above, we should be
415     // restoring it too.
416     assert(RestoreGPRs.LowGPR != RestoreGPRs.HighGPR &&
417            "Should be loading %r15 and something else");
418 
419     // Build an LMG instruction.
420     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LMG));
421 
422     // Add the explicit register operands.
423     MIB.addReg(RestoreGPRs.LowGPR, RegState::Define);
424     MIB.addReg(RestoreGPRs.HighGPR, RegState::Define);
425 
426     // Add the address.
427     MIB.addReg(HasFP ? SystemZ::R11D : SystemZ::R15D);
428     MIB.addImm(RestoreGPRs.GPROffset);
429 
430     // Do a second scan adding regs as being defined by instruction
431     for (const CalleeSavedInfo &I : CSI) {
432       Register Reg = I.getReg();
433       if (Reg != RestoreGPRs.LowGPR && Reg != RestoreGPRs.HighGPR &&
434           SystemZ::GR64BitRegClass.contains(Reg))
435         MIB.addReg(Reg, RegState::ImplicitDefine);
436     }
437   }
438 
439   return true;
440 }
441 
442 void SystemZELFFrameLowering::processFunctionBeforeFrameFinalized(
443     MachineFunction &MF, RegScavenger *RS) const {
444   MachineFrameInfo &MFFrame = MF.getFrameInfo();
445   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
446   MachineRegisterInfo *MRI = &MF.getRegInfo();
447   bool BackChain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
448 
449   if (!usePackedStack(MF) || BackChain)
450     // Create the incoming register save area.
451     getOrCreateFramePointerSaveIndex(MF);
452 
453   // Get the size of our stack frame to be allocated ...
454   uint64_t StackSize = (MFFrame.estimateStackSize(MF) +
455                         SystemZMC::ELFCallFrameSize);
456   // ... and the maximum offset we may need to reach into the
457   // caller's frame to access the save area or stack arguments.
458   int64_t MaxArgOffset = 0;
459   for (int I = MFFrame.getObjectIndexBegin(); I != 0; ++I)
460     if (MFFrame.getObjectOffset(I) >= 0) {
461       int64_t ArgOffset = MFFrame.getObjectOffset(I) +
462                           MFFrame.getObjectSize(I);
463       MaxArgOffset = std::max(MaxArgOffset, ArgOffset);
464     }
465 
466   uint64_t MaxReach = StackSize + MaxArgOffset;
467   if (!isUInt<12>(MaxReach)) {
468     // We may need register scavenging slots if some parts of the frame
469     // are outside the reach of an unsigned 12-bit displacement.
470     // Create 2 for the case where both addresses in an MVC are
471     // out of range.
472     RS->addScavengingFrameIndex(MFFrame.CreateStackObject(8, Align(8), false));
473     RS->addScavengingFrameIndex(MFFrame.CreateStackObject(8, Align(8), false));
474   }
475 
476   // If R6 is used as an argument register it is still callee saved. If it in
477   // this case is not clobbered (and restored) it should never be marked as
478   // killed.
479   if (MF.front().isLiveIn(SystemZ::R6D) &&
480       ZFI->getRestoreGPRRegs().LowGPR != SystemZ::R6D)
481     for (auto &MO : MRI->use_nodbg_operands(SystemZ::R6D))
482       MO.setIsKill(false);
483 }
484 
485 // Emit instructions before MBBI (in MBB) to add NumBytes to Reg.
486 static void emitIncrement(MachineBasicBlock &MBB,
487                           MachineBasicBlock::iterator &MBBI, const DebugLoc &DL,
488                           Register Reg, int64_t NumBytes,
489                           const TargetInstrInfo *TII) {
490   while (NumBytes) {
491     unsigned Opcode;
492     int64_t ThisVal = NumBytes;
493     if (isInt<16>(NumBytes))
494       Opcode = SystemZ::AGHI;
495     else {
496       Opcode = SystemZ::AGFI;
497       // Make sure we maintain 8-byte stack alignment.
498       int64_t MinVal = -uint64_t(1) << 31;
499       int64_t MaxVal = (int64_t(1) << 31) - 8;
500       if (ThisVal < MinVal)
501         ThisVal = MinVal;
502       else if (ThisVal > MaxVal)
503         ThisVal = MaxVal;
504     }
505     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII->get(Opcode), Reg)
506       .addReg(Reg).addImm(ThisVal);
507     // The CC implicit def is dead.
508     MI->getOperand(3).setIsDead();
509     NumBytes -= ThisVal;
510   }
511 }
512 
513 // Add CFI for the new CFA offset.
514 static void buildCFAOffs(MachineBasicBlock &MBB,
515                          MachineBasicBlock::iterator MBBI,
516                          const DebugLoc &DL, int Offset,
517                          const SystemZInstrInfo *ZII) {
518   unsigned CFIIndex = MBB.getParent()->addFrameInst(
519     MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset));
520   BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
521     .addCFIIndex(CFIIndex);
522 }
523 
524 // Add CFI for the new frame location.
525 static void buildDefCFAReg(MachineBasicBlock &MBB,
526                            MachineBasicBlock::iterator MBBI,
527                            const DebugLoc &DL, unsigned Reg,
528                            const SystemZInstrInfo *ZII) {
529   MachineFunction &MF = *MBB.getParent();
530   MachineModuleInfo &MMI = MF.getMMI();
531   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
532   unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
533   unsigned CFIIndex = MF.addFrameInst(
534                         MCCFIInstruction::createDefCfaRegister(nullptr, RegNum));
535   BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
536     .addCFIIndex(CFIIndex);
537 }
538 
539 void SystemZELFFrameLowering::emitPrologue(MachineFunction &MF,
540                                            MachineBasicBlock &MBB) const {
541   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
542   const SystemZSubtarget &STI = MF.getSubtarget<SystemZSubtarget>();
543   const SystemZTargetLowering &TLI = *STI.getTargetLowering();
544   MachineFrameInfo &MFFrame = MF.getFrameInfo();
545   auto *ZII = static_cast<const SystemZInstrInfo *>(STI.getInstrInfo());
546   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
547   MachineBasicBlock::iterator MBBI = MBB.begin();
548   MachineModuleInfo &MMI = MF.getMMI();
549   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
550   const std::vector<CalleeSavedInfo> &CSI = MFFrame.getCalleeSavedInfo();
551   bool HasFP = hasFP(MF);
552 
553   // In GHC calling convention C stack space, including the ABI-defined
554   // 160-byte base area, is (de)allocated by GHC itself.  This stack space may
555   // be used by LLVM as spill slots for the tail recursive GHC functions.  Thus
556   // do not allocate stack space here, too.
557   if (MF.getFunction().getCallingConv() == CallingConv::GHC) {
558     if (MFFrame.getStackSize() > 2048 * sizeof(long)) {
559       report_fatal_error(
560           "Pre allocated stack space for GHC function is too small");
561     }
562     if (HasFP) {
563       report_fatal_error(
564           "In GHC calling convention a frame pointer is not supported");
565     }
566     MFFrame.setStackSize(MFFrame.getStackSize() + SystemZMC::ELFCallFrameSize);
567     return;
568   }
569 
570   // Debug location must be unknown since the first debug location is used
571   // to determine the end of the prologue.
572   DebugLoc DL;
573 
574   // The current offset of the stack pointer from the CFA.
575   int64_t SPOffsetFromCFA = -SystemZMC::ELFCFAOffsetFromInitialSP;
576 
577   if (ZFI->getSpillGPRRegs().LowGPR) {
578     // Skip over the GPR saves.
579     if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
580       ++MBBI;
581     else
582       llvm_unreachable("Couldn't skip over GPR saves");
583 
584     // Add CFI for the GPR saves.
585     for (auto &Save : CSI) {
586       Register Reg = Save.getReg();
587       if (SystemZ::GR64BitRegClass.contains(Reg)) {
588         int FI = Save.getFrameIdx();
589         int64_t Offset = MFFrame.getObjectOffset(FI);
590         unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
591             nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
592         BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
593             .addCFIIndex(CFIIndex);
594       }
595     }
596   }
597 
598   uint64_t StackSize = MFFrame.getStackSize();
599   // We need to allocate the ABI-defined 160-byte base area whenever
600   // we allocate stack space for our own use and whenever we call another
601   // function.
602   bool HasStackObject = false;
603   for (unsigned i = 0, e = MFFrame.getObjectIndexEnd(); i != e; ++i)
604     if (!MFFrame.isDeadObjectIndex(i)) {
605       HasStackObject = true;
606       break;
607     }
608   if (HasStackObject || MFFrame.hasCalls())
609     StackSize += SystemZMC::ELFCallFrameSize;
610   // Don't allocate the incoming reg save area.
611   StackSize = StackSize > SystemZMC::ELFCallFrameSize
612                   ? StackSize - SystemZMC::ELFCallFrameSize
613                   : 0;
614   MFFrame.setStackSize(StackSize);
615 
616   if (StackSize) {
617     // Allocate StackSize bytes.
618     int64_t Delta = -int64_t(StackSize);
619     const unsigned ProbeSize = TLI.getStackProbeSize(MF);
620     bool FreeProbe = (ZFI->getSpillGPRRegs().GPROffset &&
621            (ZFI->getSpillGPRRegs().GPROffset + StackSize) < ProbeSize);
622     if (!FreeProbe &&
623         MF.getSubtarget().getTargetLowering()->hasInlineStackProbe(MF)) {
624       // Stack probing may involve looping, but splitting the prologue block
625       // is not possible at this point since it would invalidate the
626       // SaveBlocks / RestoreBlocks sets of PEI in the single block function
627       // case. Build a pseudo to be handled later by inlineStackProbe().
628       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::PROBED_STACKALLOC))
629         .addImm(StackSize);
630     }
631     else {
632       bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
633       // If we need backchain, save current stack pointer.  R1 is free at
634       // this point.
635       if (StoreBackchain)
636         BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR))
637           .addReg(SystemZ::R1D, RegState::Define).addReg(SystemZ::R15D);
638       emitIncrement(MBB, MBBI, DL, SystemZ::R15D, Delta, ZII);
639       buildCFAOffs(MBB, MBBI, DL, SPOffsetFromCFA + Delta, ZII);
640       if (StoreBackchain)
641         BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::STG))
642           .addReg(SystemZ::R1D, RegState::Kill).addReg(SystemZ::R15D)
643           .addImm(getBackchainOffset(MF)).addReg(0);
644     }
645     SPOffsetFromCFA += Delta;
646   }
647 
648   if (HasFP) {
649     // Copy the base of the frame to R11.
650     BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R11D)
651       .addReg(SystemZ::R15D);
652 
653     // Add CFI for the new frame location.
654     buildDefCFAReg(MBB, MBBI, DL, SystemZ::R11D, ZII);
655 
656     // Mark the FramePtr as live at the beginning of every block except
657     // the entry block.  (We'll have marked R11 as live on entry when
658     // saving the GPRs.)
659     for (MachineBasicBlock &MBBJ : llvm::drop_begin(MF))
660       MBBJ.addLiveIn(SystemZ::R11D);
661   }
662 
663   // Skip over the FPR/VR saves.
664   SmallVector<unsigned, 8> CFIIndexes;
665   for (auto &Save : CSI) {
666     Register Reg = Save.getReg();
667     if (SystemZ::FP64BitRegClass.contains(Reg)) {
668       if (MBBI != MBB.end() &&
669           (MBBI->getOpcode() == SystemZ::STD ||
670            MBBI->getOpcode() == SystemZ::STDY))
671         ++MBBI;
672       else
673         llvm_unreachable("Couldn't skip over FPR save");
674     } else if (SystemZ::VR128BitRegClass.contains(Reg)) {
675       if (MBBI != MBB.end() &&
676           MBBI->getOpcode() == SystemZ::VST)
677         ++MBBI;
678       else
679         llvm_unreachable("Couldn't skip over VR save");
680     } else
681       continue;
682 
683     // Add CFI for the this save.
684     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
685     Register IgnoredFrameReg;
686     int64_t Offset =
687         getFrameIndexReference(MF, Save.getFrameIdx(), IgnoredFrameReg)
688             .getFixed();
689 
690     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
691           nullptr, DwarfReg, SPOffsetFromCFA + Offset));
692     CFIIndexes.push_back(CFIIndex);
693   }
694   // Complete the CFI for the FPR/VR saves, modelling them as taking effect
695   // after the last save.
696   for (auto CFIIndex : CFIIndexes) {
697     BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
698         .addCFIIndex(CFIIndex);
699   }
700 }
701 
702 void SystemZELFFrameLowering::emitEpilogue(MachineFunction &MF,
703                                            MachineBasicBlock &MBB) const {
704   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
705   auto *ZII =
706       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
707   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
708   MachineFrameInfo &MFFrame = MF.getFrameInfo();
709 
710   // See SystemZELFFrameLowering::emitPrologue
711   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
712     return;
713 
714   // Skip the return instruction.
715   assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
716 
717   uint64_t StackSize = MFFrame.getStackSize();
718   if (ZFI->getRestoreGPRRegs().LowGPR) {
719     --MBBI;
720     unsigned Opcode = MBBI->getOpcode();
721     if (Opcode != SystemZ::LMG)
722       llvm_unreachable("Expected to see callee-save register restore code");
723 
724     unsigned AddrOpNo = 2;
725     DebugLoc DL = MBBI->getDebugLoc();
726     uint64_t Offset = StackSize + MBBI->getOperand(AddrOpNo + 1).getImm();
727     unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
728 
729     // If the offset is too large, use the largest stack-aligned offset
730     // and add the rest to the base register (the stack or frame pointer).
731     if (!NewOpcode) {
732       uint64_t NumBytes = Offset - 0x7fff8;
733       emitIncrement(MBB, MBBI, DL, MBBI->getOperand(AddrOpNo).getReg(),
734                     NumBytes, ZII);
735       Offset -= NumBytes;
736       NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
737       assert(NewOpcode && "No restore instruction available");
738     }
739 
740     MBBI->setDesc(ZII->get(NewOpcode));
741     MBBI->getOperand(AddrOpNo + 1).ChangeToImmediate(Offset);
742   } else if (StackSize) {
743     DebugLoc DL = MBBI->getDebugLoc();
744     emitIncrement(MBB, MBBI, DL, SystemZ::R15D, StackSize, ZII);
745   }
746 }
747 
748 void SystemZELFFrameLowering::inlineStackProbe(
749     MachineFunction &MF, MachineBasicBlock &PrologMBB) const {
750   auto *ZII =
751     static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
752   const SystemZSubtarget &STI = MF.getSubtarget<SystemZSubtarget>();
753   const SystemZTargetLowering &TLI = *STI.getTargetLowering();
754 
755   MachineInstr *StackAllocMI = nullptr;
756   for (MachineInstr &MI : PrologMBB)
757     if (MI.getOpcode() == SystemZ::PROBED_STACKALLOC) {
758       StackAllocMI = &MI;
759       break;
760     }
761   if (StackAllocMI == nullptr)
762     return;
763   uint64_t StackSize = StackAllocMI->getOperand(0).getImm();
764   const unsigned ProbeSize = TLI.getStackProbeSize(MF);
765   uint64_t NumFullBlocks = StackSize / ProbeSize;
766   uint64_t Residual = StackSize % ProbeSize;
767   int64_t SPOffsetFromCFA = -SystemZMC::ELFCFAOffsetFromInitialSP;
768   MachineBasicBlock *MBB = &PrologMBB;
769   MachineBasicBlock::iterator MBBI = StackAllocMI;
770   const DebugLoc DL = StackAllocMI->getDebugLoc();
771 
772   // Allocate a block of Size bytes on the stack and probe it.
773   auto allocateAndProbe = [&](MachineBasicBlock &InsMBB,
774                               MachineBasicBlock::iterator InsPt, unsigned Size,
775                               bool EmitCFI) -> void {
776     emitIncrement(InsMBB, InsPt, DL, SystemZ::R15D, -int64_t(Size), ZII);
777     if (EmitCFI) {
778       SPOffsetFromCFA -= Size;
779       buildCFAOffs(InsMBB, InsPt, DL, SPOffsetFromCFA, ZII);
780     }
781     // Probe by means of a volatile compare.
782     MachineMemOperand *MMO = MF.getMachineMemOperand(MachinePointerInfo(),
783       MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad, 8, Align(1));
784     BuildMI(InsMBB, InsPt, DL, ZII->get(SystemZ::CG))
785       .addReg(SystemZ::R0D, RegState::Undef)
786       .addReg(SystemZ::R15D).addImm(Size - 8).addReg(0)
787       .addMemOperand(MMO);
788   };
789 
790   bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
791   if (StoreBackchain)
792     BuildMI(*MBB, MBBI, DL, ZII->get(SystemZ::LGR))
793       .addReg(SystemZ::R1D, RegState::Define).addReg(SystemZ::R15D);
794 
795   MachineBasicBlock *DoneMBB = nullptr;
796   MachineBasicBlock *LoopMBB = nullptr;
797   if (NumFullBlocks < 3) {
798     // Emit unrolled probe statements.
799     for (unsigned int i = 0; i < NumFullBlocks; i++)
800       allocateAndProbe(*MBB, MBBI, ProbeSize, true/*EmitCFI*/);
801   } else {
802     // Emit a loop probing the pages.
803     uint64_t LoopAlloc = ProbeSize * NumFullBlocks;
804     SPOffsetFromCFA -= LoopAlloc;
805 
806     // Use R0D to hold the exit value.
807     BuildMI(*MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R0D)
808       .addReg(SystemZ::R15D);
809     buildDefCFAReg(*MBB, MBBI, DL, SystemZ::R0D, ZII);
810     emitIncrement(*MBB, MBBI, DL, SystemZ::R0D, -int64_t(LoopAlloc), ZII);
811     buildCFAOffs(*MBB, MBBI, DL, -int64_t(SystemZMC::ELFCallFrameSize + LoopAlloc),
812                  ZII);
813 
814     DoneMBB = SystemZ::splitBlockBefore(MBBI, MBB);
815     LoopMBB = SystemZ::emitBlockAfter(MBB);
816     MBB->addSuccessor(LoopMBB);
817     LoopMBB->addSuccessor(LoopMBB);
818     LoopMBB->addSuccessor(DoneMBB);
819 
820     MBB = LoopMBB;
821     allocateAndProbe(*MBB, MBB->end(), ProbeSize, false/*EmitCFI*/);
822     BuildMI(*MBB, MBB->end(), DL, ZII->get(SystemZ::CLGR))
823       .addReg(SystemZ::R15D).addReg(SystemZ::R0D);
824     BuildMI(*MBB, MBB->end(), DL, ZII->get(SystemZ::BRC))
825       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_GT).addMBB(MBB);
826 
827     MBB = DoneMBB;
828     MBBI = DoneMBB->begin();
829     buildDefCFAReg(*MBB, MBBI, DL, SystemZ::R15D, ZII);
830   }
831 
832   if (Residual)
833     allocateAndProbe(*MBB, MBBI, Residual, true/*EmitCFI*/);
834 
835   if (StoreBackchain)
836     BuildMI(*MBB, MBBI, DL, ZII->get(SystemZ::STG))
837       .addReg(SystemZ::R1D, RegState::Kill).addReg(SystemZ::R15D)
838       .addImm(getBackchainOffset(MF)).addReg(0);
839 
840   StackAllocMI->eraseFromParent();
841   if (DoneMBB != nullptr) {
842     // Compute the live-in lists for the new blocks.
843     recomputeLiveIns(*DoneMBB);
844     recomputeLiveIns(*LoopMBB);
845   }
846 }
847 
848 bool SystemZELFFrameLowering::hasFP(const MachineFunction &MF) const {
849   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
850           MF.getFrameInfo().hasVarSizedObjects());
851 }
852 
853 StackOffset SystemZELFFrameLowering::getFrameIndexReference(
854     const MachineFunction &MF, int FI, Register &FrameReg) const {
855   // Our incoming SP is actually SystemZMC::ELFCallFrameSize below the CFA, so
856   // add that difference here.
857   StackOffset Offset =
858       TargetFrameLowering::getFrameIndexReference(MF, FI, FrameReg);
859   return Offset + StackOffset::getFixed(SystemZMC::ELFCallFrameSize);
860 }
861 
862 unsigned SystemZELFFrameLowering::getRegSpillOffset(MachineFunction &MF,
863                                                     Register Reg) const {
864   bool IsVarArg = MF.getFunction().isVarArg();
865   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
866   bool BackChain = Subtarget.hasBackChain();
867   bool SoftFloat = Subtarget.hasSoftFloat();
868   unsigned Offset = RegSpillOffsets[Reg];
869   if (usePackedStack(MF) && !(IsVarArg && !SoftFloat)) {
870     if (SystemZ::GR64BitRegClass.contains(Reg))
871       // Put all GPRs at the top of the Register save area with packed
872       // stack. Make room for the backchain if needed.
873       Offset += BackChain ? 24 : 32;
874     else
875       Offset = 0;
876   }
877   return Offset;
878 }
879 
880 int SystemZELFFrameLowering::getOrCreateFramePointerSaveIndex(
881     MachineFunction &MF) const {
882   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
883   int FI = ZFI->getFramePointerSaveIndex();
884   if (!FI) {
885     MachineFrameInfo &MFFrame = MF.getFrameInfo();
886     int Offset = getBackchainOffset(MF) - SystemZMC::ELFCallFrameSize;
887     FI = MFFrame.CreateFixedObject(8, Offset, false);
888     ZFI->setFramePointerSaveIndex(FI);
889   }
890   return FI;
891 }
892 
893 bool SystemZELFFrameLowering::usePackedStack(MachineFunction &MF) const {
894   bool HasPackedStackAttr = MF.getFunction().hasFnAttribute("packed-stack");
895   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
896   bool BackChain = Subtarget.hasBackChain();
897   bool SoftFloat = Subtarget.hasSoftFloat();
898   if (HasPackedStackAttr && BackChain && !SoftFloat)
899     report_fatal_error("packed-stack + backchain + hard-float is unsupported.");
900   bool CallConv = MF.getFunction().getCallingConv() != CallingConv::GHC;
901   return HasPackedStackAttr && CallConv;
902 }
903 
904 SystemZXPLINKFrameLowering::SystemZXPLINKFrameLowering()
905     : SystemZFrameLowering(TargetFrameLowering::StackGrowsDown, Align(32), 0,
906                            Align(32), /* StackRealignable */ false),
907       RegSpillOffsets(-1) {
908 
909   // Create a mapping from register number to save slot offset.
910   // These offsets are relative to the start of the local are area.
911   RegSpillOffsets.grow(SystemZ::NUM_TARGET_REGS);
912   for (const auto &Entry : XPLINKSpillOffsetTable)
913     RegSpillOffsets[Entry.Reg] = Entry.Offset;
914 }
915 
916 // Checks if the function is a potential candidate for being a XPLeaf routine.
917 static bool isXPLeafCandidate(const MachineFunction &MF) {
918   const MachineFrameInfo &MFFrame = MF.getFrameInfo();
919   const MachineRegisterInfo &MRI = MF.getRegInfo();
920   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
921   auto *Regs =
922       static_cast<SystemZXPLINK64Registers *>(Subtarget.getSpecialRegisters());
923 
924   // If function calls other functions including alloca, then it is not a XPLeaf
925   // routine.
926   if (MFFrame.hasCalls())
927     return false;
928 
929   // If the function has var Sized Objects, then it is not a XPLeaf routine.
930   if (MFFrame.hasVarSizedObjects())
931     return false;
932 
933   // If the function adjusts the stack, then it is not a XPLeaf routine.
934   if (MFFrame.adjustsStack())
935     return false;
936 
937   // If function modifies the stack pointer register, then it is not a XPLeaf
938   // routine.
939   if (MRI.isPhysRegModified(Regs->getStackPointerRegister()))
940     return false;
941 
942   // If function modifies the ADA register, then it is not a XPLeaf routine.
943   if (MRI.isPhysRegModified(Regs->getAddressOfCalleeRegister()))
944     return false;
945 
946   // If function modifies the return address register, then it is not a XPLeaf
947   // routine.
948   if (MRI.isPhysRegModified(Regs->getReturnFunctionAddressRegister()))
949     return false;
950 
951   // If the backchain pointer should be stored, then it is not a XPLeaf routine.
952   if (MF.getSubtarget<SystemZSubtarget>().hasBackChain())
953     return false;
954 
955   // If function acquires its own stack frame, then it is not a XPLeaf routine.
956   // At the time this function is called, only slots for local variables are
957   // allocated, so this is a very rough estimate.
958   if (MFFrame.estimateStackSize(MF) > 0)
959     return false;
960 
961   return true;
962 }
963 
964 bool SystemZXPLINKFrameLowering::assignCalleeSavedSpillSlots(
965     MachineFunction &MF, const TargetRegisterInfo *TRI,
966     std::vector<CalleeSavedInfo> &CSI) const {
967   MachineFrameInfo &MFFrame = MF.getFrameInfo();
968   SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
969   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
970   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
971   auto &GRRegClass = SystemZ::GR64BitRegClass;
972 
973   // At this point, the result of isXPLeafCandidate() is not accurate because
974   // the size of the save area has not yet been determined. If
975   // isXPLeafCandidate() indicates a potential leaf function, and there are no
976   // callee-save registers, then it is indeed a leaf function, and we can early
977   // exit.
978   // TODO: It is possible for leaf functions to use callee-saved registers.
979   // It can use the 0-2k range between R4 and the caller's stack frame without
980   // acquiring its own stack frame.
981   bool IsLeaf = CSI.empty() && isXPLeafCandidate(MF);
982   if (IsLeaf)
983     return true;
984 
985   // For non-leaf functions:
986   // - the address of callee (entry point) register R6 must be saved
987   CSI.push_back(CalleeSavedInfo(Regs.getAddressOfCalleeRegister()));
988   CSI.back().setRestored(false);
989 
990   // The return address register R7 must be saved and restored.
991   CSI.push_back(CalleeSavedInfo(Regs.getReturnFunctionAddressRegister()));
992 
993   // If the function needs a frame pointer, or if the backchain pointer should
994   // be stored, then save the stack pointer register R4.
995   if (hasFP(MF) || Subtarget.hasBackChain())
996     CSI.push_back(CalleeSavedInfo(Regs.getStackPointerRegister()));
997 
998   // If this function has an associated personality function then the
999   // environment register R5 must be saved in the DSA.
1000   if (!MF.getLandingPads().empty())
1001     CSI.push_back(CalleeSavedInfo(Regs.getADARegister()));
1002 
1003   // Scan the call-saved GPRs and find the bounds of the register spill area.
1004   Register LowRestoreGPR = 0;
1005   int LowRestoreOffset = INT32_MAX;
1006   Register LowSpillGPR = 0;
1007   int LowSpillOffset = INT32_MAX;
1008   Register HighGPR = 0;
1009   int HighOffset = -1;
1010 
1011   for (auto &CS : CSI) {
1012     Register Reg = CS.getReg();
1013     int Offset = RegSpillOffsets[Reg];
1014     if (Offset >= 0) {
1015       if (GRRegClass.contains(Reg)) {
1016         if (LowSpillOffset > Offset) {
1017           LowSpillOffset = Offset;
1018           LowSpillGPR = Reg;
1019         }
1020         if (CS.isRestored() && LowRestoreOffset > Offset) {
1021           LowRestoreOffset = Offset;
1022           LowRestoreGPR = Reg;
1023         }
1024 
1025         if (Offset > HighOffset) {
1026           HighOffset = Offset;
1027           HighGPR = Reg;
1028         }
1029         // Non-volatile GPRs are saved in the dedicated register save area at
1030         // the bottom of the stack and are not truly part of the "normal" stack
1031         // frame. Mark the frame index as NoAlloc to indicate it as such.
1032         unsigned RegSize = 8;
1033         int FrameIdx = MFFrame.CreateFixedSpillStackObject(RegSize, Offset);
1034         CS.setFrameIdx(FrameIdx);
1035         MFFrame.setStackID(FrameIdx, TargetStackID::NoAlloc);
1036       }
1037     } else {
1038       Register Reg = CS.getReg();
1039       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1040       Align Alignment = TRI->getSpillAlign(*RC);
1041       unsigned Size = TRI->getSpillSize(*RC);
1042       Alignment = std::min(Alignment, getStackAlign());
1043       int FrameIdx = MFFrame.CreateStackObject(Size, Alignment, true);
1044       CS.setFrameIdx(FrameIdx);
1045     }
1046   }
1047 
1048   // Save the range of call-saved registers, for use by the
1049   // prologue/epilogue inserters.
1050   if (LowRestoreGPR)
1051     MFI->setRestoreGPRRegs(LowRestoreGPR, HighGPR, LowRestoreOffset);
1052 
1053   // Save the range of call-saved registers, for use by the epilogue inserter.
1054   assert(LowSpillGPR && "Expected registers to spill");
1055   MFI->setSpillGPRRegs(LowSpillGPR, HighGPR, LowSpillOffset);
1056 
1057   return true;
1058 }
1059 
1060 void SystemZXPLINKFrameLowering::determineCalleeSaves(MachineFunction &MF,
1061                                                       BitVector &SavedRegs,
1062                                                       RegScavenger *RS) const {
1063   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1064 
1065   bool HasFP = hasFP(MF);
1066   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1067   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1068 
1069   // If the function requires a frame pointer, record that the hard
1070   // frame pointer will be clobbered.
1071   if (HasFP)
1072     SavedRegs.set(Regs.getFramePointerRegister());
1073 }
1074 
1075 bool SystemZXPLINKFrameLowering::spillCalleeSavedRegisters(
1076     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1077     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1078   if (CSI.empty())
1079     return true;
1080 
1081   MachineFunction &MF = *MBB.getParent();
1082   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1083   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1084   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1085   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1086   SystemZ::GPRRegs SpillGPRs = ZFI->getSpillGPRRegs();
1087   DebugLoc DL;
1088 
1089   // Save GPRs
1090   if (SpillGPRs.LowGPR) {
1091     assert(SpillGPRs.LowGPR != SpillGPRs.HighGPR &&
1092            "Should be saving multiple registers");
1093 
1094     // Build an STM/STMG instruction.
1095     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STMG));
1096 
1097     // Add the explicit register operands.
1098     addSavedGPR(MBB, MIB, SpillGPRs.LowGPR, false);
1099     addSavedGPR(MBB, MIB, SpillGPRs.HighGPR, false);
1100 
1101     // Add the address r4
1102     MIB.addReg(Regs.getStackPointerRegister());
1103 
1104     // Add the partial offset
1105     // We cannot add the actual offset as, at the stack is not finalized
1106     MIB.addImm(SpillGPRs.GPROffset);
1107 
1108     // Make sure all call-saved GPRs are included as operands and are
1109     // marked as live on entry.
1110     auto &GRRegClass = SystemZ::GR64BitRegClass;
1111     for (const CalleeSavedInfo &I : CSI) {
1112       Register Reg = I.getReg();
1113       if (GRRegClass.contains(Reg))
1114         addSavedGPR(MBB, MIB, Reg, true);
1115     }
1116   }
1117 
1118   // Spill FPRs to the stack in the normal TargetInstrInfo way
1119   for (const CalleeSavedInfo &I : CSI) {
1120     Register Reg = I.getReg();
1121     if (SystemZ::FP64BitRegClass.contains(Reg)) {
1122       MBB.addLiveIn(Reg);
1123       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, I.getFrameIdx(),
1124                                &SystemZ::FP64BitRegClass, TRI, Register());
1125     }
1126     if (SystemZ::VR128BitRegClass.contains(Reg)) {
1127       MBB.addLiveIn(Reg);
1128       TII->storeRegToStackSlot(MBB, MBBI, Reg, true, I.getFrameIdx(),
1129                                &SystemZ::VR128BitRegClass, TRI, Register());
1130     }
1131   }
1132 
1133   return true;
1134 }
1135 
1136 bool SystemZXPLINKFrameLowering::restoreCalleeSavedRegisters(
1137     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1138     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1139 
1140   if (CSI.empty())
1141     return false;
1142 
1143   MachineFunction &MF = *MBB.getParent();
1144   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1145   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1146   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1147   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1148 
1149   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1150 
1151   // Restore FPRs in the normal TargetInstrInfo way.
1152   for (const CalleeSavedInfo &I : CSI) {
1153     Register Reg = I.getReg();
1154     if (SystemZ::FP64BitRegClass.contains(Reg))
1155       TII->loadRegFromStackSlot(MBB, MBBI, Reg, I.getFrameIdx(),
1156                                 &SystemZ::FP64BitRegClass, TRI, Register());
1157     if (SystemZ::VR128BitRegClass.contains(Reg))
1158       TII->loadRegFromStackSlot(MBB, MBBI, Reg, I.getFrameIdx(),
1159                                 &SystemZ::VR128BitRegClass, TRI, Register());
1160   }
1161 
1162   // Restore call-saved GPRs (but not call-clobbered varargs, which at
1163   // this point might hold return values).
1164   SystemZ::GPRRegs RestoreGPRs = ZFI->getRestoreGPRRegs();
1165   if (RestoreGPRs.LowGPR) {
1166     assert(isInt<20>(Regs.getStackPointerBias() + RestoreGPRs.GPROffset));
1167     if (RestoreGPRs.LowGPR == RestoreGPRs.HighGPR)
1168       // Build an LG/L instruction.
1169       BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LG), RestoreGPRs.LowGPR)
1170           .addReg(Regs.getStackPointerRegister())
1171           .addImm(Regs.getStackPointerBias() + RestoreGPRs.GPROffset)
1172           .addReg(0);
1173     else {
1174       // Build an LMG/LM instruction.
1175       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LMG));
1176 
1177       // Add the explicit register operands.
1178       MIB.addReg(RestoreGPRs.LowGPR, RegState::Define);
1179       MIB.addReg(RestoreGPRs.HighGPR, RegState::Define);
1180 
1181       // Add the address.
1182       MIB.addReg(Regs.getStackPointerRegister());
1183       MIB.addImm(Regs.getStackPointerBias() + RestoreGPRs.GPROffset);
1184 
1185       // Do a second scan adding regs as being defined by instruction
1186       for (const CalleeSavedInfo &I : CSI) {
1187         Register Reg = I.getReg();
1188         if (Reg > RestoreGPRs.LowGPR && Reg < RestoreGPRs.HighGPR)
1189           MIB.addReg(Reg, RegState::ImplicitDefine);
1190       }
1191     }
1192   }
1193 
1194   return true;
1195 }
1196 
1197 void SystemZXPLINKFrameLowering::emitPrologue(MachineFunction &MF,
1198                                               MachineBasicBlock &MBB) const {
1199   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
1200   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1201   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1202   MachineBasicBlock::iterator MBBI = MBB.begin();
1203   auto *ZII = static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
1204   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1205   MachineFrameInfo &MFFrame = MF.getFrameInfo();
1206   MachineInstr *StoreInstr = nullptr;
1207 
1208   determineFrameLayout(MF);
1209 
1210   bool HasFP = hasFP(MF);
1211   // Debug location must be unknown since the first debug location is used
1212   // to determine the end of the prologue.
1213   DebugLoc DL;
1214   uint64_t Offset = 0;
1215 
1216   const uint64_t StackSize = MFFrame.getStackSize();
1217 
1218   if (ZFI->getSpillGPRRegs().LowGPR) {
1219     // Skip over the GPR saves.
1220     if ((MBBI != MBB.end()) && ((MBBI->getOpcode() == SystemZ::STMG))) {
1221       const int Operand = 3;
1222       // Now we can set the offset for the operation, since now the Stack
1223       // has been finalized.
1224       Offset = Regs.getStackPointerBias() + MBBI->getOperand(Operand).getImm();
1225       // Maximum displacement for STMG instruction.
1226       if (isInt<20>(Offset - StackSize))
1227         Offset -= StackSize;
1228       else
1229         StoreInstr = &*MBBI;
1230       MBBI->getOperand(Operand).setImm(Offset);
1231       ++MBBI;
1232     } else
1233       llvm_unreachable("Couldn't skip over GPR saves");
1234   }
1235 
1236   if (StackSize) {
1237     MachineBasicBlock::iterator InsertPt = StoreInstr ? StoreInstr : MBBI;
1238     // Allocate StackSize bytes.
1239     int64_t Delta = -int64_t(StackSize);
1240 
1241     // In case the STM(G) instruction also stores SP (R4), but the displacement
1242     // is too large, the SP register is manipulated first before storing,
1243     // resulting in the wrong value stored and retrieved later. In this case, we
1244     // need to temporarily save the value of SP, and store it later to memory.
1245     if (StoreInstr && HasFP) {
1246       // Insert LR r0,r4 before STMG instruction.
1247       BuildMI(MBB, InsertPt, DL, ZII->get(SystemZ::LGR))
1248           .addReg(SystemZ::R0D, RegState::Define)
1249           .addReg(SystemZ::R4D);
1250       // Insert ST r0,xxx(,r4) after STMG instruction.
1251       BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::STG))
1252           .addReg(SystemZ::R0D, RegState::Kill)
1253           .addReg(SystemZ::R4D)
1254           .addImm(Offset)
1255           .addReg(0);
1256     }
1257 
1258     emitIncrement(MBB, InsertPt, DL, Regs.getStackPointerRegister(), Delta,
1259                   ZII);
1260 
1261     // If the requested stack size is larger than the guard page, then we need
1262     // to check if we need to call the stack extender. This requires adding a
1263     // conditional branch, but splitting the prologue block is not possible at
1264     // this point since it would invalidate the SaveBlocks / RestoreBlocks sets
1265     // of PEI in the single block function case. Build a pseudo to be handled
1266     // later by inlineStackProbe().
1267     const uint64_t GuardPageSize = 1024 * 1024;
1268     if (StackSize > GuardPageSize) {
1269       assert(StoreInstr && "Wrong insertion point");
1270       BuildMI(MBB, InsertPt, DL, ZII->get(SystemZ::XPLINK_STACKALLOC));
1271     }
1272   }
1273 
1274   if (HasFP) {
1275     // Copy the base of the frame to Frame Pointer Register.
1276     BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR),
1277             Regs.getFramePointerRegister())
1278         .addReg(Regs.getStackPointerRegister());
1279 
1280     // Mark the FramePtr as live at the beginning of every block except
1281     // the entry block.  (We'll have marked R8 as live on entry when
1282     // saving the GPRs.)
1283     for (MachineBasicBlock &B : llvm::drop_begin(MF))
1284       B.addLiveIn(Regs.getFramePointerRegister());
1285   }
1286 
1287   // Save GPRs used for varargs, if any.
1288   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1289   bool IsVarArg = MF.getFunction().isVarArg();
1290 
1291   if (IsVarArg) {
1292     // FixedRegs is the number of used registers, accounting for shadow
1293     // registers.
1294     unsigned FixedRegs = ZFI->getVarArgsFirstGPR() + ZFI->getVarArgsFirstFPR();
1295     auto &GPRs = SystemZ::XPLINK64ArgGPRs;
1296     for (unsigned I = FixedRegs; I < SystemZ::XPLINK64NumArgGPRs; I++) {
1297       uint64_t StartOffset = MFFrame.getOffsetAdjustment() +
1298                              MFFrame.getStackSize() + Regs.getCallFrameSize() +
1299                              getOffsetOfLocalArea() + I * 8;
1300       unsigned Reg = GPRs[I];
1301       BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STG))
1302           .addReg(Reg)
1303           .addReg(Regs.getStackPointerRegister())
1304           .addImm(StartOffset)
1305           .addReg(0);
1306       if (!MBB.isLiveIn(Reg))
1307         MBB.addLiveIn(Reg);
1308     }
1309   }
1310 }
1311 
1312 void SystemZXPLINKFrameLowering::emitEpilogue(MachineFunction &MF,
1313                                               MachineBasicBlock &MBB) const {
1314   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1315   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1316   SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
1317   MachineFrameInfo &MFFrame = MF.getFrameInfo();
1318   auto *ZII = static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
1319   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1320 
1321   // Skip the return instruction.
1322   assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
1323 
1324   uint64_t StackSize = MFFrame.getStackSize();
1325   if (StackSize) {
1326     unsigned SPReg = Regs.getStackPointerRegister();
1327     if (ZFI->getRestoreGPRRegs().LowGPR != SPReg) {
1328       DebugLoc DL = MBBI->getDebugLoc();
1329       emitIncrement(MBB, MBBI, DL, SPReg, StackSize, ZII);
1330     }
1331   }
1332 }
1333 
1334 // Emit a compare of the stack pointer against the stack floor, and a call to
1335 // the LE stack extender if needed.
1336 void SystemZXPLINKFrameLowering::inlineStackProbe(
1337     MachineFunction &MF, MachineBasicBlock &PrologMBB) const {
1338   auto *ZII =
1339       static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo());
1340 
1341   MachineInstr *StackAllocMI = nullptr;
1342   for (MachineInstr &MI : PrologMBB)
1343     if (MI.getOpcode() == SystemZ::XPLINK_STACKALLOC) {
1344       StackAllocMI = &MI;
1345       break;
1346     }
1347   if (StackAllocMI == nullptr)
1348     return;
1349 
1350   bool NeedSaveSP = hasFP(MF);
1351   bool NeedSaveArg = PrologMBB.isLiveIn(SystemZ::R3D);
1352   const int64_t SaveSlotR3 = 2192;
1353 
1354   MachineBasicBlock &MBB = PrologMBB;
1355   const DebugLoc DL = StackAllocMI->getDebugLoc();
1356 
1357   // The 2nd half of block MBB after split.
1358   MachineBasicBlock *NextMBB;
1359 
1360   // Add new basic block for the call to the stack overflow function.
1361   MachineBasicBlock *StackExtMBB =
1362       MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1363   MF.push_back(StackExtMBB);
1364 
1365   // LG r3,72(,r3)
1366   BuildMI(StackExtMBB, DL, ZII->get(SystemZ::LG), SystemZ::R3D)
1367       .addReg(SystemZ::R3D)
1368       .addImm(72)
1369       .addReg(0);
1370   // BASR r3,r3
1371   BuildMI(StackExtMBB, DL, ZII->get(SystemZ::CallBASR_STACKEXT))
1372       .addReg(SystemZ::R3D);
1373   if (NeedSaveArg) {
1374     if (!NeedSaveSP) {
1375       // LGR r0,r3
1376       BuildMI(MBB, StackAllocMI, DL, ZII->get(SystemZ::LGR))
1377           .addReg(SystemZ::R0D, RegState::Define)
1378           .addReg(SystemZ::R3D);
1379     } else {
1380       // In this case, the incoming value of r4 is saved in r0 so the
1381       // latter register is unavailable. Store r3 in its corresponding
1382       // slot in the parameter list instead. Do this at the start of
1383       // the prolog before r4 is manipulated by anything else.
1384       // STG r3, 2192(r4)
1385       BuildMI(MBB, MBB.begin(), DL, ZII->get(SystemZ::STG))
1386           .addReg(SystemZ::R3D)
1387           .addReg(SystemZ::R4D)
1388           .addImm(SaveSlotR3)
1389           .addReg(0);
1390     }
1391   }
1392   // LLGT r3,1208
1393   BuildMI(MBB, StackAllocMI, DL, ZII->get(SystemZ::LLGT), SystemZ::R3D)
1394       .addReg(0)
1395       .addImm(1208)
1396       .addReg(0);
1397   // CG r4,64(,r3)
1398   BuildMI(MBB, StackAllocMI, DL, ZII->get(SystemZ::CG))
1399       .addReg(SystemZ::R4D)
1400       .addReg(SystemZ::R3D)
1401       .addImm(64)
1402       .addReg(0);
1403   // JLL b'0100',F'37'
1404   BuildMI(MBB, StackAllocMI, DL, ZII->get(SystemZ::BRC))
1405       .addImm(SystemZ::CCMASK_ICMP)
1406       .addImm(SystemZ::CCMASK_CMP_LT)
1407       .addMBB(StackExtMBB);
1408 
1409   NextMBB = SystemZ::splitBlockBefore(StackAllocMI, &MBB);
1410   MBB.addSuccessor(NextMBB);
1411   MBB.addSuccessor(StackExtMBB);
1412   if (NeedSaveArg) {
1413     if (!NeedSaveSP) {
1414       // LGR r3, r0
1415       BuildMI(*NextMBB, StackAllocMI, DL, ZII->get(SystemZ::LGR))
1416           .addReg(SystemZ::R3D, RegState::Define)
1417           .addReg(SystemZ::R0D, RegState::Kill);
1418     } else {
1419       // In this case, the incoming value of r4 is saved in r0 so the
1420       // latter register is unavailable. We stored r3 in its corresponding
1421       // slot in the parameter list instead and we now restore it from there.
1422       // LGR r3, r0
1423       BuildMI(*NextMBB, StackAllocMI, DL, ZII->get(SystemZ::LGR))
1424           .addReg(SystemZ::R3D, RegState::Define)
1425           .addReg(SystemZ::R0D);
1426       // LG r3, 2192(r3)
1427       BuildMI(*NextMBB, StackAllocMI, DL, ZII->get(SystemZ::LG))
1428           .addReg(SystemZ::R3D, RegState::Define)
1429           .addReg(SystemZ::R3D)
1430           .addImm(SaveSlotR3)
1431           .addReg(0);
1432     }
1433   }
1434 
1435   // Add jump back from stack extension BB.
1436   BuildMI(StackExtMBB, DL, ZII->get(SystemZ::J)).addMBB(NextMBB);
1437   StackExtMBB->addSuccessor(NextMBB);
1438 
1439   StackAllocMI->eraseFromParent();
1440 
1441   // Compute the live-in lists for the new blocks.
1442   recomputeLiveIns(*NextMBB);
1443   recomputeLiveIns(*StackExtMBB);
1444 }
1445 
1446 bool SystemZXPLINKFrameLowering::hasFP(const MachineFunction &MF) const {
1447   return (MF.getFrameInfo().hasVarSizedObjects());
1448 }
1449 
1450 void SystemZXPLINKFrameLowering::processFunctionBeforeFrameFinalized(
1451     MachineFunction &MF, RegScavenger *RS) const {
1452   MachineFrameInfo &MFFrame = MF.getFrameInfo();
1453   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1454   auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
1455 
1456   // Setup stack frame offset
1457   MFFrame.setOffsetAdjustment(Regs.getStackPointerBias());
1458 
1459   // Nothing to do for leaf functions.
1460   uint64_t StackSize = MFFrame.estimateStackSize(MF);
1461   if (StackSize == 0 && MFFrame.getCalleeSavedInfo().empty())
1462     return;
1463 
1464   // Although the XPLINK specifications for AMODE64 state that minimum size
1465   // of the param area is minimum 32 bytes and no rounding is otherwise
1466   // specified, we round this area in 64 bytes increments to be compatible
1467   // with existing compilers.
1468   MFFrame.setMaxCallFrameSize(
1469       std::max(64U, (unsigned)alignTo(MFFrame.getMaxCallFrameSize(), 64)));
1470 }
1471 
1472 // Determines the size of the frame, and creates the deferred spill objects.
1473 void SystemZXPLINKFrameLowering::determineFrameLayout(
1474     MachineFunction &MF) const {
1475   MachineFrameInfo &MFFrame = MF.getFrameInfo();
1476   const SystemZSubtarget &Subtarget = MF.getSubtarget<SystemZSubtarget>();
1477   auto *Regs =
1478       static_cast<SystemZXPLINK64Registers *>(Subtarget.getSpecialRegisters());
1479 
1480   uint64_t StackSize = MFFrame.getStackSize();
1481   if (StackSize == 0)
1482     return;
1483 
1484   // Add the size of the register save area and the reserved area to the size.
1485   StackSize += Regs->getCallFrameSize();
1486   MFFrame.setStackSize(StackSize);
1487 
1488   // We now know the stack size. Create the fixed spill stack objects for the
1489   // register save area now. This has no impact on the stack frame layout, as
1490   // this is already computed. However, it makes sure that all callee saved
1491   // registers have a valid frame index assigned.
1492   const unsigned RegSize = MF.getDataLayout().getPointerSize();
1493   for (auto &CS : MFFrame.getCalleeSavedInfo()) {
1494     int Offset = RegSpillOffsets[CS.getReg()];
1495     if (Offset >= 0)
1496       CS.setFrameIdx(
1497           MFFrame.CreateFixedSpillStackObject(RegSize, Offset - StackSize));
1498   }
1499 }
1500