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 static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
47 return STI.isELFv2ABI() ? 24 : 40;
50 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
51 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
52 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
53 Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
54 TOCSaveOffset(computeTOCSaveOffset(Subtarget)) {}
56 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
57 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
58 unsigned &NumEntries) const {
59 if (Subtarget.isDarwinABI()) {
61 if (Subtarget.isPPC64()) {
62 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
63 return &darwin64Offsets;
65 static const SpillSlot darwinOffsets = {PPC::R31, -4};
66 return &darwinOffsets;
70 // Early exit if not using the SVR4 ABI.
71 if (!Subtarget.isSVR4ABI()) {
76 // Note that the offsets here overlap, but this is fixed up in
77 // processFunctionBeforeFrameFinalized.
79 static const SpillSlot Offsets[] = {
80 // Floating-point register save area offsets.
100 // General register save area offsets.
120 // CR save area offset. We map each of the nonvolatile CR fields
121 // to the slot for CR2, which is the first of the nonvolatile CR
122 // fields to be assigned, so that we only allocate one save slot.
123 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
126 // VRSAVE save area offset.
129 // Vector register save area
143 static const SpillSlot Offsets64[] = {
144 // Floating-point register save area offsets.
164 // General register save area offsets.
184 // VRSAVE save area offset.
187 // Vector register save area
201 if (Subtarget.isPPC64()) {
202 NumEntries = array_lengthof(Offsets64);
206 NumEntries = array_lengthof(Offsets);
212 /// RemoveVRSaveCode - We have found that this function does not need any code
213 /// to manipulate the VRSAVE register, even though it uses vector registers.
214 /// This can happen when the only registers used are known to be live in or out
215 /// of the function. Remove all of the VRSAVE related code from the function.
216 /// FIXME: The removal of the code results in a compile failure at -O0 when the
217 /// function contains a function call, as the GPR containing original VRSAVE
218 /// contents is spilled and reloaded around the call. Without the prolog code,
219 /// the spill instruction refers to an undefined register. This code needs
220 /// to account for all uses of that GPR.
221 static void RemoveVRSaveCode(MachineInstr *MI) {
222 MachineBasicBlock *Entry = MI->getParent();
223 MachineFunction *MF = Entry->getParent();
225 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
226 MachineBasicBlock::iterator MBBI = MI;
228 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
229 MBBI->eraseFromParent();
231 bool RemovedAllMTVRSAVEs = true;
232 // See if we can find and remove the MTVRSAVE instruction from all of the
234 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
235 // If last instruction is a return instruction, add an epilogue
236 if (!I->empty() && I->back().isReturn()) {
237 bool FoundIt = false;
238 for (MBBI = I->end(); MBBI != I->begin(); ) {
240 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
241 MBBI->eraseFromParent(); // remove it.
246 RemovedAllMTVRSAVEs &= FoundIt;
250 // If we found and removed all MTVRSAVE instructions, remove the read of
252 if (RemovedAllMTVRSAVEs) {
254 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
256 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
257 MBBI->eraseFromParent();
260 // Finally, nuke the UPDATE_VRSAVE.
261 MI->eraseFromParent();
264 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
265 // instruction selector. Based on the vector registers that have been used,
266 // transform this into the appropriate ORI instruction.
267 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
268 MachineFunction *MF = MI->getParent()->getParent();
269 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
270 DebugLoc dl = MI->getDebugLoc();
272 unsigned UsedRegMask = 0;
273 for (unsigned i = 0; i != 32; ++i)
274 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
275 UsedRegMask |= 1 << (31-i);
277 // Live in and live out values already must be in the mask, so don't bother
279 for (MachineRegisterInfo::livein_iterator
280 I = MF->getRegInfo().livein_begin(),
281 E = MF->getRegInfo().livein_end(); I != E; ++I) {
282 unsigned RegNo = TRI->getEncodingValue(I->first);
283 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
284 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
287 // Live out registers appear as use operands on return instructions.
288 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
289 UsedRegMask != 0 && BI != BE; ++BI) {
290 const MachineBasicBlock &MBB = *BI;
291 if (MBB.empty() || !MBB.back().isReturn())
293 const MachineInstr &Ret = MBB.back();
294 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
295 const MachineOperand &MO = Ret.getOperand(I);
296 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
298 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
299 UsedRegMask &= ~(1 << (31-RegNo));
303 // If no registers are used, turn this into a copy.
304 if (UsedRegMask == 0) {
305 // Remove all VRSAVE code.
306 RemoveVRSaveCode(MI);
310 unsigned SrcReg = MI->getOperand(1).getReg();
311 unsigned DstReg = MI->getOperand(0).getReg();
313 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
314 if (DstReg != SrcReg)
315 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
317 .addImm(UsedRegMask);
319 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
320 .addReg(SrcReg, RegState::Kill)
321 .addImm(UsedRegMask);
322 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
323 if (DstReg != SrcReg)
324 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
326 .addImm(UsedRegMask >> 16);
328 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
329 .addReg(SrcReg, RegState::Kill)
330 .addImm(UsedRegMask >> 16);
332 if (DstReg != SrcReg)
333 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
335 .addImm(UsedRegMask >> 16);
337 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
338 .addReg(SrcReg, RegState::Kill)
339 .addImm(UsedRegMask >> 16);
341 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
342 .addReg(DstReg, RegState::Kill)
343 .addImm(UsedRegMask & 0xFFFF);
346 // Remove the old UPDATE_VRSAVE instruction.
347 MI->eraseFromParent();
350 static bool spillsCR(const MachineFunction &MF) {
351 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
352 return FuncInfo->isCRSpilled();
355 static bool spillsVRSAVE(const MachineFunction &MF) {
356 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
357 return FuncInfo->isVRSAVESpilled();
360 static bool hasSpills(const MachineFunction &MF) {
361 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
362 return FuncInfo->hasSpills();
365 static bool hasNonRISpills(const MachineFunction &MF) {
366 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
367 return FuncInfo->hasNonRISpills();
370 /// MustSaveLR - Return true if this function requires that we save the LR
371 /// register onto the stack in the prolog and restore it in the epilog of the
373 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
374 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
376 // We need a save/restore of LR if there is any def of LR (which is
377 // defined by calls, including the PIC setup sequence), or if there is
378 // some use of the LR stack slot (e.g. for builtin_return_address).
379 // (LR comes in 32 and 64 bit versions.)
380 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
381 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
384 /// determineFrameLayout - Determine the size of the frame and maximum call
386 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
388 bool UseEstimate) const {
389 MachineFrameInfo *MFI = MF.getFrameInfo();
391 // Get the number of bytes to allocate from the FrameInfo
393 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
395 // Get stack alignments. The frame must be aligned to the greatest of these:
396 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
397 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
398 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
400 const PPCRegisterInfo *RegInfo =
401 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
403 // If we are a leaf function, and use up to 224 bytes of stack space,
404 // don't have a frame pointer, calls, or dynamic alloca then we do not need
405 // to adjust the stack pointer (we fit in the Red Zone).
406 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
407 // stackless code if all local vars are reg-allocated.
408 bool DisableRedZone = MF.getFunction()->getAttributes().
409 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
410 unsigned LR = RegInfo->getRARegister();
411 if (!DisableRedZone &&
412 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
413 !Subtarget.isSVR4ABI() || // allocated locals.
415 FrameSize <= 224 && // Fits in red zone.
416 !MFI->hasVarSizedObjects() && // No dynamic alloca.
417 !MFI->adjustsStack() && // No calls.
418 !MustSaveLR(MF, LR) &&
419 !RegInfo->hasBasePointer(MF)) { // No special alignment.
422 MFI->setStackSize(0);
426 // Get the maximum call frame size of all the calls.
427 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
429 // Maximum call frame needs to be at least big enough for linkage area.
430 unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
431 Subtarget.isDarwinABI(),
432 Subtarget.isELFv2ABI());
433 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
435 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
436 // that allocations will be aligned.
437 if (MFI->hasVarSizedObjects())
438 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
440 // Update maximum call frame size.
442 MFI->setMaxCallFrameSize(maxCallFrameSize);
444 // Include call frame size in total.
445 FrameSize += maxCallFrameSize;
447 // Make sure the frame is aligned.
448 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
450 // Update frame info.
452 MFI->setStackSize(FrameSize);
457 // hasFP - Return true if the specified function actually has a dedicated frame
459 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
460 const MachineFrameInfo *MFI = MF.getFrameInfo();
461 // FIXME: This is pretty much broken by design: hasFP() might be called really
462 // early, before the stack layout was calculated and thus hasFP() might return
463 // true or false here depending on the time of call.
464 return (MFI->getStackSize()) && needsFP(MF);
467 // needsFP - Return true if the specified function should have a dedicated frame
468 // pointer register. This is true if the function has variable sized allocas or
469 // if frame pointer elimination is disabled.
470 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
471 const MachineFrameInfo *MFI = MF.getFrameInfo();
473 // Naked functions have no stack frame pushed, so we don't have a frame
475 if (MF.getFunction()->getAttributes().hasAttribute(
476 AttributeSet::FunctionIndex, Attribute::Naked))
479 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
480 MFI->hasVarSizedObjects() ||
481 MFI->hasStackMap() || MFI->hasPatchPoint() ||
482 (MF.getTarget().Options.GuaranteedTailCallOpt &&
483 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
486 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
487 bool is31 = needsFP(MF);
488 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
489 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
491 const PPCRegisterInfo *RegInfo =
492 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
493 bool HasBP = RegInfo->hasBasePointer(MF);
494 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
495 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
497 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
499 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
501 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
502 MachineOperand &MO = MBBI->getOperand(I);
506 switch (MO.getReg()) {
525 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
526 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
527 MachineBasicBlock::iterator MBBI = MBB.begin();
528 MachineFrameInfo *MFI = MF.getFrameInfo();
529 const PPCInstrInfo &TII =
530 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
531 const PPCRegisterInfo *RegInfo =
532 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
534 MachineModuleInfo &MMI = MF.getMMI();
535 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
537 bool needsCFI = MMI.hasDebugInfo() ||
538 MF.getFunction()->needsUnwindTableEntry();
539 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
541 // Get processor type.
542 bool isPPC64 = Subtarget.isPPC64();
544 bool isDarwinABI = Subtarget.isDarwinABI();
545 bool isSVR4ABI = Subtarget.isSVR4ABI();
546 bool isELFv2ABI = Subtarget.isELFv2ABI();
547 assert((isDarwinABI || isSVR4ABI) &&
548 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
550 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
553 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
554 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
555 HandleVRSaveUpdate(MBBI, TII);
560 // Move MBBI back to the beginning of the function.
563 // Work out frame sizes.
564 unsigned FrameSize = determineFrameLayout(MF);
565 int NegFrameSize = -FrameSize;
566 if (!isInt<32>(NegFrameSize))
567 llvm_unreachable("Unhandled stack size!");
569 if (MFI->isFrameAddressTaken())
570 replaceFPWithRealFP(MF);
572 // Check if the link register (LR) must be saved.
573 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
574 bool MustSaveLR = FI->mustSaveLR();
575 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
576 // Do we have a frame pointer and/or base pointer for this function?
577 bool HasFP = hasFP(MF);
578 bool HasBP = RegInfo->hasBasePointer(MF);
580 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
581 unsigned BPReg = RegInfo->getBaseRegister(MF);
582 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
583 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
584 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
585 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
586 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
587 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
589 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
591 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
593 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
595 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
597 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
599 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
601 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
603 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
606 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
607 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
608 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
609 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
610 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
611 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
613 int LROffset = getReturnSaveOffset();
618 MachineFrameInfo *FFI = MF.getFrameInfo();
619 int FPIndex = FI->getFramePointerSaveIndex();
620 assert(FPIndex && "No Frame Pointer Save Slot!");
621 FPOffset = FFI->getObjectOffset(FPIndex);
624 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
631 MachineFrameInfo *FFI = MF.getFrameInfo();
632 int BPIndex = FI->getBasePointerSaveIndex();
633 assert(BPIndex && "No Base Pointer Save Slot!");
634 BPOffset = FFI->getObjectOffset(BPIndex);
637 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
644 if (FI->usesPICBase()) {
645 MachineFrameInfo *FFI = MF.getFrameInfo();
646 int PBPIndex = FI->getPICBasePointerSaveIndex();
647 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
648 PBPOffset = FFI->getObjectOffset(PBPIndex);
651 // Get stack alignments.
652 unsigned MaxAlign = MFI->getMaxAlignment();
653 if (HasBP && MaxAlign > 1)
654 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
655 "Invalid alignment!");
657 // Frames of 32KB & larger require special handling because they cannot be
658 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
659 bool isLargeFrame = !isInt<16>(NegFrameSize);
662 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
664 assert((isPPC64 || MustSaveCRs.empty()) &&
665 "Prologue CR saving supported only in 64-bit mode");
667 if (!MustSaveCRs.empty()) { // will only occur for PPC64
668 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
669 // If only one or two CR fields are clobbered, it could be more
670 // efficient to use mfocrf to selectively save just those fields.
671 MachineInstrBuilder MIB =
672 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
673 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
674 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
678 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
679 BuildMI(MBB, MBBI, dl, StoreInst)
684 if (FI->usesPICBase())
685 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
686 BuildMI(MBB, MBBI, dl, StoreInst)
692 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
693 BuildMI(MBB, MBBI, dl, StoreInst)
699 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
700 BuildMI(MBB, MBBI, dl, StoreInst)
705 if (!MustSaveCRs.empty()) // will only occur for PPC64
706 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
707 .addReg(TempReg, getKillRegState(true))
711 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
712 if (!FrameSize) return;
714 // Adjust stack pointer: r1 += NegFrameSize.
715 // If there is a preferred stack alignment, align R1 now
718 // Save a copy of r1 as the base pointer.
719 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
724 if (HasBP && MaxAlign > 1) {
726 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
729 .addImm(64 - Log2_32(MaxAlign));
731 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
734 .addImm(32 - Log2_32(MaxAlign))
737 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
738 .addReg(ScratchReg, RegState::Kill)
739 .addImm(NegFrameSize);
741 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
742 .addImm(NegFrameSize >> 16);
743 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
744 .addReg(TempReg, RegState::Kill)
745 .addImm(NegFrameSize & 0xFFFF);
746 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
747 .addReg(ScratchReg, RegState::Kill)
748 .addReg(TempReg, RegState::Kill);
750 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
751 .addReg(SPReg, RegState::Kill)
755 } else if (!isLargeFrame) {
756 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
758 .addImm(NegFrameSize)
762 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
763 .addImm(NegFrameSize >> 16);
764 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
765 .addReg(ScratchReg, RegState::Kill)
766 .addImm(NegFrameSize & 0xFFFF);
767 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
768 .addReg(SPReg, RegState::Kill)
773 // Add Call Frame Information for the instructions we generated above.
778 // Define CFA in terms of BP. Do this in preference to using FP/SP,
779 // because if the stack needed aligning then CFA won't be at a fixed
780 // offset from FP/SP.
781 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
782 CFIIndex = MMI.addFrameInst(
783 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
785 // Adjust the definition of CFA to account for the change in SP.
786 assert(NegFrameSize);
787 CFIIndex = MMI.addFrameInst(
788 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
790 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
791 .addCFIIndex(CFIIndex);
794 // Describe where FP was saved, at a fixed offset from CFA.
795 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
796 CFIIndex = MMI.addFrameInst(
797 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
798 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
799 .addCFIIndex(CFIIndex);
802 if (FI->usesPICBase()) {
803 // Describe where FP was saved, at a fixed offset from CFA.
804 unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
805 CFIIndex = MMI.addFrameInst(
806 MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
807 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
808 .addCFIIndex(CFIIndex);
812 // Describe where BP was saved, at a fixed offset from CFA.
813 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
814 CFIIndex = MMI.addFrameInst(
815 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
816 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
817 .addCFIIndex(CFIIndex);
821 // Describe where LR was saved, at a fixed offset from CFA.
822 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
823 CFIIndex = MMI.addFrameInst(
824 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
825 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
826 .addCFIIndex(CFIIndex);
830 // If there is a frame pointer, copy R1 into R31
832 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
836 if (!HasBP && needsCFI) {
837 // Change the definition of CFA from SP+offset to FP+offset, because SP
838 // will change at every alloca.
839 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
840 unsigned CFIIndex = MMI.addFrameInst(
841 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
843 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
844 .addCFIIndex(CFIIndex);
849 // Describe where callee saved registers were saved, at fixed offsets from
851 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
852 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
853 unsigned Reg = CSI[I].getReg();
854 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
856 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
857 // subregisters of CR2. We just need to emit a move of CR2.
858 if (PPC::CRBITRCRegClass.contains(Reg))
861 // For SVR4, don't emit a move for the CR spill slot if we haven't
863 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
864 && MustSaveCRs.empty())
867 // For 64-bit SVR4 when we have spilled CRs, the spill location
868 // is SP+8, not a frame-relative slot.
869 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
870 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
871 // the whole CR word. In the ELFv2 ABI, every CR that was
872 // actually saved gets its own CFI record.
873 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
874 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
875 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
876 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
877 .addCFIIndex(CFIIndex);
881 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
882 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
883 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
884 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
885 .addCFIIndex(CFIIndex);
890 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
891 MachineBasicBlock &MBB) const {
892 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
893 assert(MBBI != MBB.end() && "Returning block has no terminator");
894 const PPCInstrInfo &TII =
895 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
896 const PPCRegisterInfo *RegInfo =
897 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
899 unsigned RetOpcode = MBBI->getOpcode();
902 assert((RetOpcode == PPC::BLR ||
903 RetOpcode == PPC::BLR8 ||
904 RetOpcode == PPC::TCRETURNri ||
905 RetOpcode == PPC::TCRETURNdi ||
906 RetOpcode == PPC::TCRETURNai ||
907 RetOpcode == PPC::TCRETURNri8 ||
908 RetOpcode == PPC::TCRETURNdi8 ||
909 RetOpcode == PPC::TCRETURNai8) &&
910 "Can only insert epilog into returning blocks");
912 // Get alignment info so we know how to restore the SP.
913 const MachineFrameInfo *MFI = MF.getFrameInfo();
915 // Get the number of bytes allocated from the FrameInfo.
916 int FrameSize = MFI->getStackSize();
918 // Get processor type.
919 bool isPPC64 = Subtarget.isPPC64();
921 bool isDarwinABI = Subtarget.isDarwinABI();
922 bool isSVR4ABI = Subtarget.isSVR4ABI();
923 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
925 // Check if the link register (LR) has been saved.
926 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
927 bool MustSaveLR = FI->mustSaveLR();
928 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
929 // Do we have a frame pointer and/or base pointer for this function?
930 bool HasFP = hasFP(MF);
931 bool HasBP = RegInfo->hasBasePointer(MF);
933 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
934 unsigned BPReg = RegInfo->getBaseRegister(MF);
935 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
936 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
937 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
938 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
940 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
942 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
944 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
946 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
948 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
951 int LROffset = getReturnSaveOffset();
956 MachineFrameInfo *FFI = MF.getFrameInfo();
957 int FPIndex = FI->getFramePointerSaveIndex();
958 assert(FPIndex && "No Frame Pointer Save Slot!");
959 FPOffset = FFI->getObjectOffset(FPIndex);
962 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
969 MachineFrameInfo *FFI = MF.getFrameInfo();
970 int BPIndex = FI->getBasePointerSaveIndex();
971 assert(BPIndex && "No Base Pointer Save Slot!");
972 BPOffset = FFI->getObjectOffset(BPIndex);
975 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
982 if (FI->usesPICBase()) {
983 MachineFrameInfo *FFI = MF.getFrameInfo();
984 int PBPIndex = FI->getPICBasePointerSaveIndex();
985 assert(PBPIndex && "No PIC Base Pointer Save Slot!");
986 PBPOffset = FFI->getObjectOffset(PBPIndex);
989 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
990 RetOpcode == PPC::TCRETURNdi ||
991 RetOpcode == PPC::TCRETURNai ||
992 RetOpcode == PPC::TCRETURNri8 ||
993 RetOpcode == PPC::TCRETURNdi8 ||
994 RetOpcode == PPC::TCRETURNai8;
997 int MaxTCRetDelta = FI->getTailCallSPDelta();
998 MachineOperand &StackAdjust = MBBI->getOperand(1);
999 assert(StackAdjust.isImm() && "Expecting immediate value.");
1000 // Adjust stack pointer.
1001 int StackAdj = StackAdjust.getImm();
1002 int Delta = StackAdj - MaxTCRetDelta;
1003 assert((Delta >= 0) && "Delta must be positive");
1004 if (MaxTCRetDelta>0)
1005 FrameSize += (StackAdj +Delta);
1007 FrameSize += StackAdj;
1010 // Frames of 32KB & larger require special handling because they cannot be
1011 // indexed into with a simple LD/LWZ immediate offset operand.
1012 bool isLargeFrame = !isInt<16>(FrameSize);
1015 // In the prologue, the loaded (or persistent) stack pointer value is offset
1016 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
1018 // If this function contained a fastcc call and GuaranteedTailCallOpt is
1019 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1020 // call which invalidates the stack pointer value in SP(0). So we use the
1021 // value of R31 in this case.
1022 if (FI->hasFastCall()) {
1023 assert(HasFP && "Expecting a valid frame pointer.");
1024 if (!isLargeFrame) {
1025 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1026 .addReg(FPReg).addImm(FrameSize);
1028 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1029 .addImm(FrameSize >> 16);
1030 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1031 .addReg(ScratchReg, RegState::Kill)
1032 .addImm(FrameSize & 0xFFFF);
1033 BuildMI(MBB, MBBI, dl, AddInst)
1036 .addReg(ScratchReg);
1038 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
1039 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1043 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
1051 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1055 assert((isPPC64 || MustSaveCRs.empty()) &&
1056 "Epilogue CR restoring supported only in 64-bit mode");
1058 if (!MustSaveCRs.empty()) // will only occur for PPC64
1059 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1064 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1068 if (FI->usesPICBase())
1069 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1070 BuildMI(MBB, MBBI, dl, LoadInst)
1076 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1080 if (!MustSaveCRs.empty()) // will only occur for PPC64
1081 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1082 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1083 .addReg(TempReg, getKillRegState(i == e-1));
1086 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1088 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1089 // call optimization
1090 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1091 (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
1092 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1093 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1094 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1096 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1097 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1098 .addReg(SPReg).addImm(CallerAllocatedAmt);
1100 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1101 .addImm(CallerAllocatedAmt >> 16);
1102 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1103 .addReg(ScratchReg, RegState::Kill)
1104 .addImm(CallerAllocatedAmt & 0xFFFF);
1105 BuildMI(MBB, MBBI, dl, AddInst)
1108 .addReg(ScratchReg);
1110 } else if (RetOpcode == PPC::TCRETURNdi) {
1111 MBBI = MBB.getLastNonDebugInstr();
1112 MachineOperand &JumpTarget = MBBI->getOperand(0);
1113 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1114 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1115 } else if (RetOpcode == PPC::TCRETURNri) {
1116 MBBI = MBB.getLastNonDebugInstr();
1117 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1118 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1119 } else if (RetOpcode == PPC::TCRETURNai) {
1120 MBBI = MBB.getLastNonDebugInstr();
1121 MachineOperand &JumpTarget = MBBI->getOperand(0);
1122 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1123 } else if (RetOpcode == PPC::TCRETURNdi8) {
1124 MBBI = MBB.getLastNonDebugInstr();
1125 MachineOperand &JumpTarget = MBBI->getOperand(0);
1126 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1127 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1128 } else if (RetOpcode == PPC::TCRETURNri8) {
1129 MBBI = MBB.getLastNonDebugInstr();
1130 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1131 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1132 } else if (RetOpcode == PPC::TCRETURNai8) {
1133 MBBI = MBB.getLastNonDebugInstr();
1134 MachineOperand &JumpTarget = MBBI->getOperand(0);
1135 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1140 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1141 RegScavenger *) const {
1142 const PPCRegisterInfo *RegInfo =
1143 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1145 // Save and clear the LR state.
1146 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1147 unsigned LR = RegInfo->getRARegister();
1148 FI->setMustSaveLR(MustSaveLR(MF, LR));
1149 MachineRegisterInfo &MRI = MF.getRegInfo();
1150 MRI.setPhysRegUnused(LR);
1152 // Save R31 if necessary
1153 int FPSI = FI->getFramePointerSaveIndex();
1154 bool isPPC64 = Subtarget.isPPC64();
1155 bool isDarwinABI = Subtarget.isDarwinABI();
1156 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1157 MachineFrameInfo *MFI = MF.getFrameInfo();
1159 // If the frame pointer save index hasn't been defined yet.
1160 if (!FPSI && needsFP(MF)) {
1161 // Find out what the fix offset of the frame pointer save area.
1162 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1163 // Allocate the frame index for frame pointer save area.
1164 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1166 FI->setFramePointerSaveIndex(FPSI);
1169 int BPSI = FI->getBasePointerSaveIndex();
1170 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1171 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1172 // Allocate the frame index for the base pointer save area.
1173 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1175 FI->setBasePointerSaveIndex(BPSI);
1178 // Reserve stack space for the PIC Base register (R30).
1179 // Only used in SVR4 32-bit.
1180 if (FI->usesPICBase()) {
1181 int PBPSI = FI->getPICBasePointerSaveIndex();
1182 PBPSI = MFI->CreateFixedObject(4, -8, true);
1183 FI->setPICBasePointerSaveIndex(PBPSI);
1186 // Reserve stack space to move the linkage area to in case of a tail call.
1188 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1189 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1190 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1193 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1194 // function uses CR 2, 3, or 4.
1195 if (!isPPC64 && !isDarwinABI &&
1196 (MRI.isPhysRegUsed(PPC::CR2) ||
1197 MRI.isPhysRegUsed(PPC::CR3) ||
1198 MRI.isPhysRegUsed(PPC::CR4))) {
1199 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1200 FI->setCRSpillFrameIndex(FrameIdx);
1204 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1205 RegScavenger *RS) const {
1206 // Early exit if not using the SVR4 ABI.
1207 if (!Subtarget.isSVR4ABI()) {
1208 addScavengingSpillSlot(MF, RS);
1212 // Get callee saved register information.
1213 MachineFrameInfo *FFI = MF.getFrameInfo();
1214 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1216 // Early exit if no callee saved registers are modified!
1217 if (CSI.empty() && !needsFP(MF)) {
1218 addScavengingSpillSlot(MF, RS);
1222 unsigned MinGPR = PPC::R31;
1223 unsigned MinG8R = PPC::X31;
1224 unsigned MinFPR = PPC::F31;
1225 unsigned MinVR = PPC::V31;
1227 bool HasGPSaveArea = false;
1228 bool HasG8SaveArea = false;
1229 bool HasFPSaveArea = false;
1230 bool HasVRSAVESaveArea = false;
1231 bool HasVRSaveArea = false;
1233 SmallVector<CalleeSavedInfo, 18> GPRegs;
1234 SmallVector<CalleeSavedInfo, 18> G8Regs;
1235 SmallVector<CalleeSavedInfo, 18> FPRegs;
1236 SmallVector<CalleeSavedInfo, 18> VRegs;
1238 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1239 unsigned Reg = CSI[i].getReg();
1240 if (PPC::GPRCRegClass.contains(Reg)) {
1241 HasGPSaveArea = true;
1243 GPRegs.push_back(CSI[i]);
1248 } else if (PPC::G8RCRegClass.contains(Reg)) {
1249 HasG8SaveArea = true;
1251 G8Regs.push_back(CSI[i]);
1256 } else if (PPC::F8RCRegClass.contains(Reg)) {
1257 HasFPSaveArea = true;
1259 FPRegs.push_back(CSI[i]);
1264 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1265 PPC::CRRCRegClass.contains(Reg)) {
1266 ; // do nothing, as we already know whether CRs are spilled
1267 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1268 HasVRSAVESaveArea = true;
1269 } else if (PPC::VRRCRegClass.contains(Reg)) {
1270 HasVRSaveArea = true;
1272 VRegs.push_back(CSI[i]);
1278 llvm_unreachable("Unknown RegisterClass!");
1282 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1283 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1285 int64_t LowerBound = 0;
1287 // Take into account stack space reserved for tail calls.
1289 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1290 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1291 LowerBound = TCSPDelta;
1294 // The Floating-point register save area is right below the back chain word
1295 // of the previous stack frame.
1296 if (HasFPSaveArea) {
1297 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1298 int FI = FPRegs[i].getFrameIdx();
1300 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1303 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1306 // Check whether the frame pointer register is allocated. If so, make sure it
1307 // is spilled to the correct offset.
1309 HasGPSaveArea = true;
1311 int FI = PFI->getFramePointerSaveIndex();
1312 assert(FI && "No Frame Pointer Save Slot!");
1314 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1317 if (PFI->usesPICBase()) {
1318 HasGPSaveArea = true;
1320 int FI = PFI->getPICBasePointerSaveIndex();
1321 assert(FI && "No PIC Base Pointer Save Slot!");
1323 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1326 const PPCRegisterInfo *RegInfo =
1327 static_cast<const PPCRegisterInfo *>(Subtarget.getRegisterInfo());
1328 if (RegInfo->hasBasePointer(MF)) {
1329 HasGPSaveArea = true;
1331 int FI = PFI->getBasePointerSaveIndex();
1332 assert(FI && "No Base Pointer Save Slot!");
1334 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1337 // General register save area starts right below the Floating-point
1338 // register save area.
1339 if (HasGPSaveArea || HasG8SaveArea) {
1340 // Move general register save area spill slots down, taking into account
1341 // the size of the Floating-point register save area.
1342 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1343 int FI = GPRegs[i].getFrameIdx();
1345 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1348 // Move general register save area spill slots down, taking into account
1349 // the size of the Floating-point register save area.
1350 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1351 int FI = G8Regs[i].getFrameIdx();
1353 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1357 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1358 TRI->getEncodingValue(MinG8R));
1360 if (Subtarget.isPPC64()) {
1361 LowerBound -= (31 - MinReg + 1) * 8;
1363 LowerBound -= (31 - MinReg + 1) * 4;
1367 // For 32-bit only, the CR save area is below the general register
1368 // save area. For 64-bit SVR4, the CR save area is addressed relative
1369 // to the stack pointer and hence does not need an adjustment here.
1370 // Only CR2 (the first nonvolatile spilled) has an associated frame
1371 // index so that we have a single uniform save area.
1372 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1373 // Adjust the frame index of the CR spill slot.
1374 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1375 unsigned Reg = CSI[i].getReg();
1377 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1378 // Leave Darwin logic as-is.
1379 || (!Subtarget.isSVR4ABI() &&
1380 (PPC::CRBITRCRegClass.contains(Reg) ||
1381 PPC::CRRCRegClass.contains(Reg)))) {
1382 int FI = CSI[i].getFrameIdx();
1384 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1388 LowerBound -= 4; // The CR save area is always 4 bytes long.
1391 if (HasVRSAVESaveArea) {
1392 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1393 // which have the VRSAVE register class?
1394 // Adjust the frame index of the VRSAVE spill slot.
1395 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1396 unsigned Reg = CSI[i].getReg();
1398 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1399 int FI = CSI[i].getFrameIdx();
1401 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1405 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1408 if (HasVRSaveArea) {
1409 // Insert alignment padding, we need 16-byte alignment.
1410 LowerBound = (LowerBound - 15) & ~(15);
1412 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1413 int FI = VRegs[i].getFrameIdx();
1415 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1419 addScavengingSpillSlot(MF, RS);
1423 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1424 RegScavenger *RS) const {
1425 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1426 // a large stack, which will require scavenging a register to materialize a
1429 // We need to have a scavenger spill slot for spills if the frame size is
1430 // large. In case there is no free register for large-offset addressing,
1431 // this slot is used for the necessary emergency spill. Also, we need the
1432 // slot for dynamic stack allocations.
1434 // The scavenger might be invoked if the frame offset does not fit into
1435 // the 16-bit immediate. We don't know the complete frame size here
1436 // because we've not yet computed callee-saved register spills or the
1437 // needed alignment padding.
1438 unsigned StackSize = determineFrameLayout(MF, false, true);
1439 MachineFrameInfo *MFI = MF.getFrameInfo();
1440 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1441 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1442 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1443 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1444 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1445 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1449 // Might we have over-aligned allocas?
1450 bool HasAlVars = MFI->hasVarSizedObjects() &&
1451 MFI->getMaxAlignment() > getStackAlignment();
1453 // These kinds of spills might need two registers.
1454 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1455 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1463 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1464 MachineBasicBlock::iterator MI,
1465 const std::vector<CalleeSavedInfo> &CSI,
1466 const TargetRegisterInfo *TRI) const {
1468 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1469 // Return false otherwise to maintain pre-existing behavior.
1470 if (!Subtarget.isSVR4ABI())
1473 MachineFunction *MF = MBB.getParent();
1474 const PPCInstrInfo &TII =
1475 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1477 bool CRSpilled = false;
1478 MachineInstrBuilder CRMIB;
1480 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1481 unsigned Reg = CSI[i].getReg();
1482 // Only Darwin actually uses the VRSAVE register, but it can still appear
1483 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1484 // Darwin, ignore it.
1485 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1488 // CR2 through CR4 are the nonvolatile CR fields.
1489 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1491 // Add the callee-saved register as live-in; it's killed at the spill.
1494 if (CRSpilled && IsCRField) {
1495 CRMIB.addReg(Reg, RegState::ImplicitKill);
1499 // Insert the spill to the stack frame.
1501 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1502 if (Subtarget.isPPC64()) {
1503 // The actual spill will happen at the start of the prologue.
1504 FuncInfo->addMustSaveCR(Reg);
1507 FuncInfo->setSpillsCR();
1509 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1510 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1511 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1512 .addReg(Reg, RegState::ImplicitKill);
1514 MBB.insert(MI, CRMIB);
1515 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1517 getKillRegState(true)),
1518 CSI[i].getFrameIdx()));
1521 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1522 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1523 CSI[i].getFrameIdx(), RC, TRI);
1530 restoreCRs(bool isPPC64, bool is31,
1531 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1532 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1533 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1535 MachineFunction *MF = MBB.getParent();
1536 const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
1538 unsigned RestoreOp, MoveReg;
1541 // This is handled during epilogue generation.
1544 // 32-bit: FP-relative
1545 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1547 CSI[CSIIndex].getFrameIdx()));
1548 RestoreOp = PPC::MTOCRF;
1553 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1554 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1557 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1558 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1561 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1562 .addReg(MoveReg, getKillRegState(true)));
1565 void PPCFrameLowering::
1566 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1567 MachineBasicBlock::iterator I) const {
1568 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1569 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1570 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1571 // Add (actually subtract) back the amount the callee popped on return.
1572 if (int CalleeAmt = I->getOperand(1).getImm()) {
1573 bool is64Bit = Subtarget.isPPC64();
1575 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1576 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1577 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1578 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1579 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1580 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1581 MachineInstr *MI = I;
1582 DebugLoc dl = MI->getDebugLoc();
1584 if (isInt<16>(CalleeAmt)) {
1585 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1586 .addReg(StackReg, RegState::Kill)
1589 MachineBasicBlock::iterator MBBI = I;
1590 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1591 .addImm(CalleeAmt >> 16);
1592 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1593 .addReg(TmpReg, RegState::Kill)
1594 .addImm(CalleeAmt & 0xFFFF);
1595 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1596 .addReg(StackReg, RegState::Kill)
1601 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1606 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1607 MachineBasicBlock::iterator MI,
1608 const std::vector<CalleeSavedInfo> &CSI,
1609 const TargetRegisterInfo *TRI) const {
1611 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1612 // Return false otherwise to maintain pre-existing behavior.
1613 if (!Subtarget.isSVR4ABI())
1616 MachineFunction *MF = MBB.getParent();
1617 const PPCInstrInfo &TII =
1618 *static_cast<const PPCInstrInfo *>(Subtarget.getInstrInfo());
1619 bool CR2Spilled = false;
1620 bool CR3Spilled = false;
1621 bool CR4Spilled = false;
1622 unsigned CSIIndex = 0;
1624 // Initialize insertion-point logic; we will be restoring in reverse
1626 MachineBasicBlock::iterator I = MI, BeforeI = I;
1627 bool AtStart = I == MBB.begin();
1632 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1633 unsigned Reg = CSI[i].getReg();
1635 // Only Darwin actually uses the VRSAVE register, but it can still appear
1636 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1637 // Darwin, ignore it.
1638 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1641 if (Reg == PPC::CR2) {
1643 // The spill slot is associated only with CR2, which is the
1644 // first nonvolatile spilled. Save it here.
1647 } else if (Reg == PPC::CR3) {
1650 } else if (Reg == PPC::CR4) {
1654 // When we first encounter a non-CR register after seeing at
1655 // least one CR register, restore all spilled CRs together.
1656 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1657 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1658 bool is31 = needsFP(*MF);
1659 restoreCRs(Subtarget.isPPC64(), is31,
1660 CR2Spilled, CR3Spilled, CR4Spilled,
1661 MBB, I, CSI, CSIIndex);
1662 CR2Spilled = CR3Spilled = CR4Spilled = false;
1665 // Default behavior for non-CR saves.
1666 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1667 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1669 assert(I != MBB.begin() &&
1670 "loadRegFromStackSlot didn't insert any code!");
1673 // Insert in reverse order.
1682 // If we haven't yet spilled the CRs, do so now.
1683 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1684 bool is31 = needsFP(*MF);
1685 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1686 MBB, I, CSI, CSIIndex);