LLVM API Documentation

PPCFrameLowering.cpp
Go to the documentation of this file.
00001 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the PPC implementation of TargetFrameLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCFrameLowering.h"
00015 #include "PPCInstrBuilder.h"
00016 #include "PPCInstrInfo.h"
00017 #include "PPCMachineFunctionInfo.h"
00018 #include "PPCSubtarget.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/MachineModuleInfo.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/RegisterScavenging.h"
00025 #include "llvm/IR/Function.h"
00026 #include "llvm/Target/TargetOptions.h"
00027 
00028 using namespace llvm;
00029 
00030 /// VRRegNo - Map from a numbered VR register to its enum value.
00031 ///
00032 static const uint16_t VRRegNo[] = {
00033  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
00034  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
00035  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
00036  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
00037 };
00038 
00039 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
00040     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
00041                           (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
00042       Subtarget(STI) {}
00043 
00044 // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
00045 const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
00046     unsigned &NumEntries) const {
00047   if (Subtarget.isDarwinABI()) {
00048     NumEntries = 1;
00049     if (Subtarget.isPPC64()) {
00050       static const SpillSlot darwin64Offsets = {PPC::X31, -8};
00051       return &darwin64Offsets;
00052     } else {
00053       static const SpillSlot darwinOffsets = {PPC::R31, -4};
00054       return &darwinOffsets;
00055     }
00056   }
00057 
00058   // Early exit if not using the SVR4 ABI.
00059   if (!Subtarget.isSVR4ABI()) {
00060     NumEntries = 0;
00061     return nullptr;
00062   }
00063 
00064   // Note that the offsets here overlap, but this is fixed up in
00065   // processFunctionBeforeFrameFinalized.
00066 
00067   static const SpillSlot Offsets[] = {
00068       // Floating-point register save area offsets.
00069       {PPC::F31, -8},
00070       {PPC::F30, -16},
00071       {PPC::F29, -24},
00072       {PPC::F28, -32},
00073       {PPC::F27, -40},
00074       {PPC::F26, -48},
00075       {PPC::F25, -56},
00076       {PPC::F24, -64},
00077       {PPC::F23, -72},
00078       {PPC::F22, -80},
00079       {PPC::F21, -88},
00080       {PPC::F20, -96},
00081       {PPC::F19, -104},
00082       {PPC::F18, -112},
00083       {PPC::F17, -120},
00084       {PPC::F16, -128},
00085       {PPC::F15, -136},
00086       {PPC::F14, -144},
00087 
00088       // General register save area offsets.
00089       {PPC::R31, -4},
00090       {PPC::R30, -8},
00091       {PPC::R29, -12},
00092       {PPC::R28, -16},
00093       {PPC::R27, -20},
00094       {PPC::R26, -24},
00095       {PPC::R25, -28},
00096       {PPC::R24, -32},
00097       {PPC::R23, -36},
00098       {PPC::R22, -40},
00099       {PPC::R21, -44},
00100       {PPC::R20, -48},
00101       {PPC::R19, -52},
00102       {PPC::R18, -56},
00103       {PPC::R17, -60},
00104       {PPC::R16, -64},
00105       {PPC::R15, -68},
00106       {PPC::R14, -72},
00107 
00108       // CR save area offset.  We map each of the nonvolatile CR fields
00109       // to the slot for CR2, which is the first of the nonvolatile CR
00110       // fields to be assigned, so that we only allocate one save slot.
00111       // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
00112       {PPC::CR2, -4},
00113 
00114       // VRSAVE save area offset.
00115       {PPC::VRSAVE, -4},
00116 
00117       // Vector register save area
00118       {PPC::V31, -16},
00119       {PPC::V30, -32},
00120       {PPC::V29, -48},
00121       {PPC::V28, -64},
00122       {PPC::V27, -80},
00123       {PPC::V26, -96},
00124       {PPC::V25, -112},
00125       {PPC::V24, -128},
00126       {PPC::V23, -144},
00127       {PPC::V22, -160},
00128       {PPC::V21, -176},
00129       {PPC::V20, -192}};
00130 
00131   static const SpillSlot Offsets64[] = {
00132       // Floating-point register save area offsets.
00133       {PPC::F31, -8},
00134       {PPC::F30, -16},
00135       {PPC::F29, -24},
00136       {PPC::F28, -32},
00137       {PPC::F27, -40},
00138       {PPC::F26, -48},
00139       {PPC::F25, -56},
00140       {PPC::F24, -64},
00141       {PPC::F23, -72},
00142       {PPC::F22, -80},
00143       {PPC::F21, -88},
00144       {PPC::F20, -96},
00145       {PPC::F19, -104},
00146       {PPC::F18, -112},
00147       {PPC::F17, -120},
00148       {PPC::F16, -128},
00149       {PPC::F15, -136},
00150       {PPC::F14, -144},
00151 
00152       // General register save area offsets.
00153       {PPC::X31, -8},
00154       {PPC::X30, -16},
00155       {PPC::X29, -24},
00156       {PPC::X28, -32},
00157       {PPC::X27, -40},
00158       {PPC::X26, -48},
00159       {PPC::X25, -56},
00160       {PPC::X24, -64},
00161       {PPC::X23, -72},
00162       {PPC::X22, -80},
00163       {PPC::X21, -88},
00164       {PPC::X20, -96},
00165       {PPC::X19, -104},
00166       {PPC::X18, -112},
00167       {PPC::X17, -120},
00168       {PPC::X16, -128},
00169       {PPC::X15, -136},
00170       {PPC::X14, -144},
00171 
00172       // VRSAVE save area offset.
00173       {PPC::VRSAVE, -4},
00174 
00175       // Vector register save area
00176       {PPC::V31, -16},
00177       {PPC::V30, -32},
00178       {PPC::V29, -48},
00179       {PPC::V28, -64},
00180       {PPC::V27, -80},
00181       {PPC::V26, -96},
00182       {PPC::V25, -112},
00183       {PPC::V24, -128},
00184       {PPC::V23, -144},
00185       {PPC::V22, -160},
00186       {PPC::V21, -176},
00187       {PPC::V20, -192}};
00188 
00189   if (Subtarget.isPPC64()) {
00190     NumEntries = array_lengthof(Offsets64);
00191 
00192     return Offsets64;
00193   } else {
00194     NumEntries = array_lengthof(Offsets);
00195 
00196     return Offsets;
00197   }
00198 }
00199 
00200 /// RemoveVRSaveCode - We have found that this function does not need any code
00201 /// to manipulate the VRSAVE register, even though it uses vector registers.
00202 /// This can happen when the only registers used are known to be live in or out
00203 /// of the function.  Remove all of the VRSAVE related code from the function.
00204 /// FIXME: The removal of the code results in a compile failure at -O0 when the
00205 /// function contains a function call, as the GPR containing original VRSAVE
00206 /// contents is spilled and reloaded around the call.  Without the prolog code,
00207 /// the spill instruction refers to an undefined register.  This code needs
00208 /// to account for all uses of that GPR.
00209 static void RemoveVRSaveCode(MachineInstr *MI) {
00210   MachineBasicBlock *Entry = MI->getParent();
00211   MachineFunction *MF = Entry->getParent();
00212 
00213   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
00214   MachineBasicBlock::iterator MBBI = MI;
00215   ++MBBI;
00216   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
00217   MBBI->eraseFromParent();
00218 
00219   bool RemovedAllMTVRSAVEs = true;
00220   // See if we can find and remove the MTVRSAVE instruction from all of the
00221   // epilog blocks.
00222   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
00223     // If last instruction is a return instruction, add an epilogue
00224     if (!I->empty() && I->back().isReturn()) {
00225       bool FoundIt = false;
00226       for (MBBI = I->end(); MBBI != I->begin(); ) {
00227         --MBBI;
00228         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
00229           MBBI->eraseFromParent();  // remove it.
00230           FoundIt = true;
00231           break;
00232         }
00233       }
00234       RemovedAllMTVRSAVEs &= FoundIt;
00235     }
00236   }
00237 
00238   // If we found and removed all MTVRSAVE instructions, remove the read of
00239   // VRSAVE as well.
00240   if (RemovedAllMTVRSAVEs) {
00241     MBBI = MI;
00242     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
00243     --MBBI;
00244     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
00245     MBBI->eraseFromParent();
00246   }
00247 
00248   // Finally, nuke the UPDATE_VRSAVE.
00249   MI->eraseFromParent();
00250 }
00251 
00252 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
00253 // instruction selector.  Based on the vector registers that have been used,
00254 // transform this into the appropriate ORI instruction.
00255 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
00256   MachineFunction *MF = MI->getParent()->getParent();
00257   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00258   DebugLoc dl = MI->getDebugLoc();
00259 
00260   unsigned UsedRegMask = 0;
00261   for (unsigned i = 0; i != 32; ++i)
00262     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
00263       UsedRegMask |= 1 << (31-i);
00264 
00265   // Live in and live out values already must be in the mask, so don't bother
00266   // marking them.
00267   for (MachineRegisterInfo::livein_iterator
00268        I = MF->getRegInfo().livein_begin(),
00269        E = MF->getRegInfo().livein_end(); I != E; ++I) {
00270     unsigned RegNo = TRI->getEncodingValue(I->first);
00271     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
00272       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
00273   }
00274 
00275   // Live out registers appear as use operands on return instructions.
00276   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
00277        UsedRegMask != 0 && BI != BE; ++BI) {
00278     const MachineBasicBlock &MBB = *BI;
00279     if (MBB.empty() || !MBB.back().isReturn())
00280       continue;
00281     const MachineInstr &Ret = MBB.back();
00282     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
00283       const MachineOperand &MO = Ret.getOperand(I);
00284       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
00285         continue;
00286       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
00287       UsedRegMask &= ~(1 << (31-RegNo));
00288     }
00289   }
00290 
00291   // If no registers are used, turn this into a copy.
00292   if (UsedRegMask == 0) {
00293     // Remove all VRSAVE code.
00294     RemoveVRSaveCode(MI);
00295     return;
00296   }
00297 
00298   unsigned SrcReg = MI->getOperand(1).getReg();
00299   unsigned DstReg = MI->getOperand(0).getReg();
00300 
00301   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
00302     if (DstReg != SrcReg)
00303       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00304         .addReg(SrcReg)
00305         .addImm(UsedRegMask);
00306     else
00307       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00308         .addReg(SrcReg, RegState::Kill)
00309         .addImm(UsedRegMask);
00310   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
00311     if (DstReg != SrcReg)
00312       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00313         .addReg(SrcReg)
00314         .addImm(UsedRegMask >> 16);
00315     else
00316       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00317         .addReg(SrcReg, RegState::Kill)
00318         .addImm(UsedRegMask >> 16);
00319   } else {
00320     if (DstReg != SrcReg)
00321       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00322         .addReg(SrcReg)
00323         .addImm(UsedRegMask >> 16);
00324     else
00325       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
00326         .addReg(SrcReg, RegState::Kill)
00327         .addImm(UsedRegMask >> 16);
00328 
00329     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
00330       .addReg(DstReg, RegState::Kill)
00331       .addImm(UsedRegMask & 0xFFFF);
00332   }
00333 
00334   // Remove the old UPDATE_VRSAVE instruction.
00335   MI->eraseFromParent();
00336 }
00337 
00338 static bool spillsCR(const MachineFunction &MF) {
00339   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00340   return FuncInfo->isCRSpilled();
00341 }
00342 
00343 static bool spillsVRSAVE(const MachineFunction &MF) {
00344   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00345   return FuncInfo->isVRSAVESpilled();
00346 }
00347 
00348 static bool hasSpills(const MachineFunction &MF) {
00349   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00350   return FuncInfo->hasSpills();
00351 }
00352 
00353 static bool hasNonRISpills(const MachineFunction &MF) {
00354   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00355   return FuncInfo->hasNonRISpills();
00356 }
00357 
00358 /// determineFrameLayout - Determine the size of the frame and maximum call
00359 /// frame size.
00360 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
00361                                                 bool UpdateMF,
00362                                                 bool UseEstimate) const {
00363   MachineFrameInfo *MFI = MF.getFrameInfo();
00364 
00365   // Get the number of bytes to allocate from the FrameInfo
00366   unsigned FrameSize =
00367     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
00368 
00369   // Get stack alignments. The frame must be aligned to the greatest of these:
00370   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
00371   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
00372   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
00373 
00374   const PPCRegisterInfo *RegInfo =
00375       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00376 
00377   // If we are a leaf function, and use up to 224 bytes of stack space,
00378   // don't have a frame pointer, calls, or dynamic alloca then we do not need
00379   // to adjust the stack pointer (we fit in the Red Zone).
00380   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
00381   // stackless code if all local vars are reg-allocated.
00382   bool DisableRedZone = MF.getFunction()->getAttributes().
00383     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
00384   if (!DisableRedZone &&
00385       (Subtarget.isPPC64() ||                      // 32-bit SVR4, no stack-
00386        !Subtarget.isSVR4ABI() ||                   //   allocated locals.
00387         FrameSize == 0) &&
00388       FrameSize <= 224 &&                          // Fits in red zone.
00389       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
00390       !MFI->adjustsStack() &&                      // No calls.
00391       !RegInfo->hasBasePointer(MF)) { // No special alignment.
00392     // No need for frame
00393     if (UpdateMF)
00394       MFI->setStackSize(0);
00395     return 0;
00396   }
00397 
00398   // Get the maximum call frame size of all the calls.
00399   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
00400 
00401   // Maximum call frame needs to be at least big enough for linkage area.
00402   unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
00403                                              Subtarget.isDarwinABI(),
00404                                              Subtarget.isELFv2ABI());
00405   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
00406 
00407   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
00408   // that allocations will be aligned.
00409   if (MFI->hasVarSizedObjects())
00410     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
00411 
00412   // Update maximum call frame size.
00413   if (UpdateMF)
00414     MFI->setMaxCallFrameSize(maxCallFrameSize);
00415 
00416   // Include call frame size in total.
00417   FrameSize += maxCallFrameSize;
00418 
00419   // Make sure the frame is aligned.
00420   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
00421 
00422   // Update frame info.
00423   if (UpdateMF)
00424     MFI->setStackSize(FrameSize);
00425 
00426   return FrameSize;
00427 }
00428 
00429 // hasFP - Return true if the specified function actually has a dedicated frame
00430 // pointer register.
00431 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
00432   const MachineFrameInfo *MFI = MF.getFrameInfo();
00433   // FIXME: This is pretty much broken by design: hasFP() might be called really
00434   // early, before the stack layout was calculated and thus hasFP() might return
00435   // true or false here depending on the time of call.
00436   return (MFI->getStackSize()) && needsFP(MF);
00437 }
00438 
00439 // needsFP - Return true if the specified function should have a dedicated frame
00440 // pointer register.  This is true if the function has variable sized allocas or
00441 // if frame pointer elimination is disabled.
00442 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
00443   const MachineFrameInfo *MFI = MF.getFrameInfo();
00444 
00445   // Naked functions have no stack frame pushed, so we don't have a frame
00446   // pointer.
00447   if (MF.getFunction()->getAttributes().hasAttribute(
00448           AttributeSet::FunctionIndex, Attribute::Naked))
00449     return false;
00450 
00451   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
00452     MFI->hasVarSizedObjects() ||
00453     (MF.getTarget().Options.GuaranteedTailCallOpt &&
00454      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
00455 }
00456 
00457 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
00458   bool is31 = needsFP(MF);
00459   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
00460   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
00461 
00462   const PPCRegisterInfo *RegInfo =
00463       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00464   bool HasBP = RegInfo->hasBasePointer(MF);
00465   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
00466   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
00467 
00468   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
00469        BI != BE; ++BI)
00470     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
00471       --MBBI;
00472       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
00473         MachineOperand &MO = MBBI->getOperand(I);
00474         if (!MO.isReg())
00475           continue;
00476 
00477         switch (MO.getReg()) {
00478         case PPC::FP:
00479           MO.setReg(FPReg);
00480           break;
00481         case PPC::FP8:
00482           MO.setReg(FP8Reg);
00483           break;
00484         case PPC::BP:
00485           MO.setReg(BPReg);
00486           break;
00487         case PPC::BP8:
00488           MO.setReg(BP8Reg);
00489           break;
00490 
00491         }
00492       }
00493     }
00494 }
00495 
00496 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
00497   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
00498   MachineBasicBlock::iterator MBBI = MBB.begin();
00499   MachineFrameInfo *MFI = MF.getFrameInfo();
00500   const PPCInstrInfo &TII =
00501       *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
00502   const PPCRegisterInfo *RegInfo =
00503       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00504 
00505   MachineModuleInfo &MMI = MF.getMMI();
00506   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00507   DebugLoc dl;
00508   bool needsCFI = MMI.hasDebugInfo() ||
00509     MF.getFunction()->needsUnwindTableEntry();
00510   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
00511 
00512   // Get processor type.
00513   bool isPPC64 = Subtarget.isPPC64();
00514   // Get the ABI.
00515   bool isDarwinABI = Subtarget.isDarwinABI();
00516   bool isSVR4ABI = Subtarget.isSVR4ABI();
00517   bool isELFv2ABI = Subtarget.isELFv2ABI();
00518   assert((isDarwinABI || isSVR4ABI) &&
00519          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
00520 
00521   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
00522   // process it.
00523   if (!isSVR4ABI)
00524     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
00525       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
00526         HandleVRSaveUpdate(MBBI, TII);
00527         break;
00528       }
00529     }
00530 
00531   // Move MBBI back to the beginning of the function.
00532   MBBI = MBB.begin();
00533 
00534   // Work out frame sizes.
00535   unsigned FrameSize = determineFrameLayout(MF);
00536   int NegFrameSize = -FrameSize;
00537   if (!isInt<32>(NegFrameSize))
00538     llvm_unreachable("Unhandled stack size!");
00539 
00540   if (MFI->isFrameAddressTaken())
00541     replaceFPWithRealFP(MF);
00542 
00543   // Check if the link register (LR) must be saved.
00544   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
00545   bool MustSaveLR = FI->mustSaveLR();
00546   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
00547   // Do we have a frame pointer and/or base pointer for this function?
00548   bool HasFP = hasFP(MF);
00549   bool HasBP = RegInfo->hasBasePointer(MF);
00550 
00551   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
00552   unsigned BPReg       = RegInfo->getBaseRegister(MF);
00553   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
00554   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
00555   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
00556   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
00557   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
00558   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
00559                                                 : PPC::MFLR );
00560   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
00561                                                  : PPC::STW );
00562   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
00563                                                      : PPC::STWU );
00564   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
00565                                                         : PPC::STWUX);
00566   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
00567                                                           : PPC::LIS );
00568   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
00569                                                  : PPC::ORI );
00570   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
00571                                               : PPC::OR );
00572   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
00573                                                             : PPC::SUBFC);
00574   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
00575                                                                : PPC::SUBFIC);
00576 
00577   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
00578   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
00579   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
00580   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
00581   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
00582          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
00583 
00584   int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
00585 
00586   int FPOffset = 0;
00587   if (HasFP) {
00588     if (isSVR4ABI) {
00589       MachineFrameInfo *FFI = MF.getFrameInfo();
00590       int FPIndex = FI->getFramePointerSaveIndex();
00591       assert(FPIndex && "No Frame Pointer Save Slot!");
00592       FPOffset = FFI->getObjectOffset(FPIndex);
00593     } else {
00594       FPOffset =
00595           PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
00596     }
00597   }
00598 
00599   int BPOffset = 0;
00600   if (HasBP) {
00601     if (isSVR4ABI) {
00602       MachineFrameInfo *FFI = MF.getFrameInfo();
00603       int BPIndex = FI->getBasePointerSaveIndex();
00604       assert(BPIndex && "No Base Pointer Save Slot!");
00605       BPOffset = FFI->getObjectOffset(BPIndex);
00606     } else {
00607       BPOffset =
00608         PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
00609                                                    isDarwinABI,
00610                                                    isPIC);
00611     }
00612   }
00613 
00614   // Get stack alignments.
00615   unsigned MaxAlign = MFI->getMaxAlignment();
00616   if (HasBP && MaxAlign > 1)
00617     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
00618            "Invalid alignment!");
00619 
00620   // Frames of 32KB & larger require special handling because they cannot be
00621   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
00622   bool isLargeFrame = !isInt<16>(NegFrameSize);
00623 
00624   if (MustSaveLR)
00625     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
00626 
00627   assert((isPPC64 || MustSaveCRs.empty()) &&
00628          "Prologue CR saving supported only in 64-bit mode");
00629 
00630   if (!MustSaveCRs.empty()) { // will only occur for PPC64
00631     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
00632     // If only one or two CR fields are clobbered, it could be more
00633     // efficient to use mfocrf to selectively save just those fields.
00634     MachineInstrBuilder MIB =
00635       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
00636     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
00637       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
00638   }
00639 
00640   if (HasFP)
00641     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00642     BuildMI(MBB, MBBI, dl, StoreInst)
00643       .addReg(FPReg)
00644       .addImm(FPOffset)
00645       .addReg(SPReg);
00646 
00647   if (HasBP)
00648     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00649     BuildMI(MBB, MBBI, dl, StoreInst)
00650       .addReg(BPReg)
00651       .addImm(BPOffset)
00652       .addReg(SPReg);
00653 
00654   if (MustSaveLR)
00655     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
00656     BuildMI(MBB, MBBI, dl, StoreInst)
00657       .addReg(ScratchReg)
00658       .addImm(LROffset)
00659       .addReg(SPReg);
00660 
00661   if (!MustSaveCRs.empty()) // will only occur for PPC64
00662     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
00663       .addReg(TempReg, getKillRegState(true))
00664       .addImm(8)
00665       .addReg(SPReg);
00666 
00667   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
00668   if (!FrameSize) return;
00669 
00670   // Adjust stack pointer: r1 += NegFrameSize.
00671   // If there is a preferred stack alignment, align R1 now
00672 
00673   if (HasBP) {
00674     // Save a copy of r1 as the base pointer.
00675     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
00676       .addReg(SPReg)
00677       .addReg(SPReg);
00678   }
00679 
00680   if (HasBP && MaxAlign > 1) {
00681     if (isPPC64)
00682       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
00683         .addReg(SPReg)
00684         .addImm(0)
00685         .addImm(64 - Log2_32(MaxAlign));
00686     else // PPC32...
00687       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
00688         .addReg(SPReg)
00689         .addImm(0)
00690         .addImm(32 - Log2_32(MaxAlign))
00691         .addImm(31);
00692     if (!isLargeFrame) {
00693       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
00694         .addReg(ScratchReg, RegState::Kill)
00695         .addImm(NegFrameSize);
00696     } else {
00697       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
00698         .addImm(NegFrameSize >> 16);
00699       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
00700         .addReg(TempReg, RegState::Kill)
00701         .addImm(NegFrameSize & 0xFFFF);
00702       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
00703         .addReg(ScratchReg, RegState::Kill)
00704         .addReg(TempReg, RegState::Kill);
00705     }
00706     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00707       .addReg(SPReg, RegState::Kill)
00708       .addReg(SPReg)
00709       .addReg(ScratchReg);
00710 
00711   } else if (!isLargeFrame) {
00712     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
00713       .addReg(SPReg)
00714       .addImm(NegFrameSize)
00715       .addReg(SPReg);
00716 
00717   } else {
00718     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
00719       .addImm(NegFrameSize >> 16);
00720     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
00721       .addReg(ScratchReg, RegState::Kill)
00722       .addImm(NegFrameSize & 0xFFFF);
00723     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
00724       .addReg(SPReg, RegState::Kill)
00725       .addReg(SPReg)
00726       .addReg(ScratchReg);
00727   }
00728 
00729   // Add Call Frame Information for the instructions we generated above.
00730   if (needsCFI) {
00731     unsigned CFIIndex;
00732 
00733     if (HasBP) {
00734       // Define CFA in terms of BP. Do this in preference to using FP/SP,
00735       // because if the stack needed aligning then CFA won't be at a fixed
00736       // offset from FP/SP.
00737       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00738       CFIIndex = MMI.addFrameInst(
00739           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00740     } else {
00741       // Adjust the definition of CFA to account for the change in SP.
00742       assert(NegFrameSize);
00743       CFIIndex = MMI.addFrameInst(
00744           MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
00745     }
00746     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00747         .addCFIIndex(CFIIndex);
00748 
00749     if (HasFP) {
00750       // Describe where FP was saved, at a fixed offset from CFA.
00751       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00752       CFIIndex = MMI.addFrameInst(
00753           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
00754       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00755           .addCFIIndex(CFIIndex);
00756     }
00757 
00758     if (HasBP) {
00759       // Describe where BP was saved, at a fixed offset from CFA.
00760       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
00761       CFIIndex = MMI.addFrameInst(
00762           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
00763       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00764           .addCFIIndex(CFIIndex);
00765     }
00766 
00767     if (MustSaveLR) {
00768       // Describe where LR was saved, at a fixed offset from CFA.
00769       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
00770       CFIIndex = MMI.addFrameInst(
00771           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
00772       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00773           .addCFIIndex(CFIIndex);
00774     }
00775   }
00776 
00777   // If there is a frame pointer, copy R1 into R31
00778   if (HasFP) {
00779     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
00780       .addReg(SPReg)
00781       .addReg(SPReg);
00782 
00783     if (!HasBP && needsCFI) {
00784       // Change the definition of CFA from SP+offset to FP+offset, because SP
00785       // will change at every alloca.
00786       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
00787       unsigned CFIIndex = MMI.addFrameInst(
00788           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
00789 
00790       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00791           .addCFIIndex(CFIIndex);
00792     }
00793   }
00794 
00795   if (needsCFI) {
00796     // Describe where callee saved registers were saved, at fixed offsets from
00797     // CFA.
00798     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00799     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
00800       unsigned Reg = CSI[I].getReg();
00801       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
00802 
00803       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
00804       // subregisters of CR2. We just need to emit a move of CR2.
00805       if (PPC::CRBITRCRegClass.contains(Reg))
00806         continue;
00807 
00808       // For SVR4, don't emit a move for the CR spill slot if we haven't
00809       // spilled CRs.
00810       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
00811           && MustSaveCRs.empty())
00812         continue;
00813 
00814       // For 64-bit SVR4 when we have spilled CRs, the spill location
00815       // is SP+8, not a frame-relative slot.
00816       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
00817         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
00818         // the whole CR word.  In the ELFv2 ABI, every CR that was
00819         // actually saved gets its own CFI record.
00820         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
00821         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00822             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
00823         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00824             .addCFIIndex(CFIIndex);
00825         continue;
00826       }
00827 
00828       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
00829       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
00830           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
00831       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
00832           .addCFIIndex(CFIIndex);
00833     }
00834   }
00835 }
00836 
00837 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
00838                                 MachineBasicBlock &MBB) const {
00839   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
00840   assert(MBBI != MBB.end() && "Returning block has no terminator");
00841   const PPCInstrInfo &TII =
00842       *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
00843   const PPCRegisterInfo *RegInfo =
00844       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00845 
00846   unsigned RetOpcode = MBBI->getOpcode();
00847   DebugLoc dl;
00848 
00849   assert((RetOpcode == PPC::BLR ||
00850           RetOpcode == PPC::TCRETURNri ||
00851           RetOpcode == PPC::TCRETURNdi ||
00852           RetOpcode == PPC::TCRETURNai ||
00853           RetOpcode == PPC::TCRETURNri8 ||
00854           RetOpcode == PPC::TCRETURNdi8 ||
00855           RetOpcode == PPC::TCRETURNai8) &&
00856          "Can only insert epilog into returning blocks");
00857 
00858   // Get alignment info so we know how to restore the SP.
00859   const MachineFrameInfo *MFI = MF.getFrameInfo();
00860 
00861   // Get the number of bytes allocated from the FrameInfo.
00862   int FrameSize = MFI->getStackSize();
00863 
00864   // Get processor type.
00865   bool isPPC64 = Subtarget.isPPC64();
00866   // Get the ABI.
00867   bool isDarwinABI = Subtarget.isDarwinABI();
00868   bool isSVR4ABI = Subtarget.isSVR4ABI();
00869   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
00870 
00871   // Check if the link register (LR) has been saved.
00872   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
00873   bool MustSaveLR = FI->mustSaveLR();
00874   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
00875   // Do we have a frame pointer and/or base pointer for this function?
00876   bool HasFP = hasFP(MF);
00877   bool HasBP = RegInfo->hasBasePointer(MF);
00878 
00879   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
00880   unsigned BPReg      = RegInfo->getBaseRegister(MF);
00881   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
00882   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
00883   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
00884   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
00885                                                  : PPC::MTLR );
00886   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
00887                                                  : PPC::LWZ );
00888   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
00889                                                            : PPC::LIS );
00890   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
00891                                                   : PPC::ORI );
00892   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
00893                                                    : PPC::ADDI );
00894   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
00895                                                 : PPC::ADD4 );
00896 
00897   int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
00898 
00899   int FPOffset = 0;
00900   if (HasFP) {
00901     if (isSVR4ABI) {
00902       MachineFrameInfo *FFI = MF.getFrameInfo();
00903       int FPIndex = FI->getFramePointerSaveIndex();
00904       assert(FPIndex && "No Frame Pointer Save Slot!");
00905       FPOffset = FFI->getObjectOffset(FPIndex);
00906     } else {
00907       FPOffset =
00908           PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
00909     }
00910   }
00911 
00912   int BPOffset = 0;
00913   if (HasBP) {
00914     if (isSVR4ABI) {
00915       MachineFrameInfo *FFI = MF.getFrameInfo();
00916       int BPIndex = FI->getBasePointerSaveIndex();
00917       assert(BPIndex && "No Base Pointer Save Slot!");
00918       BPOffset = FFI->getObjectOffset(BPIndex);
00919     } else {
00920       BPOffset =
00921         PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
00922                                                    isDarwinABI,
00923                                                    isPIC);
00924     }
00925   }
00926 
00927   bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
00928     RetOpcode == PPC::TCRETURNdi ||
00929     RetOpcode == PPC::TCRETURNai ||
00930     RetOpcode == PPC::TCRETURNri8 ||
00931     RetOpcode == PPC::TCRETURNdi8 ||
00932     RetOpcode == PPC::TCRETURNai8;
00933 
00934   if (UsesTCRet) {
00935     int MaxTCRetDelta = FI->getTailCallSPDelta();
00936     MachineOperand &StackAdjust = MBBI->getOperand(1);
00937     assert(StackAdjust.isImm() && "Expecting immediate value.");
00938     // Adjust stack pointer.
00939     int StackAdj = StackAdjust.getImm();
00940     int Delta = StackAdj - MaxTCRetDelta;
00941     assert((Delta >= 0) && "Delta must be positive");
00942     if (MaxTCRetDelta>0)
00943       FrameSize += (StackAdj +Delta);
00944     else
00945       FrameSize += StackAdj;
00946   }
00947 
00948   // Frames of 32KB & larger require special handling because they cannot be
00949   // indexed into with a simple LD/LWZ immediate offset operand.
00950   bool isLargeFrame = !isInt<16>(FrameSize);
00951 
00952   if (FrameSize) {
00953     // In the prologue, the loaded (or persistent) stack pointer value is offset
00954     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
00955 
00956     // If this function contained a fastcc call and GuaranteedTailCallOpt is
00957     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
00958     // call which invalidates the stack pointer value in SP(0). So we use the
00959     // value of R31 in this case.
00960     if (FI->hasFastCall()) {
00961       assert(HasFP && "Expecting a valid frame pointer.");
00962       if (!isLargeFrame) {
00963         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
00964           .addReg(FPReg).addImm(FrameSize);
00965       } else {
00966         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
00967           .addImm(FrameSize >> 16);
00968         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
00969           .addReg(ScratchReg, RegState::Kill)
00970           .addImm(FrameSize & 0xFFFF);
00971         BuildMI(MBB, MBBI, dl, AddInst)
00972           .addReg(SPReg)
00973           .addReg(FPReg)
00974           .addReg(ScratchReg);
00975       }
00976     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
00977       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
00978         .addReg(SPReg)
00979         .addImm(FrameSize);
00980     } else {
00981       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
00982         .addImm(0)
00983         .addReg(SPReg);
00984     }
00985 
00986   }
00987 
00988   if (MustSaveLR)
00989     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
00990       .addImm(LROffset)
00991       .addReg(SPReg);
00992 
00993   assert((isPPC64 || MustSaveCRs.empty()) &&
00994          "Epilogue CR restoring supported only in 64-bit mode");
00995 
00996   if (!MustSaveCRs.empty()) // will only occur for PPC64
00997     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
00998       .addImm(8)
00999       .addReg(SPReg);
01000 
01001   if (HasFP)
01002     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
01003       .addImm(FPOffset)
01004       .addReg(SPReg);
01005 
01006   if (HasBP)
01007     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
01008       .addImm(BPOffset)
01009       .addReg(SPReg);
01010 
01011   if (!MustSaveCRs.empty()) // will only occur for PPC64
01012     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
01013       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
01014         .addReg(TempReg, getKillRegState(i == e-1));
01015 
01016   if (MustSaveLR)
01017     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
01018 
01019   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
01020   // call optimization
01021   if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
01022       MF.getFunction()->getCallingConv() == CallingConv::Fast) {
01023      PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01024      unsigned CallerAllocatedAmt = FI->getMinReservedArea();
01025 
01026      if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
01027        BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
01028          .addReg(SPReg).addImm(CallerAllocatedAmt);
01029      } else {
01030        BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
01031           .addImm(CallerAllocatedAmt >> 16);
01032        BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
01033           .addReg(ScratchReg, RegState::Kill)
01034           .addImm(CallerAllocatedAmt & 0xFFFF);
01035        BuildMI(MBB, MBBI, dl, AddInst)
01036           .addReg(SPReg)
01037           .addReg(FPReg)
01038           .addReg(ScratchReg);
01039      }
01040   } else if (RetOpcode == PPC::TCRETURNdi) {
01041     MBBI = MBB.getLastNonDebugInstr();
01042     MachineOperand &JumpTarget = MBBI->getOperand(0);
01043     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
01044       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01045   } else if (RetOpcode == PPC::TCRETURNri) {
01046     MBBI = MBB.getLastNonDebugInstr();
01047     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01048     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
01049   } else if (RetOpcode == PPC::TCRETURNai) {
01050     MBBI = MBB.getLastNonDebugInstr();
01051     MachineOperand &JumpTarget = MBBI->getOperand(0);
01052     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
01053   } else if (RetOpcode == PPC::TCRETURNdi8) {
01054     MBBI = MBB.getLastNonDebugInstr();
01055     MachineOperand &JumpTarget = MBBI->getOperand(0);
01056     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
01057       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
01058   } else if (RetOpcode == PPC::TCRETURNri8) {
01059     MBBI = MBB.getLastNonDebugInstr();
01060     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
01061     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
01062   } else if (RetOpcode == PPC::TCRETURNai8) {
01063     MBBI = MBB.getLastNonDebugInstr();
01064     MachineOperand &JumpTarget = MBBI->getOperand(0);
01065     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
01066   }
01067 }
01068 
01069 /// MustSaveLR - Return true if this function requires that we save the LR
01070 /// register onto the stack in the prolog and restore it in the epilog of the
01071 /// function.
01072 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
01073   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
01074 
01075   // We need a save/restore of LR if there is any def of LR (which is
01076   // defined by calls, including the PIC setup sequence), or if there is
01077   // some use of the LR stack slot (e.g. for builtin_return_address).
01078   // (LR comes in 32 and 64 bit versions.)
01079   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
01080   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
01081 }
01082 
01083 void
01084 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
01085                                                    RegScavenger *) const {
01086   const PPCRegisterInfo *RegInfo =
01087       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01088 
01089   //  Save and clear the LR state.
01090   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
01091   unsigned LR = RegInfo->getRARegister();
01092   FI->setMustSaveLR(MustSaveLR(MF, LR));
01093   MachineRegisterInfo &MRI = MF.getRegInfo();
01094   MRI.setPhysRegUnused(LR);
01095 
01096   //  Save R31 if necessary
01097   int FPSI = FI->getFramePointerSaveIndex();
01098   bool isPPC64 = Subtarget.isPPC64();
01099   bool isDarwinABI  = Subtarget.isDarwinABI();
01100   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
01101   MachineFrameInfo *MFI = MF.getFrameInfo();
01102 
01103   // If the frame pointer save index hasn't been defined yet.
01104   if (!FPSI && needsFP(MF)) {
01105     // Find out what the fix offset of the frame pointer save area.
01106     int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
01107     // Allocate the frame index for frame pointer save area.
01108     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
01109     // Save the result.
01110     FI->setFramePointerSaveIndex(FPSI);
01111   }
01112 
01113   int BPSI = FI->getBasePointerSaveIndex();
01114   if (!BPSI && RegInfo->hasBasePointer(MF)) {
01115     int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
01116     // Allocate the frame index for the base pointer save area.
01117     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
01118     // Save the result.
01119     FI->setBasePointerSaveIndex(BPSI);
01120   }
01121 
01122   // Reserve stack space to move the linkage area to in case of a tail call.
01123   int TCSPDelta = 0;
01124   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01125       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
01126     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
01127   }
01128 
01129   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
01130   // function uses CR 2, 3, or 4.
01131   if (!isPPC64 && !isDarwinABI &&
01132       (MRI.isPhysRegUsed(PPC::CR2) ||
01133        MRI.isPhysRegUsed(PPC::CR3) ||
01134        MRI.isPhysRegUsed(PPC::CR4))) {
01135     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
01136     FI->setCRSpillFrameIndex(FrameIdx);
01137   }
01138 }
01139 
01140 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
01141                                                        RegScavenger *RS) const {
01142   // Early exit if not using the SVR4 ABI.
01143   if (!Subtarget.isSVR4ABI()) {
01144     addScavengingSpillSlot(MF, RS);
01145     return;
01146   }
01147 
01148   // Get callee saved register information.
01149   MachineFrameInfo *FFI = MF.getFrameInfo();
01150   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
01151 
01152   // Early exit if no callee saved registers are modified!
01153   if (CSI.empty() && !needsFP(MF)) {
01154     addScavengingSpillSlot(MF, RS);
01155     return;
01156   }
01157 
01158   unsigned MinGPR = PPC::R31;
01159   unsigned MinG8R = PPC::X31;
01160   unsigned MinFPR = PPC::F31;
01161   unsigned MinVR = PPC::V31;
01162 
01163   bool HasGPSaveArea = false;
01164   bool HasG8SaveArea = false;
01165   bool HasFPSaveArea = false;
01166   bool HasVRSAVESaveArea = false;
01167   bool HasVRSaveArea = false;
01168 
01169   SmallVector<CalleeSavedInfo, 18> GPRegs;
01170   SmallVector<CalleeSavedInfo, 18> G8Regs;
01171   SmallVector<CalleeSavedInfo, 18> FPRegs;
01172   SmallVector<CalleeSavedInfo, 18> VRegs;
01173 
01174   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01175     unsigned Reg = CSI[i].getReg();
01176     if (PPC::GPRCRegClass.contains(Reg)) {
01177       HasGPSaveArea = true;
01178 
01179       GPRegs.push_back(CSI[i]);
01180 
01181       if (Reg < MinGPR) {
01182         MinGPR = Reg;
01183       }
01184     } else if (PPC::G8RCRegClass.contains(Reg)) {
01185       HasG8SaveArea = true;
01186 
01187       G8Regs.push_back(CSI[i]);
01188 
01189       if (Reg < MinG8R) {
01190         MinG8R = Reg;
01191       }
01192     } else if (PPC::F8RCRegClass.contains(Reg)) {
01193       HasFPSaveArea = true;
01194 
01195       FPRegs.push_back(CSI[i]);
01196 
01197       if (Reg < MinFPR) {
01198         MinFPR = Reg;
01199       }
01200     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
01201                PPC::CRRCRegClass.contains(Reg)) {
01202       ; // do nothing, as we already know whether CRs are spilled
01203     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
01204       HasVRSAVESaveArea = true;
01205     } else if (PPC::VRRCRegClass.contains(Reg)) {
01206       HasVRSaveArea = true;
01207 
01208       VRegs.push_back(CSI[i]);
01209 
01210       if (Reg < MinVR) {
01211         MinVR = Reg;
01212       }
01213     } else {
01214       llvm_unreachable("Unknown RegisterClass!");
01215     }
01216   }
01217 
01218   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
01219   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
01220 
01221   int64_t LowerBound = 0;
01222 
01223   // Take into account stack space reserved for tail calls.
01224   int TCSPDelta = 0;
01225   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01226       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
01227     LowerBound = TCSPDelta;
01228   }
01229 
01230   // The Floating-point register save area is right below the back chain word
01231   // of the previous stack frame.
01232   if (HasFPSaveArea) {
01233     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
01234       int FI = FPRegs[i].getFrameIdx();
01235 
01236       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01237     }
01238 
01239     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
01240   }
01241 
01242   // Check whether the frame pointer register is allocated. If so, make sure it
01243   // is spilled to the correct offset.
01244   if (needsFP(MF)) {
01245     HasGPSaveArea = true;
01246 
01247     int FI = PFI->getFramePointerSaveIndex();
01248     assert(FI && "No Frame Pointer Save Slot!");
01249 
01250     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01251   }
01252 
01253   const PPCRegisterInfo *RegInfo =
01254       static_cast<const PPCRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01255   if (RegInfo->hasBasePointer(MF)) {
01256     HasGPSaveArea = true;
01257 
01258     int FI = PFI->getBasePointerSaveIndex();
01259     assert(FI && "No Base Pointer Save Slot!");
01260 
01261     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01262   }
01263 
01264   // General register save area starts right below the Floating-point
01265   // register save area.
01266   if (HasGPSaveArea || HasG8SaveArea) {
01267     // Move general register save area spill slots down, taking into account
01268     // the size of the Floating-point register save area.
01269     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
01270       int FI = GPRegs[i].getFrameIdx();
01271 
01272       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01273     }
01274 
01275     // Move general register save area spill slots down, taking into account
01276     // the size of the Floating-point register save area.
01277     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
01278       int FI = G8Regs[i].getFrameIdx();
01279 
01280       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01281     }
01282 
01283     unsigned MinReg =
01284       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
01285                          TRI->getEncodingValue(MinG8R));
01286 
01287     if (Subtarget.isPPC64()) {
01288       LowerBound -= (31 - MinReg + 1) * 8;
01289     } else {
01290       LowerBound -= (31 - MinReg + 1) * 4;
01291     }
01292   }
01293 
01294   // For 32-bit only, the CR save area is below the general register
01295   // save area.  For 64-bit SVR4, the CR save area is addressed relative
01296   // to the stack pointer and hence does not need an adjustment here.
01297   // Only CR2 (the first nonvolatile spilled) has an associated frame
01298   // index so that we have a single uniform save area.
01299   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
01300     // Adjust the frame index of the CR spill slot.
01301     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01302       unsigned Reg = CSI[i].getReg();
01303 
01304       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
01305           // Leave Darwin logic as-is.
01306           || (!Subtarget.isSVR4ABI() &&
01307               (PPC::CRBITRCRegClass.contains(Reg) ||
01308                PPC::CRRCRegClass.contains(Reg)))) {
01309         int FI = CSI[i].getFrameIdx();
01310 
01311         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01312       }
01313     }
01314 
01315     LowerBound -= 4; // The CR save area is always 4 bytes long.
01316   }
01317 
01318   if (HasVRSAVESaveArea) {
01319     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
01320     //             which have the VRSAVE register class?
01321     // Adjust the frame index of the VRSAVE spill slot.
01322     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01323       unsigned Reg = CSI[i].getReg();
01324 
01325       if (PPC::VRSAVERCRegClass.contains(Reg)) {
01326         int FI = CSI[i].getFrameIdx();
01327 
01328         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01329       }
01330     }
01331 
01332     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
01333   }
01334 
01335   if (HasVRSaveArea) {
01336     // Insert alignment padding, we need 16-byte alignment.
01337     LowerBound = (LowerBound - 15) & ~(15);
01338 
01339     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
01340       int FI = VRegs[i].getFrameIdx();
01341 
01342       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
01343     }
01344   }
01345 
01346   addScavengingSpillSlot(MF, RS);
01347 }
01348 
01349 void
01350 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
01351                                          RegScavenger *RS) const {
01352   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
01353   // a large stack, which will require scavenging a register to materialize a
01354   // large offset.
01355 
01356   // We need to have a scavenger spill slot for spills if the frame size is
01357   // large. In case there is no free register for large-offset addressing,
01358   // this slot is used for the necessary emergency spill. Also, we need the
01359   // slot for dynamic stack allocations.
01360 
01361   // The scavenger might be invoked if the frame offset does not fit into
01362   // the 16-bit immediate. We don't know the complete frame size here
01363   // because we've not yet computed callee-saved register spills or the
01364   // needed alignment padding.
01365   unsigned StackSize = determineFrameLayout(MF, false, true);
01366   MachineFrameInfo *MFI = MF.getFrameInfo();
01367   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
01368       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
01369     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
01370     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
01371     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
01372     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01373                                                        RC->getAlignment(),
01374                                                        false));
01375 
01376     // Might we have over-aligned allocas?
01377     bool HasAlVars = MFI->hasVarSizedObjects() &&
01378                      MFI->getMaxAlignment() > getStackAlignment();
01379 
01380     // These kinds of spills might need two registers.
01381     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
01382       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
01383                                                          RC->getAlignment(),
01384                                                          false));
01385 
01386   }
01387 }
01388 
01389 bool
01390 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
01391                                      MachineBasicBlock::iterator MI,
01392                                      const std::vector<CalleeSavedInfo> &CSI,
01393                                      const TargetRegisterInfo *TRI) const {
01394 
01395   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01396   // Return false otherwise to maintain pre-existing behavior.
01397   if (!Subtarget.isSVR4ABI())
01398     return false;
01399 
01400   MachineFunction *MF = MBB.getParent();
01401   const PPCInstrInfo &TII =
01402       *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
01403   DebugLoc DL;
01404   bool CRSpilled = false;
01405   MachineInstrBuilder CRMIB;
01406 
01407   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01408     unsigned Reg = CSI[i].getReg();
01409     // Only Darwin actually uses the VRSAVE register, but it can still appear
01410     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01411     // Darwin, ignore it.
01412     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01413       continue;
01414 
01415     // CR2 through CR4 are the nonvolatile CR fields.
01416     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
01417 
01418     // Add the callee-saved register as live-in; it's killed at the spill.
01419     MBB.addLiveIn(Reg);
01420 
01421     if (CRSpilled && IsCRField) {
01422       CRMIB.addReg(Reg, RegState::ImplicitKill);
01423       continue;
01424     }
01425 
01426     // Insert the spill to the stack frame.
01427     if (IsCRField) {
01428       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
01429       if (Subtarget.isPPC64()) {
01430         // The actual spill will happen at the start of the prologue.
01431         FuncInfo->addMustSaveCR(Reg);
01432       } else {
01433         CRSpilled = true;
01434         FuncInfo->setSpillsCR();
01435 
01436         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
01437         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
01438         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
01439                   .addReg(Reg, RegState::ImplicitKill);
01440 
01441         MBB.insert(MI, CRMIB);
01442         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
01443                                          .addReg(PPC::R12,
01444                                                  getKillRegState(true)),
01445                                          CSI[i].getFrameIdx()));
01446       }
01447     } else {
01448       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01449       TII.storeRegToStackSlot(MBB, MI, Reg, true,
01450                               CSI[i].getFrameIdx(), RC, TRI);
01451     }
01452   }
01453   return true;
01454 }
01455 
01456 static void
01457 restoreCRs(bool isPPC64, bool is31,
01458            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
01459            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01460            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
01461 
01462   MachineFunction *MF = MBB.getParent();
01463   const PPCInstrInfo &TII =
01464       *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
01465   DebugLoc DL;
01466   unsigned RestoreOp, MoveReg;
01467 
01468   if (isPPC64)
01469     // This is handled during epilogue generation.
01470     return;
01471   else {
01472     // 32-bit:  FP-relative
01473     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
01474                                              PPC::R12),
01475                                      CSI[CSIIndex].getFrameIdx()));
01476     RestoreOp = PPC::MTOCRF;
01477     MoveReg = PPC::R12;
01478   }
01479 
01480   if (CR2Spilled)
01481     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
01482                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
01483 
01484   if (CR3Spilled)
01485     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
01486                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
01487 
01488   if (CR4Spilled)
01489     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
01490                .addReg(MoveReg, getKillRegState(true)));
01491 }
01492 
01493 void PPCFrameLowering::
01494 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01495                               MachineBasicBlock::iterator I) const {
01496   const PPCInstrInfo &TII =
01497       *static_cast<const PPCInstrInfo *>(MF.getSubtarget().getInstrInfo());
01498   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
01499       I->getOpcode() == PPC::ADJCALLSTACKUP) {
01500     // Add (actually subtract) back the amount the callee popped on return.
01501     if (int CalleeAmt =  I->getOperand(1).getImm()) {
01502       bool is64Bit = Subtarget.isPPC64();
01503       CalleeAmt *= -1;
01504       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
01505       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
01506       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
01507       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
01508       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
01509       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
01510       MachineInstr *MI = I;
01511       DebugLoc dl = MI->getDebugLoc();
01512 
01513       if (isInt<16>(CalleeAmt)) {
01514         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
01515           .addReg(StackReg, RegState::Kill)
01516           .addImm(CalleeAmt);
01517       } else {
01518         MachineBasicBlock::iterator MBBI = I;
01519         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
01520           .addImm(CalleeAmt >> 16);
01521         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
01522           .addReg(TmpReg, RegState::Kill)
01523           .addImm(CalleeAmt & 0xFFFF);
01524         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
01525           .addReg(StackReg, RegState::Kill)
01526           .addReg(TmpReg);
01527       }
01528     }
01529   }
01530   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
01531   MBB.erase(I);
01532 }
01533 
01534 bool
01535 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01536                                         MachineBasicBlock::iterator MI,
01537                                         const std::vector<CalleeSavedInfo> &CSI,
01538                                         const TargetRegisterInfo *TRI) const {
01539 
01540   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
01541   // Return false otherwise to maintain pre-existing behavior.
01542   if (!Subtarget.isSVR4ABI())
01543     return false;
01544 
01545   MachineFunction *MF = MBB.getParent();
01546   const PPCInstrInfo &TII =
01547       *static_cast<const PPCInstrInfo *>(MF->getSubtarget().getInstrInfo());
01548   bool CR2Spilled = false;
01549   bool CR3Spilled = false;
01550   bool CR4Spilled = false;
01551   unsigned CSIIndex = 0;
01552 
01553   // Initialize insertion-point logic; we will be restoring in reverse
01554   // order of spill.
01555   MachineBasicBlock::iterator I = MI, BeforeI = I;
01556   bool AtStart = I == MBB.begin();
01557 
01558   if (!AtStart)
01559     --BeforeI;
01560 
01561   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01562     unsigned Reg = CSI[i].getReg();
01563 
01564     // Only Darwin actually uses the VRSAVE register, but it can still appear
01565     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
01566     // Darwin, ignore it.
01567     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
01568       continue;
01569 
01570     if (Reg == PPC::CR2) {
01571       CR2Spilled = true;
01572       // The spill slot is associated only with CR2, which is the
01573       // first nonvolatile spilled.  Save it here.
01574       CSIIndex = i;
01575       continue;
01576     } else if (Reg == PPC::CR3) {
01577       CR3Spilled = true;
01578       continue;
01579     } else if (Reg == PPC::CR4) {
01580       CR4Spilled = true;
01581       continue;
01582     } else {
01583       // When we first encounter a non-CR register after seeing at
01584       // least one CR register, restore all spilled CRs together.
01585       if ((CR2Spilled || CR3Spilled || CR4Spilled)
01586           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
01587         bool is31 = needsFP(*MF);
01588         restoreCRs(Subtarget.isPPC64(), is31,
01589                    CR2Spilled, CR3Spilled, CR4Spilled,
01590                    MBB, I, CSI, CSIIndex);
01591         CR2Spilled = CR3Spilled = CR4Spilled = false;
01592       }
01593 
01594       // Default behavior for non-CR saves.
01595       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01596       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
01597                                RC, TRI);
01598       assert(I != MBB.begin() &&
01599              "loadRegFromStackSlot didn't insert any code!");
01600       }
01601 
01602     // Insert in reverse order.
01603     if (AtStart)
01604       I = MBB.begin();
01605     else {
01606       I = BeforeI;
01607       ++I;
01608     }
01609   }
01610 
01611   // If we haven't yet spilled the CRs, do so now.
01612   if (CR2Spilled || CR3Spilled || CR4Spilled) {
01613     bool is31 = needsFP(*MF);
01614     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
01615                MBB, I, CSI, CSIIndex);
01616   }
01617 
01618   return true;
01619 }