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 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
40 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
41 (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
44 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
45 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
46 unsigned &NumEntries) const {
47 if (Subtarget.isDarwinABI()) {
49 if (Subtarget.isPPC64()) {
50 static const SpillSlot darwin64Offsets = {PPC::X31, -8};
51 return &darwin64Offsets;
53 static const SpillSlot darwinOffsets = {PPC::R31, -4};
54 return &darwinOffsets;
58 // Early exit if not using the SVR4 ABI.
59 if (!Subtarget.isSVR4ABI()) {
64 // Note that the offsets here overlap, but this is fixed up in
65 // processFunctionBeforeFrameFinalized.
67 static const SpillSlot Offsets[] = {
68 // Floating-point register save area offsets.
88 // General register save area offsets.
108 // CR save area offset. We map each of the nonvolatile CR fields
109 // to the slot for CR2, which is the first of the nonvolatile CR
110 // fields to be assigned, so that we only allocate one save slot.
111 // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
114 // VRSAVE save area offset.
117 // Vector register save area
131 static const SpillSlot Offsets64[] = {
132 // Floating-point register save area offsets.
152 // General register save area offsets.
172 // VRSAVE save area offset.
175 // Vector register save area
189 if (Subtarget.isPPC64()) {
190 NumEntries = array_lengthof(Offsets64);
194 NumEntries = array_lengthof(Offsets);
200 /// RemoveVRSaveCode - We have found that this function does not need any code
201 /// to manipulate the VRSAVE register, even though it uses vector registers.
202 /// This can happen when the only registers used are known to be live in or out
203 /// of the function. Remove all of the VRSAVE related code from the function.
204 /// FIXME: The removal of the code results in a compile failure at -O0 when the
205 /// function contains a function call, as the GPR containing original VRSAVE
206 /// contents is spilled and reloaded around the call. Without the prolog code,
207 /// the spill instruction refers to an undefined register. This code needs
208 /// to account for all uses of that GPR.
209 static void RemoveVRSaveCode(MachineInstr *MI) {
210 MachineBasicBlock *Entry = MI->getParent();
211 MachineFunction *MF = Entry->getParent();
213 // We know that the MTVRSAVE instruction immediately follows MI. Remove it.
214 MachineBasicBlock::iterator MBBI = MI;
216 assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
217 MBBI->eraseFromParent();
219 bool RemovedAllMTVRSAVEs = true;
220 // See if we can find and remove the MTVRSAVE instruction from all of the
222 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
223 // If last instruction is a return instruction, add an epilogue
224 if (!I->empty() && I->back().isReturn()) {
225 bool FoundIt = false;
226 for (MBBI = I->end(); MBBI != I->begin(); ) {
228 if (MBBI->getOpcode() == PPC::MTVRSAVE) {
229 MBBI->eraseFromParent(); // remove it.
234 RemovedAllMTVRSAVEs &= FoundIt;
238 // If we found and removed all MTVRSAVE instructions, remove the read of
240 if (RemovedAllMTVRSAVEs) {
242 assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
244 assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
245 MBBI->eraseFromParent();
248 // Finally, nuke the UPDATE_VRSAVE.
249 MI->eraseFromParent();
252 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
253 // instruction selector. Based on the vector registers that have been used,
254 // transform this into the appropriate ORI instruction.
255 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
256 MachineFunction *MF = MI->getParent()->getParent();
257 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
258 DebugLoc dl = MI->getDebugLoc();
260 unsigned UsedRegMask = 0;
261 for (unsigned i = 0; i != 32; ++i)
262 if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
263 UsedRegMask |= 1 << (31-i);
265 // Live in and live out values already must be in the mask, so don't bother
267 for (MachineRegisterInfo::livein_iterator
268 I = MF->getRegInfo().livein_begin(),
269 E = MF->getRegInfo().livein_end(); I != E; ++I) {
270 unsigned RegNo = TRI->getEncodingValue(I->first);
271 if (VRRegNo[RegNo] == I->first) // If this really is a vector reg.
272 UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked.
275 // Live out registers appear as use operands on return instructions.
276 for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
277 UsedRegMask != 0 && BI != BE; ++BI) {
278 const MachineBasicBlock &MBB = *BI;
279 if (MBB.empty() || !MBB.back().isReturn())
281 const MachineInstr &Ret = MBB.back();
282 for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
283 const MachineOperand &MO = Ret.getOperand(I);
284 if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
286 unsigned RegNo = TRI->getEncodingValue(MO.getReg());
287 UsedRegMask &= ~(1 << (31-RegNo));
291 // If no registers are used, turn this into a copy.
292 if (UsedRegMask == 0) {
293 // Remove all VRSAVE code.
294 RemoveVRSaveCode(MI);
298 unsigned SrcReg = MI->getOperand(1).getReg();
299 unsigned DstReg = MI->getOperand(0).getReg();
301 if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
302 if (DstReg != SrcReg)
303 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
305 .addImm(UsedRegMask);
307 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
308 .addReg(SrcReg, RegState::Kill)
309 .addImm(UsedRegMask);
310 } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
311 if (DstReg != SrcReg)
312 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
314 .addImm(UsedRegMask >> 16);
316 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
317 .addReg(SrcReg, RegState::Kill)
318 .addImm(UsedRegMask >> 16);
320 if (DstReg != SrcReg)
321 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
323 .addImm(UsedRegMask >> 16);
325 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
326 .addReg(SrcReg, RegState::Kill)
327 .addImm(UsedRegMask >> 16);
329 BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
330 .addReg(DstReg, RegState::Kill)
331 .addImm(UsedRegMask & 0xFFFF);
334 // Remove the old UPDATE_VRSAVE instruction.
335 MI->eraseFromParent();
338 static bool spillsCR(const MachineFunction &MF) {
339 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
340 return FuncInfo->isCRSpilled();
343 static bool spillsVRSAVE(const MachineFunction &MF) {
344 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
345 return FuncInfo->isVRSAVESpilled();
348 static bool hasSpills(const MachineFunction &MF) {
349 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
350 return FuncInfo->hasSpills();
353 static bool hasNonRISpills(const MachineFunction &MF) {
354 const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
355 return FuncInfo->hasNonRISpills();
358 /// determineFrameLayout - Determine the size of the frame and maximum call
360 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
362 bool UseEstimate) const {
363 MachineFrameInfo *MFI = MF.getFrameInfo();
365 // Get the number of bytes to allocate from the FrameInfo
367 UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
369 // Get stack alignments. The frame must be aligned to the greatest of these:
370 unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
371 unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
372 unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
374 const PPCRegisterInfo *RegInfo =
375 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
377 // If we are a leaf function, and use up to 224 bytes of stack space,
378 // don't have a frame pointer, calls, or dynamic alloca then we do not need
379 // to adjust the stack pointer (we fit in the Red Zone).
380 // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
381 // stackless code if all local vars are reg-allocated.
382 bool DisableRedZone = MF.getFunction()->getAttributes().
383 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
384 if (!DisableRedZone &&
385 (Subtarget.isPPC64() || // 32-bit SVR4, no stack-
386 !Subtarget.isSVR4ABI() || // allocated locals.
388 FrameSize <= 224 && // Fits in red zone.
389 !MFI->hasVarSizedObjects() && // No dynamic alloca.
390 !MFI->adjustsStack() && // No calls.
391 !RegInfo->hasBasePointer(MF)) { // No special alignment.
394 MFI->setStackSize(0);
398 // Get the maximum call frame size of all the calls.
399 unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
401 // Maximum call frame needs to be at least big enough for linkage area.
402 unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
403 Subtarget.isDarwinABI(),
404 Subtarget.isELFv2ABI());
405 maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
407 // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
408 // that allocations will be aligned.
409 if (MFI->hasVarSizedObjects())
410 maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
412 // Update maximum call frame size.
414 MFI->setMaxCallFrameSize(maxCallFrameSize);
416 // Include call frame size in total.
417 FrameSize += maxCallFrameSize;
419 // Make sure the frame is aligned.
420 FrameSize = (FrameSize + AlignMask) & ~AlignMask;
422 // Update frame info.
424 MFI->setStackSize(FrameSize);
429 // hasFP - Return true if the specified function actually has a dedicated frame
431 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
432 const MachineFrameInfo *MFI = MF.getFrameInfo();
433 // FIXME: This is pretty much broken by design: hasFP() might be called really
434 // early, before the stack layout was calculated and thus hasFP() might return
435 // true or false here depending on the time of call.
436 return (MFI->getStackSize()) && needsFP(MF);
439 // needsFP - Return true if the specified function should have a dedicated frame
440 // pointer register. This is true if the function has variable sized allocas or
441 // if frame pointer elimination is disabled.
442 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
443 const MachineFrameInfo *MFI = MF.getFrameInfo();
445 // Naked functions have no stack frame pushed, so we don't have a frame
447 if (MF.getFunction()->getAttributes().hasAttribute(
448 AttributeSet::FunctionIndex, Attribute::Naked))
451 return MF.getTarget().Options.DisableFramePointerElim(MF) ||
452 MFI->hasVarSizedObjects() ||
453 (MF.getTarget().Options.GuaranteedTailCallOpt &&
454 MF.getInfo<PPCFunctionInfo>()->hasFastCall());
457 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
458 bool is31 = needsFP(MF);
459 unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
460 unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
462 const PPCRegisterInfo *RegInfo =
463 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
464 bool HasBP = RegInfo->hasBasePointer(MF);
465 unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
466 unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
468 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
470 for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
472 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
473 MachineOperand &MO = MBBI->getOperand(I);
477 switch (MO.getReg()) {
496 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
497 MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
498 MachineBasicBlock::iterator MBBI = MBB.begin();
499 MachineFrameInfo *MFI = MF.getFrameInfo();
500 const PPCInstrInfo &TII =
501 *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
502 const PPCRegisterInfo *RegInfo =
503 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
505 MachineModuleInfo &MMI = MF.getMMI();
506 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
508 bool needsCFI = MMI.hasDebugInfo() ||
509 MF.getFunction()->needsUnwindTableEntry();
510 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
512 // Get processor type.
513 bool isPPC64 = Subtarget.isPPC64();
515 bool isDarwinABI = Subtarget.isDarwinABI();
516 bool isSVR4ABI = Subtarget.isSVR4ABI();
517 bool isELFv2ABI = Subtarget.isELFv2ABI();
518 assert((isDarwinABI || isSVR4ABI) &&
519 "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
521 // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it,
524 for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
525 if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
526 HandleVRSaveUpdate(MBBI, TII);
531 // Move MBBI back to the beginning of the function.
534 // Work out frame sizes.
535 unsigned FrameSize = determineFrameLayout(MF);
536 int NegFrameSize = -FrameSize;
537 if (!isInt<32>(NegFrameSize))
538 llvm_unreachable("Unhandled stack size!");
540 if (MFI->isFrameAddressTaken())
541 replaceFPWithRealFP(MF);
543 // Check if the link register (LR) must be saved.
544 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
545 bool MustSaveLR = FI->mustSaveLR();
546 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
547 // Do we have a frame pointer and/or base pointer for this function?
548 bool HasFP = hasFP(MF);
549 bool HasBP = RegInfo->hasBasePointer(MF);
551 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
552 unsigned BPReg = RegInfo->getBaseRegister(MF);
553 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
554 unsigned LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
555 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
556 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
557 // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
558 const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
560 const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
562 const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
564 const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
566 const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
568 const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
570 const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
572 const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
574 const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
577 // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
578 // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
579 // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
580 // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
581 assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
582 "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
584 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
589 MachineFrameInfo *FFI = MF.getFrameInfo();
590 int FPIndex = FI->getFramePointerSaveIndex();
591 assert(FPIndex && "No Frame Pointer Save Slot!");
592 FPOffset = FFI->getObjectOffset(FPIndex);
595 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
602 MachineFrameInfo *FFI = MF.getFrameInfo();
603 int BPIndex = FI->getBasePointerSaveIndex();
604 assert(BPIndex && "No Base Pointer Save Slot!");
605 BPOffset = FFI->getObjectOffset(BPIndex);
608 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
614 // Get stack alignments.
615 unsigned MaxAlign = MFI->getMaxAlignment();
616 if (HasBP && MaxAlign > 1)
617 assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
618 "Invalid alignment!");
620 // Frames of 32KB & larger require special handling because they cannot be
621 // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
622 bool isLargeFrame = !isInt<16>(NegFrameSize);
625 BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
627 assert((isPPC64 || MustSaveCRs.empty()) &&
628 "Prologue CR saving supported only in 64-bit mode");
630 if (!MustSaveCRs.empty()) { // will only occur for PPC64
631 // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
632 // If only one or two CR fields are clobbered, it could be more
633 // efficient to use mfocrf to selectively save just those fields.
634 MachineInstrBuilder MIB =
635 BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
636 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
637 MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
641 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
642 BuildMI(MBB, MBBI, dl, StoreInst)
647 if (isPIC && !isDarwinABI && !isPPC64 &&
648 MF.getInfo<PPCFunctionInfo>()->usesPICBase())
649 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
650 BuildMI(MBB, MBBI, dl, StoreInst)
656 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
657 BuildMI(MBB, MBBI, dl, StoreInst)
663 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
664 BuildMI(MBB, MBBI, dl, StoreInst)
669 if (!MustSaveCRs.empty()) // will only occur for PPC64
670 BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
671 .addReg(TempReg, getKillRegState(true))
675 // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
676 if (!FrameSize) return;
678 // Adjust stack pointer: r1 += NegFrameSize.
679 // If there is a preferred stack alignment, align R1 now
682 // Save a copy of r1 as the base pointer.
683 BuildMI(MBB, MBBI, dl, OrInst, BPReg)
688 if (HasBP && MaxAlign > 1) {
690 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
693 .addImm(64 - Log2_32(MaxAlign));
695 BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
698 .addImm(32 - Log2_32(MaxAlign))
701 BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
702 .addReg(ScratchReg, RegState::Kill)
703 .addImm(NegFrameSize);
705 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
706 .addImm(NegFrameSize >> 16);
707 BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
708 .addReg(TempReg, RegState::Kill)
709 .addImm(NegFrameSize & 0xFFFF);
710 BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
711 .addReg(ScratchReg, RegState::Kill)
712 .addReg(TempReg, RegState::Kill);
714 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
715 .addReg(SPReg, RegState::Kill)
719 } else if (!isLargeFrame) {
720 BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
722 .addImm(NegFrameSize)
726 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
727 .addImm(NegFrameSize >> 16);
728 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
729 .addReg(ScratchReg, RegState::Kill)
730 .addImm(NegFrameSize & 0xFFFF);
731 BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
732 .addReg(SPReg, RegState::Kill)
737 // Add Call Frame Information for the instructions we generated above.
742 // Define CFA in terms of BP. Do this in preference to using FP/SP,
743 // because if the stack needed aligning then CFA won't be at a fixed
744 // offset from FP/SP.
745 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
746 CFIIndex = MMI.addFrameInst(
747 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
749 // Adjust the definition of CFA to account for the change in SP.
750 assert(NegFrameSize);
751 CFIIndex = MMI.addFrameInst(
752 MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
754 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
755 .addCFIIndex(CFIIndex);
758 // Describe where FP was saved, at a fixed offset from CFA.
759 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
760 CFIIndex = MMI.addFrameInst(
761 MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
762 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
763 .addCFIIndex(CFIIndex);
767 // Describe where BP was saved, at a fixed offset from CFA.
768 unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
769 CFIIndex = MMI.addFrameInst(
770 MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
771 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
772 .addCFIIndex(CFIIndex);
776 // Describe where LR was saved, at a fixed offset from CFA.
777 unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
778 CFIIndex = MMI.addFrameInst(
779 MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
780 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
781 .addCFIIndex(CFIIndex);
785 // If there is a frame pointer, copy R1 into R31
787 BuildMI(MBB, MBBI, dl, OrInst, FPReg)
791 if (!HasBP && needsCFI) {
792 // Change the definition of CFA from SP+offset to FP+offset, because SP
793 // will change at every alloca.
794 unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
795 unsigned CFIIndex = MMI.addFrameInst(
796 MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
798 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
799 .addCFIIndex(CFIIndex);
804 // Describe where callee saved registers were saved, at fixed offsets from
806 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
807 for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
808 unsigned Reg = CSI[I].getReg();
809 if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
811 // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
812 // subregisters of CR2. We just need to emit a move of CR2.
813 if (PPC::CRBITRCRegClass.contains(Reg))
816 // For SVR4, don't emit a move for the CR spill slot if we haven't
818 if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
819 && MustSaveCRs.empty())
822 // For 64-bit SVR4 when we have spilled CRs, the spill location
823 // is SP+8, not a frame-relative slot.
824 if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
825 // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
826 // the whole CR word. In the ELFv2 ABI, every CR that was
827 // actually saved gets its own CFI record.
828 unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
829 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
830 nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
831 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
832 .addCFIIndex(CFIIndex);
836 int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
837 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
838 nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
839 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
840 .addCFIIndex(CFIIndex);
845 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
846 MachineBasicBlock &MBB) const {
847 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
848 assert(MBBI != MBB.end() && "Returning block has no terminator");
849 const PPCInstrInfo &TII =
850 *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
851 const PPCRegisterInfo *RegInfo =
852 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
854 unsigned RetOpcode = MBBI->getOpcode();
857 assert((RetOpcode == PPC::BLR ||
858 RetOpcode == PPC::TCRETURNri ||
859 RetOpcode == PPC::TCRETURNdi ||
860 RetOpcode == PPC::TCRETURNai ||
861 RetOpcode == PPC::TCRETURNri8 ||
862 RetOpcode == PPC::TCRETURNdi8 ||
863 RetOpcode == PPC::TCRETURNai8) &&
864 "Can only insert epilog into returning blocks");
866 // Get alignment info so we know how to restore the SP.
867 const MachineFrameInfo *MFI = MF.getFrameInfo();
869 // Get the number of bytes allocated from the FrameInfo.
870 int FrameSize = MFI->getStackSize();
872 // Get processor type.
873 bool isPPC64 = Subtarget.isPPC64();
875 bool isDarwinABI = Subtarget.isDarwinABI();
876 bool isSVR4ABI = Subtarget.isSVR4ABI();
877 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
879 // Check if the link register (LR) has been saved.
880 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
881 bool MustSaveLR = FI->mustSaveLR();
882 const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
883 // Do we have a frame pointer and/or base pointer for this function?
884 bool HasFP = hasFP(MF);
885 bool HasBP = RegInfo->hasBasePointer(MF);
887 unsigned SPReg = isPPC64 ? PPC::X1 : PPC::R1;
888 unsigned BPReg = RegInfo->getBaseRegister(MF);
889 unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
890 unsigned ScratchReg = isPPC64 ? PPC::X0 : PPC::R0;
891 unsigned TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
892 const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
894 const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
896 const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
898 const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
900 const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
902 const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
905 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
910 MachineFrameInfo *FFI = MF.getFrameInfo();
911 int FPIndex = FI->getFramePointerSaveIndex();
912 assert(FPIndex && "No Frame Pointer Save Slot!");
913 FPOffset = FFI->getObjectOffset(FPIndex);
916 PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
923 MachineFrameInfo *FFI = MF.getFrameInfo();
924 int BPIndex = FI->getBasePointerSaveIndex();
925 assert(BPIndex && "No Base Pointer Save Slot!");
926 BPOffset = FFI->getObjectOffset(BPIndex);
929 PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
935 bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
936 RetOpcode == PPC::TCRETURNdi ||
937 RetOpcode == PPC::TCRETURNai ||
938 RetOpcode == PPC::TCRETURNri8 ||
939 RetOpcode == PPC::TCRETURNdi8 ||
940 RetOpcode == PPC::TCRETURNai8;
943 int MaxTCRetDelta = FI->getTailCallSPDelta();
944 MachineOperand &StackAdjust = MBBI->getOperand(1);
945 assert(StackAdjust.isImm() && "Expecting immediate value.");
946 // Adjust stack pointer.
947 int StackAdj = StackAdjust.getImm();
948 int Delta = StackAdj - MaxTCRetDelta;
949 assert((Delta >= 0) && "Delta must be positive");
951 FrameSize += (StackAdj +Delta);
953 FrameSize += StackAdj;
956 // Frames of 32KB & larger require special handling because they cannot be
957 // indexed into with a simple LD/LWZ immediate offset operand.
958 bool isLargeFrame = !isInt<16>(FrameSize);
961 // In the prologue, the loaded (or persistent) stack pointer value is offset
962 // by the STDU/STDUX/STWU/STWUX instruction. Add this offset back now.
964 // If this function contained a fastcc call and GuaranteedTailCallOpt is
965 // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
966 // call which invalidates the stack pointer value in SP(0). So we use the
967 // value of R31 in this case.
968 if (FI->hasFastCall()) {
969 assert(HasFP && "Expecting a valid frame pointer.");
971 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
972 .addReg(FPReg).addImm(FrameSize);
974 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
975 .addImm(FrameSize >> 16);
976 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
977 .addReg(ScratchReg, RegState::Kill)
978 .addImm(FrameSize & 0xFFFF);
979 BuildMI(MBB, MBBI, dl, AddInst)
984 } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
985 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
989 BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
997 BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
1001 assert((isPPC64 || MustSaveCRs.empty()) &&
1002 "Epilogue CR restoring supported only in 64-bit mode");
1004 if (!MustSaveCRs.empty()) // will only occur for PPC64
1005 BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
1010 BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
1014 if (isPIC && !isDarwinABI && !isPPC64 &&
1015 MF.getInfo<PPCFunctionInfo>()->usesPICBase())
1016 // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
1017 BuildMI(MBB, MBBI, dl, LoadInst)
1023 BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
1027 if (!MustSaveCRs.empty()) // will only occur for PPC64
1028 for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1029 BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1030 .addReg(TempReg, getKillRegState(i == e-1));
1033 BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1035 // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1036 // call optimization
1037 if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1038 MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1039 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1040 unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1042 if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1043 BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1044 .addReg(SPReg).addImm(CallerAllocatedAmt);
1046 BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1047 .addImm(CallerAllocatedAmt >> 16);
1048 BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1049 .addReg(ScratchReg, RegState::Kill)
1050 .addImm(CallerAllocatedAmt & 0xFFFF);
1051 BuildMI(MBB, MBBI, dl, AddInst)
1054 .addReg(ScratchReg);
1056 } else if (RetOpcode == PPC::TCRETURNdi) {
1057 MBBI = MBB.getLastNonDebugInstr();
1058 MachineOperand &JumpTarget = MBBI->getOperand(0);
1059 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1060 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1061 } else if (RetOpcode == PPC::TCRETURNri) {
1062 MBBI = MBB.getLastNonDebugInstr();
1063 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1064 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1065 } else if (RetOpcode == PPC::TCRETURNai) {
1066 MBBI = MBB.getLastNonDebugInstr();
1067 MachineOperand &JumpTarget = MBBI->getOperand(0);
1068 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1069 } else if (RetOpcode == PPC::TCRETURNdi8) {
1070 MBBI = MBB.getLastNonDebugInstr();
1071 MachineOperand &JumpTarget = MBBI->getOperand(0);
1072 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1073 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1074 } else if (RetOpcode == PPC::TCRETURNri8) {
1075 MBBI = MBB.getLastNonDebugInstr();
1076 assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1077 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1078 } else if (RetOpcode == PPC::TCRETURNai8) {
1079 MBBI = MBB.getLastNonDebugInstr();
1080 MachineOperand &JumpTarget = MBBI->getOperand(0);
1081 BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1085 /// MustSaveLR - Return true if this function requires that we save the LR
1086 /// register onto the stack in the prolog and restore it in the epilog of the
1088 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
1089 const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
1091 // We need a save/restore of LR if there is any def of LR (which is
1092 // defined by calls, including the PIC setup sequence), or if there is
1093 // some use of the LR stack slot (e.g. for builtin_return_address).
1094 // (LR comes in 32 and 64 bit versions.)
1095 MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
1096 return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
1100 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1101 RegScavenger *) const {
1102 const PPCRegisterInfo *RegInfo =
1103 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1105 // Save and clear the LR state.
1106 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1107 unsigned LR = RegInfo->getRARegister();
1108 FI->setMustSaveLR(MustSaveLR(MF, LR));
1109 MachineRegisterInfo &MRI = MF.getRegInfo();
1110 MRI.setPhysRegUnused(LR);
1112 // Save R31 if necessary
1113 int FPSI = FI->getFramePointerSaveIndex();
1114 bool isPPC64 = Subtarget.isPPC64();
1115 bool isDarwinABI = Subtarget.isDarwinABI();
1116 bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1117 MachineFrameInfo *MFI = MF.getFrameInfo();
1119 // If the frame pointer save index hasn't been defined yet.
1120 if (!FPSI && needsFP(MF)) {
1121 // Find out what the fix offset of the frame pointer save area.
1122 int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1123 // Allocate the frame index for frame pointer save area.
1124 FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1126 FI->setFramePointerSaveIndex(FPSI);
1129 int BPSI = FI->getBasePointerSaveIndex();
1130 if (!BPSI && RegInfo->hasBasePointer(MF)) {
1131 int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1132 // Allocate the frame index for the base pointer save area.
1133 BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1135 FI->setBasePointerSaveIndex(BPSI);
1138 // Reserve stack space to move the linkage area to in case of a tail call.
1140 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1141 (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1142 MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1145 // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1146 // function uses CR 2, 3, or 4.
1147 if (!isPPC64 && !isDarwinABI &&
1148 (MRI.isPhysRegUsed(PPC::CR2) ||
1149 MRI.isPhysRegUsed(PPC::CR3) ||
1150 MRI.isPhysRegUsed(PPC::CR4))) {
1151 int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1152 FI->setCRSpillFrameIndex(FrameIdx);
1156 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1157 RegScavenger *RS) const {
1158 // Early exit if not using the SVR4 ABI.
1159 if (!Subtarget.isSVR4ABI()) {
1160 addScavengingSpillSlot(MF, RS);
1164 // Get callee saved register information.
1165 MachineFrameInfo *FFI = MF.getFrameInfo();
1166 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1168 // Early exit if no callee saved registers are modified!
1169 if (CSI.empty() && !needsFP(MF)) {
1170 addScavengingSpillSlot(MF, RS);
1174 unsigned MinGPR = PPC::R31;
1175 unsigned MinG8R = PPC::X31;
1176 unsigned MinFPR = PPC::F31;
1177 unsigned MinVR = PPC::V31;
1179 bool HasGPSaveArea = false;
1180 bool HasG8SaveArea = false;
1181 bool HasFPSaveArea = false;
1182 bool HasVRSAVESaveArea = false;
1183 bool HasVRSaveArea = false;
1185 SmallVector<CalleeSavedInfo, 18> GPRegs;
1186 SmallVector<CalleeSavedInfo, 18> G8Regs;
1187 SmallVector<CalleeSavedInfo, 18> FPRegs;
1188 SmallVector<CalleeSavedInfo, 18> VRegs;
1190 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1191 unsigned Reg = CSI[i].getReg();
1192 if (PPC::GPRCRegClass.contains(Reg)) {
1193 HasGPSaveArea = true;
1195 GPRegs.push_back(CSI[i]);
1200 } else if (PPC::G8RCRegClass.contains(Reg)) {
1201 HasG8SaveArea = true;
1203 G8Regs.push_back(CSI[i]);
1208 } else if (PPC::F8RCRegClass.contains(Reg)) {
1209 HasFPSaveArea = true;
1211 FPRegs.push_back(CSI[i]);
1216 } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1217 PPC::CRRCRegClass.contains(Reg)) {
1218 ; // do nothing, as we already know whether CRs are spilled
1219 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1220 HasVRSAVESaveArea = true;
1221 } else if (PPC::VRRCRegClass.contains(Reg)) {
1222 HasVRSaveArea = true;
1224 VRegs.push_back(CSI[i]);
1230 llvm_unreachable("Unknown RegisterClass!");
1234 PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1235 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1237 int64_t LowerBound = 0;
1239 // Take into account stack space reserved for tail calls.
1241 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1242 (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1243 LowerBound = TCSPDelta;
1246 // The Floating-point register save area is right below the back chain word
1247 // of the previous stack frame.
1248 if (HasFPSaveArea) {
1249 for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1250 int FI = FPRegs[i].getFrameIdx();
1252 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1255 LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1258 // Check whether the frame pointer register is allocated. If so, make sure it
1259 // is spilled to the correct offset.
1261 HasGPSaveArea = true;
1263 int FI = PFI->getFramePointerSaveIndex();
1264 assert(FI && "No Frame Pointer Save Slot!");
1266 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1269 const PPCRegisterInfo *RegInfo =
1270 static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1271 if (RegInfo->hasBasePointer(MF)) {
1272 HasGPSaveArea = true;
1274 int FI = PFI->getBasePointerSaveIndex();
1275 assert(FI && "No Base Pointer Save Slot!");
1277 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1280 // General register save area starts right below the Floating-point
1281 // register save area.
1282 if (HasGPSaveArea || HasG8SaveArea) {
1283 // Move general register save area spill slots down, taking into account
1284 // the size of the Floating-point register save area.
1285 for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1286 int FI = GPRegs[i].getFrameIdx();
1288 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1291 // Move general register save area spill slots down, taking into account
1292 // the size of the Floating-point register save area.
1293 for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1294 int FI = G8Regs[i].getFrameIdx();
1296 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1300 std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1301 TRI->getEncodingValue(MinG8R));
1303 if (Subtarget.isPPC64()) {
1304 LowerBound -= (31 - MinReg + 1) * 8;
1306 LowerBound -= (31 - MinReg + 1) * 4;
1310 // For 32-bit only, the CR save area is below the general register
1311 // save area. For 64-bit SVR4, the CR save area is addressed relative
1312 // to the stack pointer and hence does not need an adjustment here.
1313 // Only CR2 (the first nonvolatile spilled) has an associated frame
1314 // index so that we have a single uniform save area.
1315 if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1316 // Adjust the frame index of the CR spill slot.
1317 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1318 unsigned Reg = CSI[i].getReg();
1320 if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1321 // Leave Darwin logic as-is.
1322 || (!Subtarget.isSVR4ABI() &&
1323 (PPC::CRBITRCRegClass.contains(Reg) ||
1324 PPC::CRRCRegClass.contains(Reg)))) {
1325 int FI = CSI[i].getFrameIdx();
1327 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1331 LowerBound -= 4; // The CR save area is always 4 bytes long.
1334 if (HasVRSAVESaveArea) {
1335 // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1336 // which have the VRSAVE register class?
1337 // Adjust the frame index of the VRSAVE spill slot.
1338 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1339 unsigned Reg = CSI[i].getReg();
1341 if (PPC::VRSAVERCRegClass.contains(Reg)) {
1342 int FI = CSI[i].getFrameIdx();
1344 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1348 LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1351 if (HasVRSaveArea) {
1352 // Insert alignment padding, we need 16-byte alignment.
1353 LowerBound = (LowerBound - 15) & ~(15);
1355 for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1356 int FI = VRegs[i].getFrameIdx();
1358 FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1362 addScavengingSpillSlot(MF, RS);
1366 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1367 RegScavenger *RS) const {
1368 // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1369 // a large stack, which will require scavenging a register to materialize a
1372 // We need to have a scavenger spill slot for spills if the frame size is
1373 // large. In case there is no free register for large-offset addressing,
1374 // this slot is used for the necessary emergency spill. Also, we need the
1375 // slot for dynamic stack allocations.
1377 // The scavenger might be invoked if the frame offset does not fit into
1378 // the 16-bit immediate. We don't know the complete frame size here
1379 // because we've not yet computed callee-saved register spills or the
1380 // needed alignment padding.
1381 unsigned StackSize = determineFrameLayout(MF, false, true);
1382 MachineFrameInfo *MFI = MF.getFrameInfo();
1383 if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1384 hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1385 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1386 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1387 const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1388 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1392 // Might we have over-aligned allocas?
1393 bool HasAlVars = MFI->hasVarSizedObjects() &&
1394 MFI->getMaxAlignment() > getStackAlignment();
1396 // These kinds of spills might need two registers.
1397 if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1398 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1406 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1407 MachineBasicBlock::iterator MI,
1408 const std::vector<CalleeSavedInfo> &CSI,
1409 const TargetRegisterInfo *TRI) const {
1411 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1412 // Return false otherwise to maintain pre-existing behavior.
1413 if (!Subtarget.isSVR4ABI())
1416 MachineFunction *MF = MBB.getParent();
1417 const PPCInstrInfo &TII =
1418 *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
1420 bool CRSpilled = false;
1421 MachineInstrBuilder CRMIB;
1423 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1424 unsigned Reg = CSI[i].getReg();
1425 // Only Darwin actually uses the VRSAVE register, but it can still appear
1426 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1427 // Darwin, ignore it.
1428 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1431 // CR2 through CR4 are the nonvolatile CR fields.
1432 bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1434 // Add the callee-saved register as live-in; it's killed at the spill.
1437 if (CRSpilled && IsCRField) {
1438 CRMIB.addReg(Reg, RegState::ImplicitKill);
1442 // Insert the spill to the stack frame.
1444 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1445 if (Subtarget.isPPC64()) {
1446 // The actual spill will happen at the start of the prologue.
1447 FuncInfo->addMustSaveCR(Reg);
1450 FuncInfo->setSpillsCR();
1452 // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
1453 // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1454 CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1455 .addReg(Reg, RegState::ImplicitKill);
1457 MBB.insert(MI, CRMIB);
1458 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1460 getKillRegState(true)),
1461 CSI[i].getFrameIdx()));
1464 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1465 TII.storeRegToStackSlot(MBB, MI, Reg, true,
1466 CSI[i].getFrameIdx(), RC, TRI);
1473 restoreCRs(bool isPPC64, bool is31,
1474 bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1475 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1476 const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1478 MachineFunction *MF = MBB.getParent();
1479 const PPCInstrInfo &TII =
1480 *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
1482 unsigned RestoreOp, MoveReg;
1485 // This is handled during epilogue generation.
1488 // 32-bit: FP-relative
1489 MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1491 CSI[CSIIndex].getFrameIdx()));
1492 RestoreOp = PPC::MTOCRF;
1497 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1498 .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1501 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1502 .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1505 MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1506 .addReg(MoveReg, getKillRegState(true)));
1509 void PPCFrameLowering::
1510 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1511 MachineBasicBlock::iterator I) const {
1512 const PPCInstrInfo &TII =
1513 *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
1514 if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1515 I->getOpcode() == PPC::ADJCALLSTACKUP) {
1516 // Add (actually subtract) back the amount the callee popped on return.
1517 if (int CalleeAmt = I->getOperand(1).getImm()) {
1518 bool is64Bit = Subtarget.isPPC64();
1520 unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1521 unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1522 unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1523 unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1524 unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1525 unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1526 MachineInstr *MI = I;
1527 DebugLoc dl = MI->getDebugLoc();
1529 if (isInt<16>(CalleeAmt)) {
1530 BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1531 .addReg(StackReg, RegState::Kill)
1534 MachineBasicBlock::iterator MBBI = I;
1535 BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1536 .addImm(CalleeAmt >> 16);
1537 BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1538 .addReg(TmpReg, RegState::Kill)
1539 .addImm(CalleeAmt & 0xFFFF);
1540 BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1541 .addReg(StackReg, RegState::Kill)
1546 // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1551 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1552 MachineBasicBlock::iterator MI,
1553 const std::vector<CalleeSavedInfo> &CSI,
1554 const TargetRegisterInfo *TRI) const {
1556 // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1557 // Return false otherwise to maintain pre-existing behavior.
1558 if (!Subtarget.isSVR4ABI())
1561 MachineFunction *MF = MBB.getParent();
1562 const PPCInstrInfo &TII =
1563 *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
1564 bool CR2Spilled = false;
1565 bool CR3Spilled = false;
1566 bool CR4Spilled = false;
1567 unsigned CSIIndex = 0;
1569 // Initialize insertion-point logic; we will be restoring in reverse
1571 MachineBasicBlock::iterator I = MI, BeforeI = I;
1572 bool AtStart = I == MBB.begin();
1577 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1578 unsigned Reg = CSI[i].getReg();
1580 // Only Darwin actually uses the VRSAVE register, but it can still appear
1581 // here if, for example, @llvm.eh.unwind.init() is used. If we're not on
1582 // Darwin, ignore it.
1583 if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1586 if (Reg == PPC::CR2) {
1588 // The spill slot is associated only with CR2, which is the
1589 // first nonvolatile spilled. Save it here.
1592 } else if (Reg == PPC::CR3) {
1595 } else if (Reg == PPC::CR4) {
1599 // When we first encounter a non-CR register after seeing at
1600 // least one CR register, restore all spilled CRs together.
1601 if ((CR2Spilled || CR3Spilled || CR4Spilled)
1602 && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1603 bool is31 = needsFP(*MF);
1604 restoreCRs(Subtarget.isPPC64(), is31,
1605 CR2Spilled, CR3Spilled, CR4Spilled,
1606 MBB, I, CSI, CSIIndex);
1607 CR2Spilled = CR3Spilled = CR4Spilled = false;
1610 // Default behavior for non-CR saves.
1611 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1612 TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1614 assert(I != MBB.begin() &&
1615 "loadRegFromStackSlot didn't insert any code!");
1618 // Insert in reverse order.
1627 // If we haven't yet spilled the CRs, do so now.
1628 if (CR2Spilled || CR3Spilled || CR4Spilled) {
1629 bool is31 = needsFP(*MF);
1630 restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1631 MBB, I, CSI, CSIIndex);