1 //===-- SystemZFrameLowering.cpp - Frame lowering for SystemZ -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "SystemZFrameLowering.h"
11 #include "SystemZCallingConv.h"
12 #include "SystemZInstrBuilder.h"
13 #include "SystemZInstrInfo.h"
14 #include "SystemZMachineFunctionInfo.h"
15 #include "SystemZRegisterInfo.h"
16 #include "SystemZSubtarget.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/RegisterScavenging.h"
20 #include "llvm/IR/Function.h"
25 // The ABI-defined register save slots, relative to the incoming stack
27 static const TargetFrameLowering::SpillSlot SpillOffsetTable[] = {
28 { SystemZ::R2D, 0x10 },
29 { SystemZ::R3D, 0x18 },
30 { SystemZ::R4D, 0x20 },
31 { SystemZ::R5D, 0x28 },
32 { SystemZ::R6D, 0x30 },
33 { SystemZ::R7D, 0x38 },
34 { SystemZ::R8D, 0x40 },
35 { SystemZ::R9D, 0x48 },
36 { SystemZ::R10D, 0x50 },
37 { SystemZ::R11D, 0x58 },
38 { SystemZ::R12D, 0x60 },
39 { SystemZ::R13D, 0x68 },
40 { SystemZ::R14D, 0x70 },
41 { SystemZ::R15D, 0x78 },
42 { SystemZ::F0D, 0x80 },
43 { SystemZ::F2D, 0x88 },
44 { SystemZ::F4D, 0x90 },
45 { SystemZ::F6D, 0x98 }
47 } // end anonymous namespace
49 SystemZFrameLowering::SystemZFrameLowering()
50 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 8,
51 -SystemZMC::CallFrameSize, 8) {
52 // Create a mapping from register number to save slot offset.
53 RegSpillOffsets.grow(SystemZ::NUM_TARGET_REGS);
54 for (unsigned I = 0, E = array_lengthof(SpillOffsetTable); I != E; ++I)
55 RegSpillOffsets[SpillOffsetTable[I].Reg] = SpillOffsetTable[I].Offset;
58 const TargetFrameLowering::SpillSlot *
59 SystemZFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
60 NumEntries = array_lengthof(SpillOffsetTable);
61 return SpillOffsetTable;
64 void SystemZFrameLowering::
65 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
66 RegScavenger *RS) const {
67 MachineFrameInfo *MFFrame = MF.getFrameInfo();
68 MachineRegisterInfo &MRI = MF.getRegInfo();
69 const TargetRegisterInfo *TRI =
70 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
71 bool HasFP = hasFP(MF);
72 SystemZMachineFunctionInfo *MFI = MF.getInfo<SystemZMachineFunctionInfo>();
73 bool IsVarArg = MF.getFunction()->isVarArg();
75 // va_start stores incoming FPR varargs in the normal way, but delegates
76 // the saving of incoming GPR varargs to spillCalleeSavedRegisters().
77 // Record these pending uses, which typically include the call-saved
78 // argument register R6D.
80 for (unsigned I = MFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
81 MRI.setPhysRegUsed(SystemZ::ArgGPRs[I]);
83 // If the function requires a frame pointer, record that the hard
84 // frame pointer will be clobbered.
86 MRI.setPhysRegUsed(SystemZ::R11D);
88 // If the function calls other functions, record that the return
89 // address register will be clobbered.
90 if (MFFrame->hasCalls())
91 MRI.setPhysRegUsed(SystemZ::R14D);
93 // If we are saving GPRs other than the stack pointer, we might as well
94 // save and restore the stack pointer at the same time, via STMG and LMG.
95 // This allows the deallocation to be done by the LMG, rather than needing
96 // a separate %r15 addition.
97 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
98 for (unsigned I = 0; CSRegs[I]; ++I) {
99 unsigned Reg = CSRegs[I];
100 if (SystemZ::GR64BitRegClass.contains(Reg) && MRI.isPhysRegUsed(Reg)) {
101 MRI.setPhysRegUsed(SystemZ::R15D);
107 // Add GPR64 to the save instruction being built by MIB, which is in basic
108 // block MBB. IsImplicit says whether this is an explicit operand to the
109 // instruction, or an implicit one that comes between the explicit start
110 // and end registers.
111 static void addSavedGPR(MachineBasicBlock &MBB, MachineInstrBuilder &MIB,
112 unsigned GPR64, bool IsImplicit) {
113 const TargetRegisterInfo *RI =
114 MBB.getParent()->getTarget().getSubtargetImpl()->getRegisterInfo();
115 unsigned GPR32 = RI->getSubReg(GPR64, SystemZ::subreg_l32);
116 bool IsLive = MBB.isLiveIn(GPR64) || MBB.isLiveIn(GPR32);
117 if (!IsLive || !IsImplicit) {
118 MIB.addReg(GPR64, getImplRegState(IsImplicit) | getKillRegState(!IsLive));
120 MBB.addLiveIn(GPR64);
124 bool SystemZFrameLowering::
125 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator MBBI,
127 const std::vector<CalleeSavedInfo> &CSI,
128 const TargetRegisterInfo *TRI) const {
132 MachineFunction &MF = *MBB.getParent();
133 const TargetInstrInfo *TII =
134 MF.getTarget().getSubtargetImpl()->getInstrInfo();
135 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
136 bool IsVarArg = MF.getFunction()->isVarArg();
137 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
139 // Scan the call-saved GPRs and find the bounds of the register spill area.
141 unsigned HighGPR = SystemZ::R15D;
142 unsigned StartOffset = -1U;
143 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
144 unsigned Reg = CSI[I].getReg();
145 if (SystemZ::GR64BitRegClass.contains(Reg)) {
146 unsigned Offset = RegSpillOffsets[Reg];
147 assert(Offset && "Unexpected GPR save");
148 if (StartOffset > Offset) {
150 StartOffset = Offset;
155 // Save the range of call-saved registers, for use by the epilogue inserter.
156 ZFI->setLowSavedGPR(LowGPR);
157 ZFI->setHighSavedGPR(HighGPR);
159 // Include the GPR varargs, if any. R6D is call-saved, so would
160 // be included by the loop above, but we also need to handle the
161 // call-clobbered argument registers.
163 unsigned FirstGPR = ZFI->getVarArgsFirstGPR();
164 if (FirstGPR < SystemZ::NumArgGPRs) {
165 unsigned Reg = SystemZ::ArgGPRs[FirstGPR];
166 unsigned Offset = RegSpillOffsets[Reg];
167 if (StartOffset > Offset) {
168 LowGPR = Reg; StartOffset = Offset;
175 assert(LowGPR != HighGPR && "Should be saving %r15 and something else");
177 // Build an STMG instruction.
178 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::STMG));
180 // Add the explicit register operands.
181 addSavedGPR(MBB, MIB, LowGPR, false);
182 addSavedGPR(MBB, MIB, HighGPR, false);
185 MIB.addReg(SystemZ::R15D).addImm(StartOffset);
187 // Make sure all call-saved GPRs are included as operands and are
188 // marked as live on entry.
189 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
190 unsigned Reg = CSI[I].getReg();
191 if (SystemZ::GR64BitRegClass.contains(Reg))
192 addSavedGPR(MBB, MIB, Reg, true);
195 // ...likewise GPR varargs.
197 for (unsigned I = ZFI->getVarArgsFirstGPR(); I < SystemZ::NumArgGPRs; ++I)
198 addSavedGPR(MBB, MIB, SystemZ::ArgGPRs[I], true);
201 // Save FPRs in the normal TargetInstrInfo way.
202 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
203 unsigned Reg = CSI[I].getReg();
204 if (SystemZ::FP64BitRegClass.contains(Reg)) {
206 TII->storeRegToStackSlot(MBB, MBBI, Reg, true, CSI[I].getFrameIdx(),
207 &SystemZ::FP64BitRegClass, TRI);
214 bool SystemZFrameLowering::
215 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
216 MachineBasicBlock::iterator MBBI,
217 const std::vector<CalleeSavedInfo> &CSI,
218 const TargetRegisterInfo *TRI) const {
222 MachineFunction &MF = *MBB.getParent();
223 const TargetInstrInfo *TII =
224 MF.getTarget().getSubtargetImpl()->getInstrInfo();
225 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
226 bool HasFP = hasFP(MF);
227 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
229 // Restore FPRs in the normal TargetInstrInfo way.
230 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
231 unsigned Reg = CSI[I].getReg();
232 if (SystemZ::FP64BitRegClass.contains(Reg))
233 TII->loadRegFromStackSlot(MBB, MBBI, Reg, CSI[I].getFrameIdx(),
234 &SystemZ::FP64BitRegClass, TRI);
237 // Restore call-saved GPRs (but not call-clobbered varargs, which at
238 // this point might hold return values).
239 unsigned LowGPR = ZFI->getLowSavedGPR();
240 unsigned HighGPR = ZFI->getHighSavedGPR();
241 unsigned StartOffset = RegSpillOffsets[LowGPR];
243 // If we saved any of %r2-%r5 as varargs, we should also be saving
244 // and restoring %r6. If we're saving %r6 or above, we should be
246 assert(LowGPR != HighGPR && "Should be loading %r15 and something else");
248 // Build an LMG instruction.
249 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(SystemZ::LMG));
251 // Add the explicit register operands.
252 MIB.addReg(LowGPR, RegState::Define);
253 MIB.addReg(HighGPR, RegState::Define);
256 MIB.addReg(HasFP ? SystemZ::R11D : SystemZ::R15D);
257 MIB.addImm(StartOffset);
259 // Do a second scan adding regs as being defined by instruction
260 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
261 unsigned Reg = CSI[I].getReg();
262 if (Reg != LowGPR && Reg != HighGPR)
263 MIB.addReg(Reg, RegState::ImplicitDefine);
270 void SystemZFrameLowering::
271 processFunctionBeforeFrameFinalized(MachineFunction &MF,
272 RegScavenger *RS) const {
273 MachineFrameInfo *MFFrame = MF.getFrameInfo();
274 uint64_t MaxReach = (MFFrame->estimateStackSize(MF) +
275 SystemZMC::CallFrameSize * 2);
276 if (!isUInt<12>(MaxReach)) {
277 // We may need register scavenging slots if some parts of the frame
278 // are outside the reach of an unsigned 12-bit displacement.
279 // Create 2 for the case where both addresses in an MVC are
281 RS->addScavengingFrameIndex(MFFrame->CreateStackObject(8, 8, false));
282 RS->addScavengingFrameIndex(MFFrame->CreateStackObject(8, 8, false));
286 // Emit instructions before MBBI (in MBB) to add NumBytes to Reg.
287 static void emitIncrement(MachineBasicBlock &MBB,
288 MachineBasicBlock::iterator &MBBI,
290 unsigned Reg, int64_t NumBytes,
291 const TargetInstrInfo *TII) {
294 int64_t ThisVal = NumBytes;
295 if (isInt<16>(NumBytes))
296 Opcode = SystemZ::AGHI;
298 Opcode = SystemZ::AGFI;
299 // Make sure we maintain 8-byte stack alignment.
300 int64_t MinVal = -int64_t(1) << 31;
301 int64_t MaxVal = (int64_t(1) << 31) - 8;
302 if (ThisVal < MinVal)
304 else if (ThisVal > MaxVal)
307 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII->get(Opcode), Reg)
308 .addReg(Reg).addImm(ThisVal);
309 // The CC implicit def is dead.
310 MI->getOperand(3).setIsDead();
315 void SystemZFrameLowering::emitPrologue(MachineFunction &MF) const {
316 MachineBasicBlock &MBB = MF.front();
317 MachineFrameInfo *MFFrame = MF.getFrameInfo();
318 auto *ZII = static_cast<const SystemZInstrInfo *>(
319 MF.getTarget().getSubtargetImpl()->getInstrInfo());
320 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
321 MachineBasicBlock::iterator MBBI = MBB.begin();
322 MachineModuleInfo &MMI = MF.getMMI();
323 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
324 const std::vector<CalleeSavedInfo> &CSI = MFFrame->getCalleeSavedInfo();
325 bool HasFP = hasFP(MF);
326 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
328 // The current offset of the stack pointer from the CFA.
329 int64_t SPOffsetFromCFA = -SystemZMC::CFAOffsetFromInitialSP;
331 if (ZFI->getLowSavedGPR()) {
332 // Skip over the GPR saves.
333 if (MBBI != MBB.end() && MBBI->getOpcode() == SystemZ::STMG)
336 llvm_unreachable("Couldn't skip over GPR saves");
338 // Add CFI for the GPR saves.
339 for (auto &Save : CSI) {
340 unsigned Reg = Save.getReg();
341 if (SystemZ::GR64BitRegClass.contains(Reg)) {
342 int64_t Offset = SPOffsetFromCFA + RegSpillOffsets[Reg];
343 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
344 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
345 BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
346 .addCFIIndex(CFIIndex);
351 uint64_t StackSize = getAllocatedStackSize(MF);
353 // Allocate StackSize bytes.
354 int64_t Delta = -int64_t(StackSize);
355 emitIncrement(MBB, MBBI, DL, SystemZ::R15D, Delta, ZII);
357 // Add CFI for the allocation.
358 unsigned CFIIndex = MMI.addFrameInst(
359 MCCFIInstruction::createDefCfaOffset(nullptr, SPOffsetFromCFA + Delta));
360 BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
361 .addCFIIndex(CFIIndex);
362 SPOffsetFromCFA += Delta;
366 // Copy the base of the frame to R11.
367 BuildMI(MBB, MBBI, DL, ZII->get(SystemZ::LGR), SystemZ::R11D)
368 .addReg(SystemZ::R15D);
370 // Add CFI for the new frame location.
371 unsigned HardFP = MRI->getDwarfRegNum(SystemZ::R11D, true);
372 unsigned CFIIndex = MMI.addFrameInst(
373 MCCFIInstruction::createDefCfaRegister(nullptr, HardFP));
374 BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
375 .addCFIIndex(CFIIndex);
377 // Mark the FramePtr as live at the beginning of every block except
378 // the entry block. (We'll have marked R11 as live on entry when
380 for (auto I = std::next(MF.begin()), E = MF.end(); I != E; ++I)
381 I->addLiveIn(SystemZ::R11D);
384 // Skip over the FPR saves.
385 SmallVector<unsigned, 8> CFIIndexes;
386 for (auto &Save : CSI) {
387 unsigned Reg = Save.getReg();
388 if (SystemZ::FP64BitRegClass.contains(Reg)) {
389 if (MBBI != MBB.end() &&
390 (MBBI->getOpcode() == SystemZ::STD ||
391 MBBI->getOpcode() == SystemZ::STDY))
394 llvm_unreachable("Couldn't skip over FPR save");
396 // Add CFI for the this save.
397 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
398 int64_t Offset = getFrameIndexOffset(MF, Save.getFrameIdx());
399 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
400 nullptr, DwarfReg, SPOffsetFromCFA + Offset));
401 CFIIndexes.push_back(CFIIndex);
404 // Complete the CFI for the FPR saves, modelling them as taking effect
405 // after the last save.
406 for (auto CFIIndex : CFIIndexes) {
407 BuildMI(MBB, MBBI, DL, ZII->get(TargetOpcode::CFI_INSTRUCTION))
408 .addCFIIndex(CFIIndex);
412 void SystemZFrameLowering::emitEpilogue(MachineFunction &MF,
413 MachineBasicBlock &MBB) const {
414 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
415 auto *ZII = static_cast<const SystemZInstrInfo *>(
416 MF.getTarget().getSubtargetImpl()->getInstrInfo());
417 SystemZMachineFunctionInfo *ZFI = MF.getInfo<SystemZMachineFunctionInfo>();
419 // Skip the return instruction.
420 assert(MBBI->isReturn() && "Can only insert epilogue into returning blocks");
422 uint64_t StackSize = getAllocatedStackSize(MF);
423 if (ZFI->getLowSavedGPR()) {
425 unsigned Opcode = MBBI->getOpcode();
426 if (Opcode != SystemZ::LMG)
427 llvm_unreachable("Expected to see callee-save register restore code");
429 unsigned AddrOpNo = 2;
430 DebugLoc DL = MBBI->getDebugLoc();
431 uint64_t Offset = StackSize + MBBI->getOperand(AddrOpNo + 1).getImm();
432 unsigned NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
434 // If the offset is too large, use the largest stack-aligned offset
435 // and add the rest to the base register (the stack or frame pointer).
437 uint64_t NumBytes = Offset - 0x7fff8;
438 emitIncrement(MBB, MBBI, DL, MBBI->getOperand(AddrOpNo).getReg(),
441 NewOpcode = ZII->getOpcodeForOffset(Opcode, Offset);
442 assert(NewOpcode && "No restore instruction available");
445 MBBI->setDesc(ZII->get(NewOpcode));
446 MBBI->getOperand(AddrOpNo + 1).ChangeToImmediate(Offset);
447 } else if (StackSize) {
448 DebugLoc DL = MBBI->getDebugLoc();
449 emitIncrement(MBB, MBBI, DL, SystemZ::R15D, StackSize, ZII);
453 bool SystemZFrameLowering::hasFP(const MachineFunction &MF) const {
454 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
455 MF.getFrameInfo()->hasVarSizedObjects() ||
456 MF.getInfo<SystemZMachineFunctionInfo>()->getManipulatesSP());
459 int SystemZFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
461 const MachineFrameInfo *MFFrame = MF.getFrameInfo();
463 // Start with the offset of FI from the top of the caller-allocated frame
464 // (i.e. the top of the 160 bytes allocated by the caller). This initial
465 // offset is therefore negative.
466 int64_t Offset = (MFFrame->getObjectOffset(FI) +
467 MFFrame->getOffsetAdjustment());
469 // Make the offset relative to the incoming stack pointer.
470 Offset -= getOffsetOfLocalArea();
472 // Make the offset relative to the bottom of the frame.
473 Offset += getAllocatedStackSize(MF);
478 uint64_t SystemZFrameLowering::
479 getAllocatedStackSize(const MachineFunction &MF) const {
480 const MachineFrameInfo *MFFrame = MF.getFrameInfo();
482 // Start with the size of the local variables and spill slots.
483 uint64_t StackSize = MFFrame->getStackSize();
485 // We need to allocate the ABI-defined 160-byte base area whenever
486 // we allocate stack space for our own use and whenever we call another
488 if (StackSize || MFFrame->hasVarSizedObjects() || MFFrame->hasCalls())
489 StackSize += SystemZMC::CallFrameSize;
495 SystemZFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
496 // The ABI requires us to allocate 160 bytes of stack space for the callee,
497 // with any outgoing stack arguments being placed above that. It seems
498 // better to make that area a permanent feature of the frame even if
499 // we're using a frame pointer.
503 void SystemZFrameLowering::
504 eliminateCallFramePseudoInstr(MachineFunction &MF,
505 MachineBasicBlock &MBB,
506 MachineBasicBlock::iterator MI) const {
507 switch (MI->getOpcode()) {
508 case SystemZ::ADJCALLSTACKDOWN:
509 case SystemZ::ADJCALLSTACKUP:
510 assert(hasReservedCallFrame(MF) &&
511 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
516 llvm_unreachable("Unexpected call frame instruction");