1 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
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 // This file contains the PPC implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCFrameLowering.h"
15 #include "PPCInstrBuilder.h"
16 #include "PPCInstrInfo.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Target/TargetOptions.h"
30 /// VRRegNo - Map from a numbered VR register to its enum value.
32 static const uint16_t VRRegNo[] = {
33 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
34 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
35 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
36 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
39 static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
40 if (STI.isDarwinABI())
41 return STI.isPPC64() ? 16 : 8;
43 return STI.isPPC64() ? 16 : 4;
46 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
47 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
48 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
49 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)) {}
51 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
52 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
53 unsigned &NumEntries) const {
54 if (Subtarget.isDarwinABI()) {
56 if (Subtarget.isPPC64()) {
57 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
58 return &darwin64Offsets;
60 static const SpillSlot darwinOffsets = {PPC::R31, -4};
61 return &darwinOffsets;
65 // Early exit if not using the SVR4 ABI.
66 if (!Subtarget.isSVR4ABI()) {
71 // Note that the offsets here overlap, but this is fixed up in
72 // processFunctionBeforeFrameFinalized.
74 static const SpillSlot Offsets[] = {
75 // Floating-point register save area offsets.
95 // General register save area offsets.
115 // CR save area offset. We map each of the nonvolatile CR fields
116 // to the slot for CR2, which is the first of the nonvolatile CR
117 // fields to be assigned, so that we only allocate one save slot.
118 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
121 // VRSAVE save area offset.
124 // Vector register save area
138 static const SpillSlot Offsets64[] = {
139 // Floating-point register save area offsets.
159 // General register save area offsets.
179 // VRSAVE save area offset.
182 // Vector register save area
196 if (Subtarget.isPPC64()) {
197 NumEntries = array_lengthof(Offsets64);
201 NumEntries = array_lengthof(Offsets);
207 /// RemoveVRSaveCode - We have found that this function does not need any code
208 /// to manipulate the VRSAVE register, even though it uses vector registers.
209 /// This can happen when the only registers used are known to be live in or out
210 /// of the function. Remove all of the VRSAVE related code from the function.
211 /// FIXME: The removal of the code results in a compile failure at -O0 when the
212 /// function contains a function call, as the GPR containing original VRSAVE
213 /// contents is spilled and reloaded around the call. Without the prolog code,
214 /// the spill instruction refers to an undefined register. This code needs
215 /// to account for all uses of that GPR.
216 static void RemoveVRSaveCode(MachineInstr *MI) {
217 MachineBasicBlock *Entry = MI->getParent();
218 MachineFunction *MF = Entry->getParent();
220 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
221 MachineBasicBlock::iterator MBBI = MI;
223 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
224 MBBI->eraseFromParent();
226 bool RemovedAllMTVRSAVEs = true;
227 // See if we can find and remove the MTVRSAVE instruction from all of the
229 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
230 // If last instruction is a return instruction, add an epilogue
231 if (!I->empty() && I->back().isReturn()) {
232 bool FoundIt = false;
233 for (MBBI = I->end(); MBBI != I->begin(); ) {
235 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
236 MBBI->eraseFromParent(); // remove it.
241 RemovedAllMTVRSAVEs &= FoundIt;
245 // If we found and removed all MTVRSAVE instructions, remove the read of
247 if (RemovedAllMTVRSAVEs) {
249 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
251 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
252 MBBI->eraseFromParent();
255 // Finally, nuke the UPDATE_VRSAVE.
256 MI->eraseFromParent();
259 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
260 // instruction selector. Based on the vector registers that have been used,
261 // transform this into the appropriate ORI instruction.
262 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
263 MachineFunction *MF = MI->getParent()->getParent();
264 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
265 DebugLoc dl = MI->getDebugLoc();
267 unsigned UsedRegMask = 0;
268 for (unsigned i = 0; i != 32; ++i)
269 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
270 UsedRegMask |= 1 << (31-i);
272 // Live in and live out values already must be in the mask, so don't bother
274 for (MachineRegisterInfo::livein_iterator
275 I = MF->getRegInfo().livein_begin(),
276 E = MF->getRegInfo().livein_end(); I != E; ++I) {
277 unsigned RegNo = TRI->getEncodingValue(I->first);
278 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
279 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
282 // Live out registers appear as use operands on return instructions.
283 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
284 UsedRegMask != 0 && BI != BE; ++BI) {
285 const MachineBasicBlock &MBB = *BI;
286 if (MBB.empty() || !MBB.back().isReturn())
288 const MachineInstr &Ret = MBB.back();
289 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
290 const MachineOperand &MO = Ret.getOperand(I);
291 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
293 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
294 UsedRegMask &= ~(1 << (31-RegNo));
298 // If no registers are used, turn this into a copy.
299 if (UsedRegMask == 0) {
300 // Remove all VRSAVE code.
301 RemoveVRSaveCode(MI);
305 unsigned SrcReg = MI->getOperand(1).getReg();
306 unsigned DstReg = MI->getOperand(0).getReg();
308 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
309 if (DstReg != SrcReg)
310 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
312 .addImm(UsedRegMask);
314 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
315 .addReg(SrcReg, RegState::Kill)
316 .addImm(UsedRegMask);
317 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
318 if (DstReg != SrcReg)
319 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
321 .addImm(UsedRegMask >> 16);
323 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
324 .addReg(SrcReg, RegState::Kill)
325 .addImm(UsedRegMask >> 16);
327 if (DstReg != SrcReg)
328 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
330 .addImm(UsedRegMask >> 16);
332 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
333 .addReg(SrcReg, RegState::Kill)
334 .addImm(UsedRegMask >> 16);
336 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
337 .addReg(DstReg, RegState::Kill)
338 .addImm(UsedRegMask & 0xFFFF);
341 // Remove the old UPDATE_VRSAVE instruction.
342 MI->eraseFromParent();
345 static bool spillsCR(const MachineFunction &MF) {
346 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
347 return FuncInfo->isCRSpilled();
350 static bool spillsVRSAVE(const MachineFunction &MF) {
351 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
352 return FuncInfo->isVRSAVESpilled();
355 static bool hasSpills(const MachineFunction &MF) {
356 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
357 return FuncInfo->hasSpills();
360 static bool hasNonRISpills(const MachineFunction &MF) {
361 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
362 return FuncInfo->hasNonRISpills();
365 /// MustSaveLR - Return true if this function requires that we save the LR
366 /// register onto the stack in the prolog and restore it in the epilog of the
368 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
369 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
371 // We need a save/restore of LR if there is any def of LR (which is
372 // defined by calls, including the PIC setup sequence), or if there is
373 // some use of the LR stack slot (e.g. for builtin_return_address).
374 // (LR comes in 32 and 64 bit versions.)
375 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
376 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
379 /// determineFrameLayout - Determine the size of the frame and maximum call
381 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
383 bool UseEstimate) const {
384 MachineFrameInfo *MFI = MF.getFrameInfo();
386 // Get the number of bytes to allocate from the FrameInfo
388 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
390 // Get stack alignments. The frame must be aligned to the greatest of these:
391 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
392 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
393 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
395 const PPCRegisterInfo *RegInfo =
396 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
398 // If we are a leaf function, and use up to 224 bytes of stack space,
399 // don't have a frame pointer, calls, or dynamic alloca then we do not need
400 // to adjust the stack pointer (we fit in the Red Zone).
401 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
402 // stackless code if all local vars are reg-allocated.
403 bool DisableRedZone = MF.getFunction()->getAttributes().
404 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
405 unsigned LR = RegInfo->getRARegister();
406 if (!DisableRedZone &&
407 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
408 !Subtarget.isSVR4ABI() || // allocated locals.
410 FrameSize <= 224 && // Fits in red zone.
411 !MFI->hasVarSizedObjects() && // No dynamic alloca.
412 !MFI->adjustsStack() && // No calls.
413 !MustSaveLR(MF, LR) &&
414 !RegInfo->hasBasePointer(MF)) { // No special alignment.
417 MFI->setStackSize(0);
421 // Get the maximum call frame size of all the calls.
422 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
424 // Maximum call frame needs to be at least big enough for linkage area.
425 unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
426 Subtarget.isDarwinABI(),
427 Subtarget.isELFv2ABI());
428 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
430 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
431 // that allocations will be aligned.
432 if (MFI->hasVarSizedObjects())
433 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
435 // Update maximum call frame size.
437 MFI->setMaxCallFrameSize(maxCallFrameSize);
439 // Include call frame size in total.
440 FrameSize += maxCallFrameSize;
442 // Make sure the frame is aligned.
443 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
445 // Update frame info.
447 MFI->setStackSize(FrameSize);
452 // hasFP - Return true if the specified function actually has a dedicated frame
454 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
455 const MachineFrameInfo *MFI = MF.getFrameInfo();
456 // FIXME: This is pretty much broken by design: hasFP() might be called really
457 // early, before the stack layout was calculated and thus hasFP() might return
458 // true or false here depending on the time of call.
459 return (MFI->getStackSize()) && needsFP(MF);
462 // needsFP - Return true if the specified function should have a dedicated frame
463 // pointer register. This is true if the function has variable sized allocas or
464 // if frame pointer elimination is disabled.
465 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
466 const MachineFrameInfo *MFI = MF.getFrameInfo();
468 // Naked functions have no stack frame pushed, so we don't have a frame
470 if (MF.getFunction()->getAttributes().hasAttribute(
471 AttributeSet::FunctionIndex, Attribute::Naked))
474 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
475 MFI->hasVarSizedObjects() ||
476 MFI->hasStackMap() || MFI->hasPatchPoint() ||
477 (MF.getTarget().Options.GuaranteedTailCallOpt &&
478 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
481 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
482 bool is31 = needsFP(MF);
483 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
484 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
486 const PPCRegisterInfo *RegInfo =
487 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
488 bool HasBP = RegInfo->hasBasePointer(MF);
489 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
490 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
492 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
494 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
496 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
497 MachineOperand &MO = MBBI->getOperand(I);
501 switch (MO.getReg()) {
520 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
521 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
522 MachineBasicBlock::iterator MBBI = MBB.begin();
523 MachineFrameInfo *MFI = MF.getFrameInfo();
524 const PPCInstrInfo &TII =
525 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
526 const PPCRegisterInfo *RegInfo =
527 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
529 MachineModuleInfo &MMI = MF.getMMI();
530 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
532 bool needsCFI = MMI.hasDebugInfo() ||
533 MF.getFunction()->needsUnwindTableEntry();
534 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
536 // Get processor type.
537 bool isPPC64 = Subtarget.isPPC64();
539 bool isDarwinABI = Subtarget.isDarwinABI();
540 bool isSVR4ABI = Subtarget.isSVR4ABI();
541 bool isELFv2ABI = Subtarget.isELFv2ABI();
542 assert((isDarwinABI || isSVR4ABI) &&
543 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
545 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
548 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
549 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
550 HandleVRSaveUpdate(MBBI, TII);
555 // Move MBBI back to the beginning of the function.
558 // Work out frame sizes.
559 unsigned FrameSize = determineFrameLayout(MF);
560 int NegFrameSize = -FrameSize;
561 if (!isInt<32>(NegFrameSize))
562 llvm_unreachable("Unhandled stack size!");
564 if (MFI->isFrameAddressTaken())
565 replaceFPWithRealFP(MF);
567 // Check if the link register (LR) must be saved.
568 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
569 bool MustSaveLR = FI->mustSaveLR();
570 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
571 // Do we have a frame pointer and/or base pointer for this function?
572 bool HasFP = hasFP(MF);
573 bool HasBP = RegInfo->hasBasePointer(MF);
575 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
576 unsigned BPReg = RegInfo->getBaseRegister(MF);
577 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
578 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
579 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
580 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
581 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
582 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
584 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
586 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
588 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
590 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
592 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
594 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
596 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
598 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
601 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
602 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
603 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
604 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
605 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
606 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
608 int LROffset = getReturnSaveOffset();
613 MachineFrameInfo *FFI = MF.getFrameInfo();
614 int FPIndex = FI->getFramePointerSaveIndex();
615 assert(FPIndex && "No Frame Pointer Save Slot!");
616 FPOffset = FFI->getObjectOffset(FPIndex);
619 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
626 MachineFrameInfo *FFI = MF.getFrameInfo();
627 int BPIndex = FI->getBasePointerSaveIndex();
628 assert(BPIndex && "No Base Pointer Save Slot!");
629 BPOffset = FFI->getObjectOffset(BPIndex);
632 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
639 if (FI->usesPICBase()) {
640 MachineFrameInfo *FFI = MF.getFrameInfo();
641 int PBPIndex = FI->getPICBasePointerSaveIndex();
642 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
643 PBPOffset = FFI->getObjectOffset(PBPIndex);
646 // Get stack alignments.
647 unsigned MaxAlign = MFI->getMaxAlignment();
648 if (HasBP && MaxAlign > 1)
649 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
650 "Invalid alignment!");
652 // Frames of 32KB & larger require special handling because they cannot be
653 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
654 bool isLargeFrame = !isInt<16>(NegFrameSize);
657 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
659 assert((isPPC64 || MustSaveCRs.empty()) &&
660 "Prologue CR saving supported only in 64-bit mode");
662 if (!MustSaveCRs.empty()) { // will only occur for PPC64
663 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
664 // If only one or two CR fields are clobbered, it could be more
665 // efficient to use mfocrf to selectively save just those fields.
666 MachineInstrBuilder MIB =
667 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
668 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
669 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
673 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
674 BuildMI(MBB, MBBI, dl, StoreInst)
679 if (FI->usesPICBase())
680 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
681 BuildMI(MBB, MBBI, dl, StoreInst)
687 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
688 BuildMI(MBB, MBBI, dl, StoreInst)
694 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
695 BuildMI(MBB, MBBI, dl, StoreInst)
700 if (!MustSaveCRs.empty()) // will only occur for PPC64
701 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
702 .addReg(TempReg, getKillRegState(true))
706 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
707 if (!FrameSize) return;
709 // Adjust stack pointer: r1 += NegFrameSize.
710 // If there is a preferred stack alignment, align R1 now
713 // Save a copy of r1 as the base pointer.
714 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
719 if (HasBP && MaxAlign > 1) {
721 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
724 .addImm(64 - Log2_32(MaxAlign));
726 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
729 .addImm(32 - Log2_32(MaxAlign))
732 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
733 .addReg(ScratchReg, RegState::Kill)
734 .addImm(NegFrameSize);
736 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
737 .addImm(NegFrameSize >> 16);
738 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
739 .addReg(TempReg, RegState::Kill)
740 .addImm(NegFrameSize & 0xFFFF);
741 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
742 .addReg(ScratchReg, RegState::Kill)
743 .addReg(TempReg, RegState::Kill);
745 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
746 .addReg(SPReg, RegState::Kill)
750 } else if (!isLargeFrame) {
751 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
753 .addImm(NegFrameSize)
757 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
758 .addImm(NegFrameSize >> 16);
759 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
760 .addReg(ScratchReg, RegState::Kill)
761 .addImm(NegFrameSize & 0xFFFF);
762 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
763 .addReg(SPReg, RegState::Kill)
768 // Add Call Frame Information for the instructions we generated above.
773 // Define CFA in terms of BP. Do this in preference to using FP/SP,
774 // because if the stack needed aligning then CFA won't be at a fixed
775 // offset from FP/SP.
776 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
777 CFIIndex = MMI.addFrameInst(
778 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
780 // Adjust the definition of CFA to account for the change in SP.
781 assert(NegFrameSize);
782 CFIIndex = MMI.addFrameInst(
783 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
785 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
786 .addCFIIndex(CFIIndex);
789 // Describe where FP was saved, at a fixed offset from CFA.
790 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
791 CFIIndex = MMI.addFrameInst(
792 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
793 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
794 .addCFIIndex(CFIIndex);
797 if (FI->usesPICBase()) {
798 // Describe where FP was saved, at a fixed offset from CFA.
799 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
800 CFIIndex = MMI.addFrameInst(
801 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
802 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
803 .addCFIIndex(CFIIndex);
807 // Describe where BP was saved, at a fixed offset from CFA.
808 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
809 CFIIndex = MMI.addFrameInst(
810 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
811 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
812 .addCFIIndex(CFIIndex);
816 // Describe where LR was saved, at a fixed offset from CFA.
817 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
818 CFIIndex = MMI.addFrameInst(
819 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
820 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
821 .addCFIIndex(CFIIndex);
825 // If there is a frame pointer, copy R1 into R31
827 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
831 if (!HasBP && needsCFI) {
832 // Change the definition of CFA from SP+offset to FP+offset, because SP
833 // will change at every alloca.
834 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
835 unsigned CFIIndex = MMI.addFrameInst(
836 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
838 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
839 .addCFIIndex(CFIIndex);
844 // Describe where callee saved registers were saved, at fixed offsets from
846 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
847 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
848 unsigned Reg = CSI[I].getReg();
849 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
851 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
852 // subregisters of CR2. We just need to emit a move of CR2.
853 if (PPC::CRBITRCRegClass.contains(Reg))
856 // For SVR4, don't emit a move for the CR spill slot if we haven't
858 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
859 && MustSaveCRs.empty())
862 // For 64-bit SVR4 when we have spilled CRs, the spill location
863 // is SP+8, not a frame-relative slot.
864 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
865 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
866 // the whole CR word. In the ELFv2 ABI, every CR that was
867 // actually saved gets its own CFI record.
868 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
869 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
870 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
871 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
872 .addCFIIndex(CFIIndex);
876 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
877 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
878 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
879 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
880 .addCFIIndex(CFIIndex);
885 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
886 MachineBasicBlock &MBB) const {
887 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
888 assert(MBBI != MBB.end() && "Returning block has no terminator");
889 const PPCInstrInfo &TII =
890 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
891 const PPCRegisterInfo *RegInfo =
892 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
894 unsigned RetOpcode = MBBI->getOpcode();
897 assert((RetOpcode == PPC::BLR ||
898 RetOpcode == PPC::BLR8 ||
899 RetOpcode == PPC::TCRETURNri ||
900 RetOpcode == PPC::TCRETURNdi ||
901 RetOpcode == PPC::TCRETURNai ||
902 RetOpcode == PPC::TCRETURNri8 ||
903 RetOpcode == PPC::TCRETURNdi8 ||
904 RetOpcode == PPC::TCRETURNai8) &&
905 "Can only insert epilog into returning blocks");
907 // Get alignment info so we know how to restore the SP.
908 const MachineFrameInfo *MFI = MF.getFrameInfo();
910 // Get the number of bytes allocated from the FrameInfo.
911 int FrameSize = MFI->getStackSize();
913 // Get processor type.
914 bool isPPC64 = Subtarget.isPPC64();
916 bool isDarwinABI = Subtarget.isDarwinABI();
917 bool isSVR4ABI = Subtarget.isSVR4ABI();
918 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
920 // Check if the link register (LR) has been saved.
921 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
922 bool MustSaveLR = FI->mustSaveLR();
923 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
924 // Do we have a frame pointer and/or base pointer for this function?
925 bool HasFP = hasFP(MF);
926 bool HasBP = RegInfo->hasBasePointer(MF);
928 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
929 unsigned BPReg = RegInfo->getBaseRegister(MF);
930 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
931 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
932 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
933 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
935 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
937 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
939 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
941 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
943 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
946 int LROffset = getReturnSaveOffset();
951 MachineFrameInfo *FFI = MF.getFrameInfo();
952 int FPIndex = FI->getFramePointerSaveIndex();
953 assert(FPIndex && "No Frame Pointer Save Slot!");
954 FPOffset = FFI->getObjectOffset(FPIndex);
957 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
964 MachineFrameInfo *FFI = MF.getFrameInfo();
965 int BPIndex = FI->getBasePointerSaveIndex();
966 assert(BPIndex && "No Base Pointer Save Slot!");
967 BPOffset = FFI->getObjectOffset(BPIndex);
970 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
977 if (FI->usesPICBase()) {
978 MachineFrameInfo *FFI = MF.getFrameInfo();
979 int PBPIndex = FI->getPICBasePointerSaveIndex();
980 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
981 PBPOffset = FFI->getObjectOffset(PBPIndex);
984 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
985 RetOpcode == PPC::TCRETURNdi ||
986 RetOpcode == PPC::TCRETURNai ||
987 RetOpcode == PPC::TCRETURNri8 ||
988 RetOpcode == PPC::TCRETURNdi8 ||
989 RetOpcode == PPC::TCRETURNai8;
992 int MaxTCRetDelta = FI->getTailCallSPDelta();
993 MachineOperand &StackAdjust = MBBI->getOperand(1);
994 assert(StackAdjust.isImm() && "Expecting immediate value.");
995 // Adjust stack pointer.
996 int StackAdj = StackAdjust.getImm();
997 int Delta = StackAdj - MaxTCRetDelta;
998 assert((Delta >= 0) && "Delta must be positive");
1000 FrameSize += (StackAdj +Delta);
1002 FrameSize += StackAdj;
1005 // Frames of 32KB & larger require special handling because they cannot be
1006 // indexed into with a simple LD/LWZ immediate offset operand.
1007 bool isLargeFrame = !isInt<16>(FrameSize);
1010 // In the prologue, the loaded (or persistent) stack pointer value is offset
1011 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
1013 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1014 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1015 // call which invalidates the stack pointer value in SP(0). So we use the
1016 // value of R31 in this case.
1017 if (FI->hasFastCall()) {
1018 assert(HasFP && "Expecting a valid frame pointer.");
1019 if (!isLargeFrame) {
1020 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1021 .addReg(FPReg).addImm(FrameSize);
1023 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1024 .addImm(FrameSize >> 16);
1025 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1026 .addReg(ScratchReg, RegState::Kill)
1027 .addImm(FrameSize & 0xFFFF);
1028 BuildMI(MBB, MBBI, dl, AddInst)
1031 .addReg(ScratchReg);
1033 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1034 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1038 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1046 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1050 assert((isPPC64 || MustSaveCRs.empty()) &&
1051 "Epilogue CR restoring supported only in 64-bit mode");
1053 if (!MustSaveCRs.empty()) // will only occur for PPC64
1054 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1059 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1063 if (FI->usesPICBase())
1064 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1065 BuildMI(MBB, MBBI, dl, LoadInst)
1071 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1075 if (!MustSaveCRs.empty()) // will only occur for PPC64
1076 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1077 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1078 .addReg(TempReg, getKillRegState(i == e-1));
1081 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1083 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1084 // call optimization
1085 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1086 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1087 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1088 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1089 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1091 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1092 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1093 .addReg(SPReg).addImm(CallerAllocatedAmt);
1095 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1096 .addImm(CallerAllocatedAmt >> 16);
1097 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1098 .addReg(ScratchReg, RegState::Kill)
1099 .addImm(CallerAllocatedAmt & 0xFFFF);
1100 BuildMI(MBB, MBBI, dl, AddInst)
1103 .addReg(ScratchReg);
1105 } else if (RetOpcode == PPC::TCRETURNdi) {
1106 MBBI = MBB.getLastNonDebugInstr();
1107 MachineOperand &JumpTarget = MBBI->getOperand(0);
1108 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1109 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1110 } else if (RetOpcode == PPC::TCRETURNri) {
1111 MBBI = MBB.getLastNonDebugInstr();
1112 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1113 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1114 } else if (RetOpcode == PPC::TCRETURNai) {
1115 MBBI = MBB.getLastNonDebugInstr();
1116 MachineOperand &JumpTarget = MBBI->getOperand(0);
1117 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1118 } else if (RetOpcode == PPC::TCRETURNdi8) {
1119 MBBI = MBB.getLastNonDebugInstr();
1120 MachineOperand &JumpTarget = MBBI->getOperand(0);
1121 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1122 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1123 } else if (RetOpcode == PPC::TCRETURNri8) {
1124 MBBI = MBB.getLastNonDebugInstr();
1125 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1126 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1127 } else if (RetOpcode == PPC::TCRETURNai8) {
1128 MBBI = MBB.getLastNonDebugInstr();
1129 MachineOperand &JumpTarget = MBBI->getOperand(0);
1130 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1135 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1136 RegScavenger *) const {
1137 const PPCRegisterInfo *RegInfo =
1138 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1140 // Save and clear the LR state.
1141 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1142 unsigned LR = RegInfo->getRARegister();
1143 FI->setMustSaveLR(MustSaveLR(MF, LR));
1144 MachineRegisterInfo &MRI = MF.getRegInfo();
1145 MRI.setPhysRegUnused(LR);
1147 // Save R31 if necessary
1148 int FPSI = FI->getFramePointerSaveIndex();
1149 bool isPPC64 = Subtarget.isPPC64();
1150 bool isDarwinABI = Subtarget.isDarwinABI();
1151 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1152 MachineFrameInfo *MFI = MF.getFrameInfo();
1154 // If the frame pointer save index hasn't been defined yet.
1155 if (!FPSI && needsFP(MF)) {
1156 // Find out what the fix offset of the frame pointer save area.
1157 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1158 // Allocate the frame index for frame pointer save area.
1159 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1161 FI->setFramePointerSaveIndex(FPSI);
1164 int BPSI = FI->getBasePointerSaveIndex();
1165 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1166 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1167 // Allocate the frame index for the base pointer save area.
1168 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1170 FI->setBasePointerSaveIndex(BPSI);
1173 // Reserve stack space for the PIC Base register (R30).
1174 // Only used in SVR4 32-bit.
1175 if (FI->usesPICBase()) {
1176 int PBPSI = FI->getPICBasePointerSaveIndex();
1177 PBPSI = MFI->CreateFixedObject(4, -8, true);
1178 FI->setPICBasePointerSaveIndex(PBPSI);
1181 // Reserve stack space to move the linkage area to in case of a tail call.
1183 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1184 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1185 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1188 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1189 // function uses CR 2, 3, or 4.
1190 if (!isPPC64 && !isDarwinABI &&
1191 (MRI.isPhysRegUsed(PPC::CR2) ||
1192 MRI.isPhysRegUsed(PPC::CR3) ||
1193 MRI.isPhysRegUsed(PPC::CR4))) {
1194 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1195 FI->setCRSpillFrameIndex(FrameIdx);
1199 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1200 RegScavenger *RS) const {
1201 // Early exit if not using the SVR4 ABI.
1202 if (!Subtarget.isSVR4ABI()) {
1203 addScavengingSpillSlot(MF, RS);
1207 // Get callee saved register information.
1208 MachineFrameInfo *FFI = MF.getFrameInfo();
1209 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1211 // Early exit if no callee saved registers are modified!
1212 if (CSI.empty() && !needsFP(MF)) {
1213 addScavengingSpillSlot(MF, RS);
1217 unsigned MinGPR = PPC::R31;
1218 unsigned MinG8R = PPC::X31;
1219 unsigned MinFPR = PPC::F31;
1220 unsigned MinVR = PPC::V31;
1222 bool HasGPSaveArea = false;
1223 bool HasG8SaveArea = false;
1224 bool HasFPSaveArea = false;
1225 bool HasVRSAVESaveArea = false;
1226 bool HasVRSaveArea = false;
1228 SmallVector<CalleeSavedInfo, 18> GPRegs;
1229 SmallVector<CalleeSavedInfo, 18> G8Regs;
1230 SmallVector<CalleeSavedInfo, 18> FPRegs;
1231 SmallVector<CalleeSavedInfo, 18> VRegs;
1233 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1234 unsigned Reg = CSI[i].getReg();
1235 if (PPC::GPRCRegClass.contains(Reg)) {
1236 HasGPSaveArea = true;
1238 GPRegs.push_back(CSI[i]);
1243 } else if (PPC::G8RCRegClass.contains(Reg)) {
1244 HasG8SaveArea = true;
1246 G8Regs.push_back(CSI[i]);
1251 } else if (PPC::F8RCRegClass.contains(Reg)) {
1252 HasFPSaveArea = true;
1254 FPRegs.push_back(CSI[i]);
1259 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1260 PPC::CRRCRegClass.contains(Reg)) {
1261 ; // do nothing, as we already know whether CRs are spilled
1262 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1263 HasVRSAVESaveArea = true;
1264 } else if (PPC::VRRCRegClass.contains(Reg)) {
1265 HasVRSaveArea = true;
1267 VRegs.push_back(CSI[i]);
1273 llvm_unreachable("Unknown RegisterClass!");
1277 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1278 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1280 int64_t LowerBound = 0;
1282 // Take into account stack space reserved for tail calls.
1284 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1285 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1286 LowerBound = TCSPDelta;
1289 // The Floating-point register save area is right below the back chain word
1290 // of the previous stack frame.
1291 if (HasFPSaveArea) {
1292 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1293 int FI = FPRegs[i].getFrameIdx();
1295 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1298 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1301 // Check whether the frame pointer register is allocated. If so, make sure it
1302 // is spilled to the correct offset.
1304 HasGPSaveArea = true;
1306 int FI = PFI->getFramePointerSaveIndex();
1307 assert(FI && "No Frame Pointer Save Slot!");
1309 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1312 if (PFI->usesPICBase()) {
1313 HasGPSaveArea = true;
1315 int FI = PFI->getPICBasePointerSaveIndex();
1316 assert(FI && "No PIC Base Pointer Save Slot!");
1318 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1321 const PPCRegisterInfo *RegInfo =
1322 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1323 if (RegInfo->hasBasePointer(MF)) {
1324 HasGPSaveArea = true;
1326 int FI = PFI->getBasePointerSaveIndex();
1327 assert(FI && "No Base Pointer Save Slot!");
1329 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1332 // General register save area starts right below the Floating-point
1333 // register save area.
1334 if (HasGPSaveArea || HasG8SaveArea) {
1335 // Move general register save area spill slots down, taking into account
1336 // the size of the Floating-point register save area.
1337 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1338 int FI = GPRegs[i].getFrameIdx();
1340 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1343 // Move general register save area spill slots down, taking into account
1344 // the size of the Floating-point register save area.
1345 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1346 int FI = G8Regs[i].getFrameIdx();
1348 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1352 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1353 TRI->getEncodingValue(MinG8R));
1355 if (Subtarget.isPPC64()) {
1356 LowerBound -= (31 - MinReg + 1) * 8;
1358 LowerBound -= (31 - MinReg + 1) * 4;
1362 // For 32-bit only, the CR save area is below the general register
1363 // save area. For 64-bit SVR4, the CR save area is addressed relative
1364 // to the stack pointer and hence does not need an adjustment here.
1365 // Only CR2 (the first nonvolatile spilled) has an associated frame
1366 // index so that we have a single uniform save area.
1367 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1368 // Adjust the frame index of the CR spill slot.
1369 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1370 unsigned Reg = CSI[i].getReg();
1372 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1373 // Leave Darwin logic as-is.
1374 || (!Subtarget.isSVR4ABI() &&
1375 (PPC::CRBITRCRegClass.contains(Reg) ||
1376 PPC::CRRCRegClass.contains(Reg)))) {
1377 int FI = CSI[i].getFrameIdx();
1379 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1383 LowerBound -= 4; // The CR save area is always 4 bytes long.
1386 if (HasVRSAVESaveArea) {
1387 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1388 // which have the VRSAVE register class?
1389 // Adjust the frame index of the VRSAVE spill slot.
1390 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1391 unsigned Reg = CSI[i].getReg();
1393 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1394 int FI = CSI[i].getFrameIdx();
1396 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1400 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1403 if (HasVRSaveArea) {
1404 // Insert alignment padding, we need 16-byte alignment.
1405 LowerBound = (LowerBound - 15) & ~(15);
1407 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1408 int FI = VRegs[i].getFrameIdx();
1410 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1414 addScavengingSpillSlot(MF, RS);
1418 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1419 RegScavenger *RS) const {
1420 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1421 // a large stack, which will require scavenging a register to materialize a
1424 // We need to have a scavenger spill slot for spills if the frame size is
1425 // large. In case there is no free register for large-offset addressing,
1426 // this slot is used for the necessary emergency spill. Also, we need the
1427 // slot for dynamic stack allocations.
1429 // The scavenger might be invoked if the frame offset does not fit into
1430 // the 16-bit immediate. We don't know the complete frame size here
1431 // because we've not yet computed callee-saved register spills or the
1432 // needed alignment padding.
1433 unsigned StackSize = determineFrameLayout(MF, false, true);
1434 MachineFrameInfo *MFI = MF.getFrameInfo();
1435 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1436 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1437 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1438 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1439 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1440 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1444 // Might we have over-aligned allocas?
1445 bool HasAlVars = MFI->hasVarSizedObjects() &&
1446 MFI->getMaxAlignment() > getStackAlignment();
1448 // These kinds of spills might need two registers.
1449 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1450 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1458 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1459 MachineBasicBlock::iterator MI,
1460 const std::vector<CalleeSavedInfo> &CSI,
1461 const TargetRegisterInfo *TRI) const {
1463 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1464 // Return false otherwise to maintain pre-existing behavior.
1465 if (!Subtarget.isSVR4ABI())
1468 MachineFunction *MF = MBB.getParent();
1469 const PPCInstrInfo &TII =
1470 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1472 bool CRSpilled = false;
1473 MachineInstrBuilder CRMIB;
1475 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1476 unsigned Reg = CSI[i].getReg();
1477 // Only Darwin actually uses the VRSAVE register, but it can still appear
1478 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1479 // Darwin, ignore it.
1480 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1483 // CR2 through CR4 are the nonvolatile CR fields.
1484 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1486 // Add the callee-saved register as live-in; it's killed at the spill.
1489 if (CRSpilled && IsCRField) {
1490 CRMIB.addReg(Reg, RegState::ImplicitKill);
1494 // Insert the spill to the stack frame.
1496 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1497 if (Subtarget.isPPC64()) {
1498 // The actual spill will happen at the start of the prologue.
1499 FuncInfo->addMustSaveCR(Reg);
1502 FuncInfo->setSpillsCR();
1504 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1505 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1506 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1507 .addReg(Reg, RegState::ImplicitKill);
1509 MBB.insert(MI, CRMIB);
1510 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1512 getKillRegState(true)),
1513 CSI[i].getFrameIdx()));
1516 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1517 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1518 CSI[i].getFrameIdx(), RC, TRI);
1525 restoreCRs(bool isPPC64, bool is31,
1526 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1527 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1528 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1530 MachineFunction *MF = MBB.getParent();
1531 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1533 unsigned RestoreOp, MoveReg;
1536 // This is handled during epilogue generation.
1539 // 32-bit: FP-relative
1540 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1542 CSI[CSIIndex].getFrameIdx()));
1543 RestoreOp = PPC::MTOCRF;
1548 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1549 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1552 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1553 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1556 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1557 .addReg(MoveReg, getKillRegState(true)));
1560 void PPCFrameLowering::
1561 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1562 MachineBasicBlock::iterator I) const {
1563 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1564 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1565 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1566 // Add (actually subtract) back the amount the callee popped on return.
1567 if (int CalleeAmt = I->getOperand(1).getImm()) {
1568 bool is64Bit = Subtarget.isPPC64();
1570 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1571 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1572 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1573 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1574 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1575 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1576 MachineInstr *MI = I;
1577 DebugLoc dl = MI->getDebugLoc();
1579 if (isInt<16>(CalleeAmt)) {
1580 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1581 .addReg(StackReg, RegState::Kill)
1584 MachineBasicBlock::iterator MBBI = I;
1585 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1586 .addImm(CalleeAmt >> 16);
1587 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1588 .addReg(TmpReg, RegState::Kill)
1589 .addImm(CalleeAmt & 0xFFFF);
1590 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1591 .addReg(StackReg, RegState::Kill)
1596 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1601 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1602 MachineBasicBlock::iterator MI,
1603 const std::vector<CalleeSavedInfo> &CSI,
1604 const TargetRegisterInfo *TRI) const {
1606 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1607 // Return false otherwise to maintain pre-existing behavior.
1608 if (!Subtarget.isSVR4ABI())
1611 MachineFunction *MF = MBB.getParent();
1612 const PPCInstrInfo &TII =
1613 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1614 bool CR2Spilled = false;
1615 bool CR3Spilled = false;
1616 bool CR4Spilled = false;
1617 unsigned CSIIndex = 0;
1619 // Initialize insertion-point logic; we will be restoring in reverse
1621 MachineBasicBlock::iterator I = MI, BeforeI = I;
1622 bool AtStart = I == MBB.begin();
1627 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1628 unsigned Reg = CSI[i].getReg();
1630 // Only Darwin actually uses the VRSAVE register, but it can still appear
1631 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1632 // Darwin, ignore it.
1633 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1636 if (Reg == PPC::CR2) {
1638 // The spill slot is associated only with CR2, which is the
1639 // first nonvolatile spilled. Save it here.
1642 } else if (Reg == PPC::CR3) {
1645 } else if (Reg == PPC::CR4) {
1649 // When we first encounter a non-CR register after seeing at
1650 // least one CR register, restore all spilled CRs together.
1651 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1652 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1653 bool is31 = needsFP(*MF);
1654 restoreCRs(Subtarget.isPPC64(), is31,
1655 CR2Spilled, CR3Spilled, CR4Spilled,
1656 MBB, I, CSI, CSIIndex);
1657 CR2Spilled = CR3Spilled = CR4Spilled = false;
1660 // Default behavior for non-CR saves.
1661 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1662 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1664 assert(I != MBB.begin() &&
1665 "loadRegFromStackSlot didn't insert any code!");
1668 // Insert in reverse order.
1677 // If we haven't yet spilled the CRs, do so now.
1678 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1679 bool is31 = needsFP(*MF);
1680 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1681 MBB, I, CSI, CSIIndex);