51d88628262dddd00212623979c685185789d3a7
[oota-llvm.git] / lib / Target / PowerPC / PPCFrameLowering.cpp
1 //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the PPC implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
27
28 using namespace llvm;
29
30 /// VRRegNo - Map from a numbered VR register to its enum value.
31 ///
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
37 };
38
39 PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
40     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
41                           (STI.hasQPX() || STI.isBGQ()) ? 32 : 16, 0),
42       Subtarget(STI) {}
43
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()) {
48     NumEntries = 1;
49     if (Subtarget.isPPC64()) {
50       static const SpillSlot darwin64Offsets = {PPC::X31, -8};
51       return &darwin64Offsets;
52     } else {
53       static const SpillSlot darwinOffsets = {PPC::R31, -4};
54       return &darwinOffsets;
55     }
56   }
57
58   // Early exit if not using the SVR4 ABI.
59   if (!Subtarget.isSVR4ABI()) {
60     NumEntries = 0;
61     return nullptr;
62   }
63
64   // Note that the offsets here overlap, but this is fixed up in
65   // processFunctionBeforeFrameFinalized.
66
67   static const SpillSlot Offsets[] = {
68       // Floating-point register save area offsets.
69       {PPC::F31, -8},
70       {PPC::F30, -16},
71       {PPC::F29, -24},
72       {PPC::F28, -32},
73       {PPC::F27, -40},
74       {PPC::F26, -48},
75       {PPC::F25, -56},
76       {PPC::F24, -64},
77       {PPC::F23, -72},
78       {PPC::F22, -80},
79       {PPC::F21, -88},
80       {PPC::F20, -96},
81       {PPC::F19, -104},
82       {PPC::F18, -112},
83       {PPC::F17, -120},
84       {PPC::F16, -128},
85       {PPC::F15, -136},
86       {PPC::F14, -144},
87
88       // General register save area offsets.
89       {PPC::R31, -4},
90       {PPC::R30, -8},
91       {PPC::R29, -12},
92       {PPC::R28, -16},
93       {PPC::R27, -20},
94       {PPC::R26, -24},
95       {PPC::R25, -28},
96       {PPC::R24, -32},
97       {PPC::R23, -36},
98       {PPC::R22, -40},
99       {PPC::R21, -44},
100       {PPC::R20, -48},
101       {PPC::R19, -52},
102       {PPC::R18, -56},
103       {PPC::R17, -60},
104       {PPC::R16, -64},
105       {PPC::R15, -68},
106       {PPC::R14, -72},
107
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.
112       {PPC::CR2, -4},
113
114       // VRSAVE save area offset.
115       {PPC::VRSAVE, -4},
116
117       // Vector register save area
118       {PPC::V31, -16},
119       {PPC::V30, -32},
120       {PPC::V29, -48},
121       {PPC::V28, -64},
122       {PPC::V27, -80},
123       {PPC::V26, -96},
124       {PPC::V25, -112},
125       {PPC::V24, -128},
126       {PPC::V23, -144},
127       {PPC::V22, -160},
128       {PPC::V21, -176},
129       {PPC::V20, -192}};
130
131   static const SpillSlot Offsets64[] = {
132       // Floating-point register save area offsets.
133       {PPC::F31, -8},
134       {PPC::F30, -16},
135       {PPC::F29, -24},
136       {PPC::F28, -32},
137       {PPC::F27, -40},
138       {PPC::F26, -48},
139       {PPC::F25, -56},
140       {PPC::F24, -64},
141       {PPC::F23, -72},
142       {PPC::F22, -80},
143       {PPC::F21, -88},
144       {PPC::F20, -96},
145       {PPC::F19, -104},
146       {PPC::F18, -112},
147       {PPC::F17, -120},
148       {PPC::F16, -128},
149       {PPC::F15, -136},
150       {PPC::F14, -144},
151
152       // General register save area offsets.
153       {PPC::X31, -8},
154       {PPC::X30, -16},
155       {PPC::X29, -24},
156       {PPC::X28, -32},
157       {PPC::X27, -40},
158       {PPC::X26, -48},
159       {PPC::X25, -56},
160       {PPC::X24, -64},
161       {PPC::X23, -72},
162       {PPC::X22, -80},
163       {PPC::X21, -88},
164       {PPC::X20, -96},
165       {PPC::X19, -104},
166       {PPC::X18, -112},
167       {PPC::X17, -120},
168       {PPC::X16, -128},
169       {PPC::X15, -136},
170       {PPC::X14, -144},
171
172       // VRSAVE save area offset.
173       {PPC::VRSAVE, -4},
174
175       // Vector register save area
176       {PPC::V31, -16},
177       {PPC::V30, -32},
178       {PPC::V29, -48},
179       {PPC::V28, -64},
180       {PPC::V27, -80},
181       {PPC::V26, -96},
182       {PPC::V25, -112},
183       {PPC::V24, -128},
184       {PPC::V23, -144},
185       {PPC::V22, -160},
186       {PPC::V21, -176},
187       {PPC::V20, -192}};
188
189   if (Subtarget.isPPC64()) {
190     NumEntries = array_lengthof(Offsets64);
191
192     return Offsets64;
193   } else {
194     NumEntries = array_lengthof(Offsets);
195
196     return Offsets;
197   }
198 }
199
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();
212
213   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
214   MachineBasicBlock::iterator MBBI = MI;
215   ++MBBI;
216   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
217   MBBI->eraseFromParent();
218
219   bool RemovedAllMTVRSAVEs = true;
220   // See if we can find and remove the MTVRSAVE instruction from all of the
221   // epilog blocks.
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(); ) {
227         --MBBI;
228         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
229           MBBI->eraseFromParent();  // remove it.
230           FoundIt = true;
231           break;
232         }
233       }
234       RemovedAllMTVRSAVEs &= FoundIt;
235     }
236   }
237
238   // If we found and removed all MTVRSAVE instructions, remove the read of
239   // VRSAVE as well.
240   if (RemovedAllMTVRSAVEs) {
241     MBBI = MI;
242     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
243     --MBBI;
244     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
245     MBBI->eraseFromParent();
246   }
247
248   // Finally, nuke the UPDATE_VRSAVE.
249   MI->eraseFromParent();
250 }
251
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 =
258       MF->getTarget().getSubtargetImpl()->getRegisterInfo();
259   DebugLoc dl = MI->getDebugLoc();
260
261   unsigned UsedRegMask = 0;
262   for (unsigned i = 0; i != 32; ++i)
263     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
264       UsedRegMask |= 1 << (31-i);
265
266   // Live in and live out values already must be in the mask, so don't bother
267   // marking them.
268   for (MachineRegisterInfo::livein_iterator
269        I = MF->getRegInfo().livein_begin(),
270        E = MF->getRegInfo().livein_end(); I != E; ++I) {
271     unsigned RegNo = TRI->getEncodingValue(I->first);
272     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
273       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
274   }
275
276   // Live out registers appear as use operands on return instructions.
277   for (MachineFunction::const_iterator BI = MF->begin(), BE = MF->end();
278        UsedRegMask != 0 && BI != BE; ++BI) {
279     const MachineBasicBlock &MBB = *BI;
280     if (MBB.empty() || !MBB.back().isReturn())
281       continue;
282     const MachineInstr &Ret = MBB.back();
283     for (unsigned I = 0, E = Ret.getNumOperands(); I != E; ++I) {
284       const MachineOperand &MO = Ret.getOperand(I);
285       if (!MO.isReg() || !PPC::VRRCRegClass.contains(MO.getReg()))
286         continue;
287       unsigned RegNo = TRI->getEncodingValue(MO.getReg());
288       UsedRegMask &= ~(1 << (31-RegNo));
289     }
290   }
291
292   // If no registers are used, turn this into a copy.
293   if (UsedRegMask == 0) {
294     // Remove all VRSAVE code.
295     RemoveVRSaveCode(MI);
296     return;
297   }
298
299   unsigned SrcReg = MI->getOperand(1).getReg();
300   unsigned DstReg = MI->getOperand(0).getReg();
301
302   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
303     if (DstReg != SrcReg)
304       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
305         .addReg(SrcReg)
306         .addImm(UsedRegMask);
307     else
308       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
309         .addReg(SrcReg, RegState::Kill)
310         .addImm(UsedRegMask);
311   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
312     if (DstReg != SrcReg)
313       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
314         .addReg(SrcReg)
315         .addImm(UsedRegMask >> 16);
316     else
317       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
318         .addReg(SrcReg, RegState::Kill)
319         .addImm(UsedRegMask >> 16);
320   } else {
321     if (DstReg != SrcReg)
322       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
323         .addReg(SrcReg)
324         .addImm(UsedRegMask >> 16);
325     else
326       BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
327         .addReg(SrcReg, RegState::Kill)
328         .addImm(UsedRegMask >> 16);
329
330     BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
331       .addReg(DstReg, RegState::Kill)
332       .addImm(UsedRegMask & 0xFFFF);
333   }
334
335   // Remove the old UPDATE_VRSAVE instruction.
336   MI->eraseFromParent();
337 }
338
339 static bool spillsCR(const MachineFunction &MF) {
340   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
341   return FuncInfo->isCRSpilled();
342 }
343
344 static bool spillsVRSAVE(const MachineFunction &MF) {
345   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
346   return FuncInfo->isVRSAVESpilled();
347 }
348
349 static bool hasSpills(const MachineFunction &MF) {
350   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
351   return FuncInfo->hasSpills();
352 }
353
354 static bool hasNonRISpills(const MachineFunction &MF) {
355   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
356   return FuncInfo->hasNonRISpills();
357 }
358
359 /// determineFrameLayout - Determine the size of the frame and maximum call
360 /// frame size.
361 unsigned PPCFrameLowering::determineFrameLayout(MachineFunction &MF,
362                                                 bool UpdateMF,
363                                                 bool UseEstimate) const {
364   MachineFrameInfo *MFI = MF.getFrameInfo();
365
366   // Get the number of bytes to allocate from the FrameInfo
367   unsigned FrameSize =
368     UseEstimate ? MFI->estimateStackSize(MF) : MFI->getStackSize();
369
370   // Get stack alignments. The frame must be aligned to the greatest of these:
371   unsigned TargetAlign = getStackAlignment(); // alignment required per the ABI
372   unsigned MaxAlign = MFI->getMaxAlignment(); // algmt required by data in frame
373   unsigned AlignMask = std::max(MaxAlign, TargetAlign) - 1;
374
375   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
376       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
377
378   // If we are a leaf function, and use up to 224 bytes of stack space,
379   // don't have a frame pointer, calls, or dynamic alloca then we do not need
380   // to adjust the stack pointer (we fit in the Red Zone).
381   // The 32-bit SVR4 ABI has no Red Zone. However, it can still generate
382   // stackless code if all local vars are reg-allocated.
383   bool DisableRedZone = MF.getFunction()->getAttributes().
384     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoRedZone);
385   if (!DisableRedZone &&
386       (Subtarget.isPPC64() ||                      // 32-bit SVR4, no stack-
387        !Subtarget.isSVR4ABI() ||                   //   allocated locals.
388         FrameSize == 0) &&
389       FrameSize <= 224 &&                          // Fits in red zone.
390       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
391       !MFI->adjustsStack() &&                      // No calls.
392       !RegInfo->hasBasePointer(MF)) { // No special alignment.
393     // No need for frame
394     if (UpdateMF)
395       MFI->setStackSize(0);
396     return 0;
397   }
398
399   // Get the maximum call frame size of all the calls.
400   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
401
402   // Maximum call frame needs to be at least big enough for linkage area.
403   unsigned minCallFrameSize = getLinkageSize(Subtarget.isPPC64(),
404                                              Subtarget.isDarwinABI(),
405                                              Subtarget.isELFv2ABI());
406   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
407
408   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
409   // that allocations will be aligned.
410   if (MFI->hasVarSizedObjects())
411     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
412
413   // Update maximum call frame size.
414   if (UpdateMF)
415     MFI->setMaxCallFrameSize(maxCallFrameSize);
416
417   // Include call frame size in total.
418   FrameSize += maxCallFrameSize;
419
420   // Make sure the frame is aligned.
421   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
422
423   // Update frame info.
424   if (UpdateMF)
425     MFI->setStackSize(FrameSize);
426
427   return FrameSize;
428 }
429
430 // hasFP - Return true if the specified function actually has a dedicated frame
431 // pointer register.
432 bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
433   const MachineFrameInfo *MFI = MF.getFrameInfo();
434   // FIXME: This is pretty much broken by design: hasFP() might be called really
435   // early, before the stack layout was calculated and thus hasFP() might return
436   // true or false here depending on the time of call.
437   return (MFI->getStackSize()) && needsFP(MF);
438 }
439
440 // needsFP - Return true if the specified function should have a dedicated frame
441 // pointer register.  This is true if the function has variable sized allocas or
442 // if frame pointer elimination is disabled.
443 bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
444   const MachineFrameInfo *MFI = MF.getFrameInfo();
445
446   // Naked functions have no stack frame pushed, so we don't have a frame
447   // pointer.
448   if (MF.getFunction()->getAttributes().hasAttribute(
449           AttributeSet::FunctionIndex, Attribute::Naked))
450     return false;
451
452   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
453     MFI->hasVarSizedObjects() ||
454     (MF.getTarget().Options.GuaranteedTailCallOpt &&
455      MF.getInfo<PPCFunctionInfo>()->hasFastCall());
456 }
457
458 void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
459   bool is31 = needsFP(MF);
460   unsigned FPReg  = is31 ? PPC::R31 : PPC::R1;
461   unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
462
463   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
464       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
465   bool HasBP = RegInfo->hasBasePointer(MF);
466   unsigned BPReg  = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
467   unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FPReg;
468
469   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
470        BI != BE; ++BI)
471     for (MachineBasicBlock::iterator MBBI = BI->end(); MBBI != BI->begin(); ) {
472       --MBBI;
473       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
474         MachineOperand &MO = MBBI->getOperand(I);
475         if (!MO.isReg())
476           continue;
477
478         switch (MO.getReg()) {
479         case PPC::FP:
480           MO.setReg(FPReg);
481           break;
482         case PPC::FP8:
483           MO.setReg(FP8Reg);
484           break;
485         case PPC::BP:
486           MO.setReg(BPReg);
487           break;
488         case PPC::BP8:
489           MO.setReg(BP8Reg);
490           break;
491
492         }
493       }
494     }
495 }
496
497 void PPCFrameLowering::emitPrologue(MachineFunction &MF) const {
498   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
499   MachineBasicBlock::iterator MBBI = MBB.begin();
500   MachineFrameInfo *MFI = MF.getFrameInfo();
501   const PPCInstrInfo &TII =
502       *static_cast<const PPCInstrInfo *>(
503           MF.getTarget().getSubtargetImpl()->getInstrInfo());
504   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
505       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
506
507   MachineModuleInfo &MMI = MF.getMMI();
508   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
509   DebugLoc dl;
510   bool needsFrameMoves = MMI.hasDebugInfo() ||
511     MF.getFunction()->needsUnwindTableEntry();
512   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
513
514   // Get processor type.
515   bool isPPC64 = Subtarget.isPPC64();
516   // Get the ABI.
517   bool isDarwinABI = Subtarget.isDarwinABI();
518   bool isSVR4ABI = Subtarget.isSVR4ABI();
519   bool isELFv2ABI = Subtarget.isELFv2ABI();
520   assert((isDarwinABI || isSVR4ABI) &&
521          "Currently only Darwin and SVR4 ABIs are supported for PowerPC.");
522
523   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
524   // process it.
525   if (!isSVR4ABI)
526     for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
527       if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
528         HandleVRSaveUpdate(MBBI, TII);
529         break;
530       }
531     }
532
533   // Move MBBI back to the beginning of the function.
534   MBBI = MBB.begin();
535
536   // Work out frame sizes.
537   unsigned FrameSize = determineFrameLayout(MF);
538   int NegFrameSize = -FrameSize;
539   if (!isInt<32>(NegFrameSize))
540     llvm_unreachable("Unhandled stack size!");
541
542   if (MFI->isFrameAddressTaken())
543     replaceFPWithRealFP(MF);
544
545   // Check if the link register (LR) must be saved.
546   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
547   bool MustSaveLR = FI->mustSaveLR();
548   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
549   // Do we have a frame pointer and/or base pointer for this function?
550   bool HasFP = hasFP(MF);
551   bool HasBP = RegInfo->hasBasePointer(MF);
552
553   unsigned SPReg       = isPPC64 ? PPC::X1  : PPC::R1;
554   unsigned BPReg       = RegInfo->getBaseRegister(MF);
555   unsigned FPReg       = isPPC64 ? PPC::X31 : PPC::R31;
556   unsigned LRReg       = isPPC64 ? PPC::LR8 : PPC::LR;
557   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
558   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
559   //  ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
560   const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
561                                                 : PPC::MFLR );
562   const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
563                                                  : PPC::STW );
564   const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
565                                                      : PPC::STWU );
566   const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
567                                                         : PPC::STWUX);
568   const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
569                                                           : PPC::LIS );
570   const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
571                                                  : PPC::ORI );
572   const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
573                                               : PPC::OR );
574   const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
575                                                             : PPC::SUBFC);
576   const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
577                                                                : PPC::SUBFIC);
578
579   // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
580   // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
581   // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
582   // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
583   assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
584          "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
585
586   int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
587
588   int FPOffset = 0;
589   if (HasFP) {
590     if (isSVR4ABI) {
591       MachineFrameInfo *FFI = MF.getFrameInfo();
592       int FPIndex = FI->getFramePointerSaveIndex();
593       assert(FPIndex && "No Frame Pointer Save Slot!");
594       FPOffset = FFI->getObjectOffset(FPIndex);
595     } else {
596       FPOffset =
597           PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
598     }
599   }
600
601   int BPOffset = 0;
602   if (HasBP) {
603     if (isSVR4ABI) {
604       MachineFrameInfo *FFI = MF.getFrameInfo();
605       int BPIndex = FI->getBasePointerSaveIndex();
606       assert(BPIndex && "No Base Pointer Save Slot!");
607       BPOffset = FFI->getObjectOffset(BPIndex);
608     } else {
609       BPOffset =
610         PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
611                                                    isDarwinABI,
612                                                    isPIC);
613     }
614   }
615
616   // Get stack alignments.
617   unsigned MaxAlign = MFI->getMaxAlignment();
618   if (HasBP && MaxAlign > 1)
619     assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
620            "Invalid alignment!");
621
622   // Frames of 32KB & larger require special handling because they cannot be
623   // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
624   bool isLargeFrame = !isInt<16>(NegFrameSize);
625
626   if (MustSaveLR)
627     BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
628
629   assert((isPPC64 || MustSaveCRs.empty()) &&
630          "Prologue CR saving supported only in 64-bit mode");
631
632   if (!MustSaveCRs.empty()) { // will only occur for PPC64
633     // FIXME: In the ELFv2 ABI, we are not required to save all CR fields.
634     // If only one or two CR fields are clobbered, it could be more
635     // efficient to use mfocrf to selectively save just those fields.
636     MachineInstrBuilder MIB =
637       BuildMI(MBB, MBBI, dl, TII.get(PPC::MFCR8), TempReg);
638     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
639       MIB.addReg(MustSaveCRs[i], RegState::ImplicitKill);
640   }
641
642   if (HasFP)
643     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
644     BuildMI(MBB, MBBI, dl, StoreInst)
645       .addReg(FPReg)
646       .addImm(FPOffset)
647       .addReg(SPReg);
648
649   if (HasBP)
650     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
651     BuildMI(MBB, MBBI, dl, StoreInst)
652       .addReg(BPReg)
653       .addImm(BPOffset)
654       .addReg(SPReg);
655
656   if (MustSaveLR)
657     // FIXME: On PPC32 SVR4, we must not spill before claiming the stackframe.
658     BuildMI(MBB, MBBI, dl, StoreInst)
659       .addReg(ScratchReg)
660       .addImm(LROffset)
661       .addReg(SPReg);
662
663   if (!MustSaveCRs.empty()) // will only occur for PPC64
664     BuildMI(MBB, MBBI, dl, TII.get(PPC::STW8))
665       .addReg(TempReg, getKillRegState(true))
666       .addImm(8)
667       .addReg(SPReg);
668
669   // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
670   if (!FrameSize) return;
671
672   // Adjust stack pointer: r1 += NegFrameSize.
673   // If there is a preferred stack alignment, align R1 now
674
675   if (HasBP) {
676     // Save a copy of r1 as the base pointer.
677     BuildMI(MBB, MBBI, dl, OrInst, BPReg)
678       .addReg(SPReg)
679       .addReg(SPReg);
680   }
681
682   if (HasBP && MaxAlign > 1) {
683     if (isPPC64)
684       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
685         .addReg(SPReg)
686         .addImm(0)
687         .addImm(64 - Log2_32(MaxAlign));
688     else // PPC32...
689       BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
690         .addReg(SPReg)
691         .addImm(0)
692         .addImm(32 - Log2_32(MaxAlign))
693         .addImm(31);
694     if (!isLargeFrame) {
695       BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
696         .addReg(ScratchReg, RegState::Kill)
697         .addImm(NegFrameSize);
698     } else {
699       BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
700         .addImm(NegFrameSize >> 16);
701       BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
702         .addReg(TempReg, RegState::Kill)
703         .addImm(NegFrameSize & 0xFFFF);
704       BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
705         .addReg(ScratchReg, RegState::Kill)
706         .addReg(TempReg, RegState::Kill);
707     }
708     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
709       .addReg(SPReg, RegState::Kill)
710       .addReg(SPReg)
711       .addReg(ScratchReg);
712
713   } else if (!isLargeFrame) {
714     BuildMI(MBB, MBBI, dl, StoreUpdtInst, SPReg)
715       .addReg(SPReg)
716       .addImm(NegFrameSize)
717       .addReg(SPReg);
718
719   } else {
720     BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
721       .addImm(NegFrameSize >> 16);
722     BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
723       .addReg(ScratchReg, RegState::Kill)
724       .addImm(NegFrameSize & 0xFFFF);
725     BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
726       .addReg(SPReg, RegState::Kill)
727       .addReg(SPReg)
728       .addReg(ScratchReg);
729   }
730
731   // Add the "machine moves" for the instructions we generated above, but in
732   // reverse order.
733   if (needsFrameMoves) {
734     // Show update of SP.
735     assert(NegFrameSize);
736     unsigned CFIIndex = MMI.addFrameInst(
737         MCCFIInstruction::createDefCfaOffset(nullptr, NegFrameSize));
738     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
739         .addCFIIndex(CFIIndex);
740
741     if (HasFP) {
742       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
743       CFIIndex = MMI.addFrameInst(
744           MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
745       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
746           .addCFIIndex(CFIIndex);
747     }
748
749     if (HasBP) {
750       unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
751       CFIIndex = MMI.addFrameInst(
752           MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
753       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
754           .addCFIIndex(CFIIndex);
755     }
756
757     if (MustSaveLR) {
758       unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
759       CFIIndex = MMI.addFrameInst(
760           MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
761       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
762           .addCFIIndex(CFIIndex);
763     }
764   }
765
766   // If there is a frame pointer, copy R1 into R31
767   if (HasFP) {
768     BuildMI(MBB, MBBI, dl, OrInst, FPReg)
769       .addReg(SPReg)
770       .addReg(SPReg);
771
772     if (needsFrameMoves) {
773       // Mark effective beginning of when frame pointer is ready.
774       unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
775       unsigned CFIIndex = MMI.addFrameInst(
776           MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
777
778       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
779           .addCFIIndex(CFIIndex);
780     }
781   }
782
783   if (needsFrameMoves) {
784     // Add callee saved registers to move list.
785     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
786     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
787       unsigned Reg = CSI[I].getReg();
788       if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
789
790       // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
791       // subregisters of CR2. We just need to emit a move of CR2.
792       if (PPC::CRBITRCRegClass.contains(Reg))
793         continue;
794
795       // For SVR4, don't emit a move for the CR spill slot if we haven't
796       // spilled CRs.
797       if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
798           && MustSaveCRs.empty())
799         continue;
800
801       // For 64-bit SVR4 when we have spilled CRs, the spill location
802       // is SP+8, not a frame-relative slot.
803       if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
804         // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
805         // the whole CR word.  In the ELFv2 ABI, every CR that was
806         // actually saved gets its own CFI record.
807         unsigned CRReg = isELFv2ABI? Reg : (unsigned) PPC::CR2;
808         unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
809             nullptr, MRI->getDwarfRegNum(CRReg, true), 8));
810         BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
811             .addCFIIndex(CFIIndex);
812         continue;
813       }
814
815       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
816       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
817           nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
818       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
819           .addCFIIndex(CFIIndex);
820     }
821   }
822 }
823
824 void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
825                                 MachineBasicBlock &MBB) const {
826   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
827   assert(MBBI != MBB.end() && "Returning block has no terminator");
828   const PPCInstrInfo &TII =
829       *static_cast<const PPCInstrInfo *>(
830           MF.getTarget().getSubtargetImpl()->getInstrInfo());
831   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
832       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
833
834   unsigned RetOpcode = MBBI->getOpcode();
835   DebugLoc dl;
836
837   assert((RetOpcode == PPC::BLR ||
838           RetOpcode == PPC::TCRETURNri ||
839           RetOpcode == PPC::TCRETURNdi ||
840           RetOpcode == PPC::TCRETURNai ||
841           RetOpcode == PPC::TCRETURNri8 ||
842           RetOpcode == PPC::TCRETURNdi8 ||
843           RetOpcode == PPC::TCRETURNai8) &&
844          "Can only insert epilog into returning blocks");
845
846   // Get alignment info so we know how to restore the SP.
847   const MachineFrameInfo *MFI = MF.getFrameInfo();
848
849   // Get the number of bytes allocated from the FrameInfo.
850   int FrameSize = MFI->getStackSize();
851
852   // Get processor type.
853   bool isPPC64 = Subtarget.isPPC64();
854   // Get the ABI.
855   bool isDarwinABI = Subtarget.isDarwinABI();
856   bool isSVR4ABI = Subtarget.isSVR4ABI();
857   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
858
859   // Check if the link register (LR) has been saved.
860   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
861   bool MustSaveLR = FI->mustSaveLR();
862   const SmallVectorImpl<unsigned> &MustSaveCRs = FI->getMustSaveCRs();
863   // Do we have a frame pointer and/or base pointer for this function?
864   bool HasFP = hasFP(MF);
865   bool HasBP = RegInfo->hasBasePointer(MF);
866
867   unsigned SPReg      = isPPC64 ? PPC::X1  : PPC::R1;
868   unsigned BPReg      = RegInfo->getBaseRegister(MF);
869   unsigned FPReg      = isPPC64 ? PPC::X31 : PPC::R31;
870   unsigned ScratchReg  = isPPC64 ? PPC::X0  : PPC::R0;
871   unsigned TempReg     = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
872   const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
873                                                  : PPC::MTLR );
874   const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
875                                                  : PPC::LWZ );
876   const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
877                                                            : PPC::LIS );
878   const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
879                                                   : PPC::ORI );
880   const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
881                                                    : PPC::ADDI );
882   const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
883                                                 : PPC::ADD4 );
884
885   int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
886
887   int FPOffset = 0;
888   if (HasFP) {
889     if (isSVR4ABI) {
890       MachineFrameInfo *FFI = MF.getFrameInfo();
891       int FPIndex = FI->getFramePointerSaveIndex();
892       assert(FPIndex && "No Frame Pointer Save Slot!");
893       FPOffset = FFI->getObjectOffset(FPIndex);
894     } else {
895       FPOffset =
896           PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
897     }
898   }
899
900   int BPOffset = 0;
901   if (HasBP) {
902     if (isSVR4ABI) {
903       MachineFrameInfo *FFI = MF.getFrameInfo();
904       int BPIndex = FI->getBasePointerSaveIndex();
905       assert(BPIndex && "No Base Pointer Save Slot!");
906       BPOffset = FFI->getObjectOffset(BPIndex);
907     } else {
908       BPOffset =
909         PPCFrameLowering::getBasePointerSaveOffset(isPPC64,
910                                                    isDarwinABI,
911                                                    isPIC);
912     }
913   }
914
915   bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
916     RetOpcode == PPC::TCRETURNdi ||
917     RetOpcode == PPC::TCRETURNai ||
918     RetOpcode == PPC::TCRETURNri8 ||
919     RetOpcode == PPC::TCRETURNdi8 ||
920     RetOpcode == PPC::TCRETURNai8;
921
922   if (UsesTCRet) {
923     int MaxTCRetDelta = FI->getTailCallSPDelta();
924     MachineOperand &StackAdjust = MBBI->getOperand(1);
925     assert(StackAdjust.isImm() && "Expecting immediate value.");
926     // Adjust stack pointer.
927     int StackAdj = StackAdjust.getImm();
928     int Delta = StackAdj - MaxTCRetDelta;
929     assert((Delta >= 0) && "Delta must be positive");
930     if (MaxTCRetDelta>0)
931       FrameSize += (StackAdj +Delta);
932     else
933       FrameSize += StackAdj;
934   }
935
936   // Frames of 32KB & larger require special handling because they cannot be
937   // indexed into with a simple LD/LWZ immediate offset operand.
938   bool isLargeFrame = !isInt<16>(FrameSize);
939
940   if (FrameSize) {
941     // In the prologue, the loaded (or persistent) stack pointer value is offset
942     // by the STDU/STDUX/STWU/STWUX instruction.  Add this offset back now.
943
944     // If this function contained a fastcc call and GuaranteedTailCallOpt is
945     // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
946     // call which invalidates the stack pointer value in SP(0). So we use the
947     // value of R31 in this case.
948     if (FI->hasFastCall()) {
949       assert(HasFP && "Expecting a valid frame pointer.");
950       if (!isLargeFrame) {
951         BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
952           .addReg(FPReg).addImm(FrameSize);
953       } else {
954         BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
955           .addImm(FrameSize >> 16);
956         BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
957           .addReg(ScratchReg, RegState::Kill)
958           .addImm(FrameSize & 0xFFFF);
959         BuildMI(MBB, MBBI, dl, AddInst)
960           .addReg(SPReg)
961           .addReg(FPReg)
962           .addReg(ScratchReg);
963       }
964     } else if (!isLargeFrame && !HasBP && !MFI->hasVarSizedObjects()) {
965       BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
966         .addReg(SPReg)
967         .addImm(FrameSize);
968     } else {
969       BuildMI(MBB, MBBI, dl, LoadInst, SPReg)
970         .addImm(0)
971         .addReg(SPReg);
972     }
973
974   }
975
976   if (MustSaveLR)
977     BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
978       .addImm(LROffset)
979       .addReg(SPReg);
980
981   assert((isPPC64 || MustSaveCRs.empty()) &&
982          "Epilogue CR restoring supported only in 64-bit mode");
983
984   if (!MustSaveCRs.empty()) // will only occur for PPC64
985     BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ8), TempReg)
986       .addImm(8)
987       .addReg(SPReg);
988
989   if (HasFP)
990     BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
991       .addImm(FPOffset)
992       .addReg(SPReg);
993
994   if (HasBP)
995     BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
996       .addImm(BPOffset)
997       .addReg(SPReg);
998
999   if (!MustSaveCRs.empty()) // will only occur for PPC64
1000     for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
1001       BuildMI(MBB, MBBI, dl, TII.get(PPC::MTOCRF8), MustSaveCRs[i])
1002         .addReg(TempReg, getKillRegState(i == e-1));
1003
1004   if (MustSaveLR)
1005     BuildMI(MBB, MBBI, dl, MTLRInst).addReg(ScratchReg);
1006
1007   // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1008   // call optimization
1009   if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1010       MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1011      PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1012      unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1013
1014      if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1015        BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
1016          .addReg(SPReg).addImm(CallerAllocatedAmt);
1017      } else {
1018        BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
1019           .addImm(CallerAllocatedAmt >> 16);
1020        BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
1021           .addReg(ScratchReg, RegState::Kill)
1022           .addImm(CallerAllocatedAmt & 0xFFFF);
1023        BuildMI(MBB, MBBI, dl, AddInst)
1024           .addReg(SPReg)
1025           .addReg(FPReg)
1026           .addReg(ScratchReg);
1027      }
1028   } else if (RetOpcode == PPC::TCRETURNdi) {
1029     MBBI = MBB.getLastNonDebugInstr();
1030     MachineOperand &JumpTarget = MBBI->getOperand(0);
1031     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1032       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1033   } else if (RetOpcode == PPC::TCRETURNri) {
1034     MBBI = MBB.getLastNonDebugInstr();
1035     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1036     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1037   } else if (RetOpcode == PPC::TCRETURNai) {
1038     MBBI = MBB.getLastNonDebugInstr();
1039     MachineOperand &JumpTarget = MBBI->getOperand(0);
1040     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1041   } else if (RetOpcode == PPC::TCRETURNdi8) {
1042     MBBI = MBB.getLastNonDebugInstr();
1043     MachineOperand &JumpTarget = MBBI->getOperand(0);
1044     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1045       addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1046   } else if (RetOpcode == PPC::TCRETURNri8) {
1047     MBBI = MBB.getLastNonDebugInstr();
1048     assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1049     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1050   } else if (RetOpcode == PPC::TCRETURNai8) {
1051     MBBI = MBB.getLastNonDebugInstr();
1052     MachineOperand &JumpTarget = MBBI->getOperand(0);
1053     BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1054   }
1055 }
1056
1057 /// MustSaveLR - Return true if this function requires that we save the LR
1058 /// register onto the stack in the prolog and restore it in the epilog of the
1059 /// function.
1060 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
1061   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
1062
1063   // We need a save/restore of LR if there is any def of LR (which is
1064   // defined by calls, including the PIC setup sequence), or if there is
1065   // some use of the LR stack slot (e.g. for builtin_return_address).
1066   // (LR comes in 32 and 64 bit versions.)
1067   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
1068   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
1069 }
1070
1071 void
1072 PPCFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1073                                                    RegScavenger *) const {
1074   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
1075       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1076
1077   //  Save and clear the LR state.
1078   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1079   unsigned LR = RegInfo->getRARegister();
1080   FI->setMustSaveLR(MustSaveLR(MF, LR));
1081   MachineRegisterInfo &MRI = MF.getRegInfo();
1082   MRI.setPhysRegUnused(LR);
1083
1084   //  Save R31 if necessary
1085   int FPSI = FI->getFramePointerSaveIndex();
1086   bool isPPC64 = Subtarget.isPPC64();
1087   bool isDarwinABI  = Subtarget.isDarwinABI();
1088   bool isPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
1089   MachineFrameInfo *MFI = MF.getFrameInfo();
1090
1091   // If the frame pointer save index hasn't been defined yet.
1092   if (!FPSI && needsFP(MF)) {
1093     // Find out what the fix offset of the frame pointer save area.
1094     int FPOffset = getFramePointerSaveOffset(isPPC64, isDarwinABI);
1095     // Allocate the frame index for frame pointer save area.
1096     FPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
1097     // Save the result.
1098     FI->setFramePointerSaveIndex(FPSI);
1099   }
1100
1101   int BPSI = FI->getBasePointerSaveIndex();
1102   if (!BPSI && RegInfo->hasBasePointer(MF)) {
1103     int BPOffset = getBasePointerSaveOffset(isPPC64, isDarwinABI, isPIC);
1104     // Allocate the frame index for the base pointer save area.
1105     BPSI = MFI->CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
1106     // Save the result.
1107     FI->setBasePointerSaveIndex(BPSI);
1108   }
1109
1110   // Reserve stack space to move the linkage area to in case of a tail call.
1111   int TCSPDelta = 0;
1112   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1113       (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1114     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
1115   }
1116
1117   // For 32-bit SVR4, allocate the nonvolatile CR spill slot iff the
1118   // function uses CR 2, 3, or 4.
1119   if (!isPPC64 && !isDarwinABI &&
1120       (MRI.isPhysRegUsed(PPC::CR2) ||
1121        MRI.isPhysRegUsed(PPC::CR3) ||
1122        MRI.isPhysRegUsed(PPC::CR4))) {
1123     int FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
1124     FI->setCRSpillFrameIndex(FrameIdx);
1125   }
1126 }
1127
1128 void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
1129                                                        RegScavenger *RS) const {
1130   // Early exit if not using the SVR4 ABI.
1131   if (!Subtarget.isSVR4ABI()) {
1132     addScavengingSpillSlot(MF, RS);
1133     return;
1134   }
1135
1136   // Get callee saved register information.
1137   MachineFrameInfo *FFI = MF.getFrameInfo();
1138   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1139
1140   // Early exit if no callee saved registers are modified!
1141   if (CSI.empty() && !needsFP(MF)) {
1142     addScavengingSpillSlot(MF, RS);
1143     return;
1144   }
1145
1146   unsigned MinGPR = PPC::R31;
1147   unsigned MinG8R = PPC::X31;
1148   unsigned MinFPR = PPC::F31;
1149   unsigned MinVR = PPC::V31;
1150
1151   bool HasGPSaveArea = false;
1152   bool HasG8SaveArea = false;
1153   bool HasFPSaveArea = false;
1154   bool HasVRSAVESaveArea = false;
1155   bool HasVRSaveArea = false;
1156
1157   SmallVector<CalleeSavedInfo, 18> GPRegs;
1158   SmallVector<CalleeSavedInfo, 18> G8Regs;
1159   SmallVector<CalleeSavedInfo, 18> FPRegs;
1160   SmallVector<CalleeSavedInfo, 18> VRegs;
1161
1162   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1163     unsigned Reg = CSI[i].getReg();
1164     if (PPC::GPRCRegClass.contains(Reg)) {
1165       HasGPSaveArea = true;
1166
1167       GPRegs.push_back(CSI[i]);
1168
1169       if (Reg < MinGPR) {
1170         MinGPR = Reg;
1171       }
1172     } else if (PPC::G8RCRegClass.contains(Reg)) {
1173       HasG8SaveArea = true;
1174
1175       G8Regs.push_back(CSI[i]);
1176
1177       if (Reg < MinG8R) {
1178         MinG8R = Reg;
1179       }
1180     } else if (PPC::F8RCRegClass.contains(Reg)) {
1181       HasFPSaveArea = true;
1182
1183       FPRegs.push_back(CSI[i]);
1184
1185       if (Reg < MinFPR) {
1186         MinFPR = Reg;
1187       }
1188     } else if (PPC::CRBITRCRegClass.contains(Reg) ||
1189                PPC::CRRCRegClass.contains(Reg)) {
1190       ; // do nothing, as we already know whether CRs are spilled
1191     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1192       HasVRSAVESaveArea = true;
1193     } else if (PPC::VRRCRegClass.contains(Reg)) {
1194       HasVRSaveArea = true;
1195
1196       VRegs.push_back(CSI[i]);
1197
1198       if (Reg < MinVR) {
1199         MinVR = Reg;
1200       }
1201     } else {
1202       llvm_unreachable("Unknown RegisterClass!");
1203     }
1204   }
1205
1206   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1207   const TargetRegisterInfo *TRI =
1208       MF.getTarget().getSubtargetImpl()->getRegisterInfo();
1209
1210   int64_t LowerBound = 0;
1211
1212   // Take into account stack space reserved for tail calls.
1213   int TCSPDelta = 0;
1214   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1215       (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1216     LowerBound = TCSPDelta;
1217   }
1218
1219   // The Floating-point register save area is right below the back chain word
1220   // of the previous stack frame.
1221   if (HasFPSaveArea) {
1222     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1223       int FI = FPRegs[i].getFrameIdx();
1224
1225       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1226     }
1227
1228     LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
1229   }
1230
1231   // Check whether the frame pointer register is allocated. If so, make sure it
1232   // is spilled to the correct offset.
1233   if (needsFP(MF)) {
1234     HasGPSaveArea = true;
1235
1236     int FI = PFI->getFramePointerSaveIndex();
1237     assert(FI && "No Frame Pointer Save Slot!");
1238
1239     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1240   }
1241
1242   const PPCRegisterInfo *RegInfo = static_cast<const PPCRegisterInfo *>(
1243       MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1244   if (RegInfo->hasBasePointer(MF)) {
1245     HasGPSaveArea = true;
1246
1247     int FI = PFI->getBasePointerSaveIndex();
1248     assert(FI && "No Base Pointer Save Slot!");
1249
1250     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1251   }
1252
1253   // General register save area starts right below the Floating-point
1254   // register save area.
1255   if (HasGPSaveArea || HasG8SaveArea) {
1256     // Move general register save area spill slots down, taking into account
1257     // the size of the Floating-point register save area.
1258     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1259       int FI = GPRegs[i].getFrameIdx();
1260
1261       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1262     }
1263
1264     // Move general register save area spill slots down, taking into account
1265     // the size of the Floating-point register save area.
1266     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1267       int FI = G8Regs[i].getFrameIdx();
1268
1269       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1270     }
1271
1272     unsigned MinReg =
1273       std::min<unsigned>(TRI->getEncodingValue(MinGPR),
1274                          TRI->getEncodingValue(MinG8R));
1275
1276     if (Subtarget.isPPC64()) {
1277       LowerBound -= (31 - MinReg + 1) * 8;
1278     } else {
1279       LowerBound -= (31 - MinReg + 1) * 4;
1280     }
1281   }
1282
1283   // For 32-bit only, the CR save area is below the general register
1284   // save area.  For 64-bit SVR4, the CR save area is addressed relative
1285   // to the stack pointer and hence does not need an adjustment here.
1286   // Only CR2 (the first nonvolatile spilled) has an associated frame
1287   // index so that we have a single uniform save area.
1288   if (spillsCR(MF) && !(Subtarget.isPPC64() && Subtarget.isSVR4ABI())) {
1289     // Adjust the frame index of the CR spill slot.
1290     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1291       unsigned Reg = CSI[i].getReg();
1292
1293       if ((Subtarget.isSVR4ABI() && Reg == PPC::CR2)
1294           // Leave Darwin logic as-is.
1295           || (!Subtarget.isSVR4ABI() &&
1296               (PPC::CRBITRCRegClass.contains(Reg) ||
1297                PPC::CRRCRegClass.contains(Reg)))) {
1298         int FI = CSI[i].getFrameIdx();
1299
1300         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1301       }
1302     }
1303
1304     LowerBound -= 4; // The CR save area is always 4 bytes long.
1305   }
1306
1307   if (HasVRSAVESaveArea) {
1308     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1309     //             which have the VRSAVE register class?
1310     // Adjust the frame index of the VRSAVE spill slot.
1311     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1312       unsigned Reg = CSI[i].getReg();
1313
1314       if (PPC::VRSAVERCRegClass.contains(Reg)) {
1315         int FI = CSI[i].getFrameIdx();
1316
1317         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1318       }
1319     }
1320
1321     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1322   }
1323
1324   if (HasVRSaveArea) {
1325     // Insert alignment padding, we need 16-byte alignment.
1326     LowerBound = (LowerBound - 15) & ~(15);
1327
1328     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1329       int FI = VRegs[i].getFrameIdx();
1330
1331       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1332     }
1333   }
1334
1335   addScavengingSpillSlot(MF, RS);
1336 }
1337
1338 void
1339 PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
1340                                          RegScavenger *RS) const {
1341   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1342   // a large stack, which will require scavenging a register to materialize a
1343   // large offset.
1344
1345   // We need to have a scavenger spill slot for spills if the frame size is
1346   // large. In case there is no free register for large-offset addressing,
1347   // this slot is used for the necessary emergency spill. Also, we need the
1348   // slot for dynamic stack allocations.
1349
1350   // The scavenger might be invoked if the frame offset does not fit into
1351   // the 16-bit immediate. We don't know the complete frame size here
1352   // because we've not yet computed callee-saved register spills or the
1353   // needed alignment padding.
1354   unsigned StackSize = determineFrameLayout(MF, false, true);
1355   MachineFrameInfo *MFI = MF.getFrameInfo();
1356   if (MFI->hasVarSizedObjects() || spillsCR(MF) || spillsVRSAVE(MF) ||
1357       hasNonRISpills(MF) || (hasSpills(MF) && !isInt<16>(StackSize))) {
1358     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1359     const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1360     const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
1361     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1362                                                        RC->getAlignment(),
1363                                                        false));
1364
1365     // Might we have over-aligned allocas?
1366     bool HasAlVars = MFI->hasVarSizedObjects() &&
1367                      MFI->getMaxAlignment() > getStackAlignment();
1368
1369     // These kinds of spills might need two registers.
1370     if (spillsCR(MF) || spillsVRSAVE(MF) || HasAlVars)
1371       RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1372                                                          RC->getAlignment(),
1373                                                          false));
1374
1375   }
1376 }
1377
1378 bool
1379 PPCFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1380                                      MachineBasicBlock::iterator MI,
1381                                      const std::vector<CalleeSavedInfo> &CSI,
1382                                      const TargetRegisterInfo *TRI) const {
1383
1384   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1385   // Return false otherwise to maintain pre-existing behavior.
1386   if (!Subtarget.isSVR4ABI())
1387     return false;
1388
1389   MachineFunction *MF = MBB.getParent();
1390   const PPCInstrInfo &TII =
1391       *static_cast<const PPCInstrInfo *>(
1392           MF->getTarget().getSubtargetImpl()->getInstrInfo());
1393   DebugLoc DL;
1394   bool CRSpilled = false;
1395   MachineInstrBuilder CRMIB;
1396
1397   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1398     unsigned Reg = CSI[i].getReg();
1399     // Only Darwin actually uses the VRSAVE register, but it can still appear
1400     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1401     // Darwin, ignore it.
1402     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1403       continue;
1404
1405     // CR2 through CR4 are the nonvolatile CR fields.
1406     bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
1407
1408     // Add the callee-saved register as live-in; it's killed at the spill.
1409     MBB.addLiveIn(Reg);
1410
1411     if (CRSpilled && IsCRField) {
1412       CRMIB.addReg(Reg, RegState::ImplicitKill);
1413       continue;
1414     }
1415
1416     // Insert the spill to the stack frame.
1417     if (IsCRField) {
1418       PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
1419       if (Subtarget.isPPC64()) {
1420         // The actual spill will happen at the start of the prologue.
1421         FuncInfo->addMustSaveCR(Reg);
1422       } else {
1423         CRSpilled = true;
1424         FuncInfo->setSpillsCR();
1425
1426         // 32-bit:  FP-relative.  Note that we made sure CR2-CR4 all have
1427         // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
1428         CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
1429                   .addReg(Reg, RegState::ImplicitKill);
1430
1431         MBB.insert(MI, CRMIB);
1432         MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
1433                                          .addReg(PPC::R12,
1434                                                  getKillRegState(true)),
1435                                          CSI[i].getFrameIdx()));
1436       }
1437     } else {
1438       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1439       TII.storeRegToStackSlot(MBB, MI, Reg, true,
1440                               CSI[i].getFrameIdx(), RC, TRI);
1441     }
1442   }
1443   return true;
1444 }
1445
1446 static void
1447 restoreCRs(bool isPPC64, bool is31,
1448            bool CR2Spilled, bool CR3Spilled, bool CR4Spilled,
1449            MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1450            const std::vector<CalleeSavedInfo> &CSI, unsigned CSIIndex) {
1451
1452   MachineFunction *MF = MBB.getParent();
1453   const PPCInstrInfo &TII =
1454       *static_cast<const PPCInstrInfo *>(
1455           MF->getTarget().getSubtargetImpl()->getInstrInfo());
1456   DebugLoc DL;
1457   unsigned RestoreOp, MoveReg;
1458
1459   if (isPPC64)
1460     // This is handled during epilogue generation.
1461     return;
1462   else {
1463     // 32-bit:  FP-relative
1464     MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ),
1465                                              PPC::R12),
1466                                      CSI[CSIIndex].getFrameIdx()));
1467     RestoreOp = PPC::MTOCRF;
1468     MoveReg = PPC::R12;
1469   }
1470
1471   if (CR2Spilled)
1472     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
1473                .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
1474
1475   if (CR3Spilled)
1476     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
1477                .addReg(MoveReg, getKillRegState(!CR4Spilled)));
1478
1479   if (CR4Spilled)
1480     MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
1481                .addReg(MoveReg, getKillRegState(true)));
1482 }
1483
1484 void PPCFrameLowering::
1485 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1486                               MachineBasicBlock::iterator I) const {
1487   const PPCInstrInfo &TII =
1488       *static_cast<const PPCInstrInfo *>(
1489           MF.getTarget().getSubtargetImpl()->getInstrInfo());
1490   if (MF.getTarget().Options.GuaranteedTailCallOpt &&
1491       I->getOpcode() == PPC::ADJCALLSTACKUP) {
1492     // Add (actually subtract) back the amount the callee popped on return.
1493     if (int CalleeAmt =  I->getOperand(1).getImm()) {
1494       bool is64Bit = Subtarget.isPPC64();
1495       CalleeAmt *= -1;
1496       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
1497       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
1498       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
1499       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
1500       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
1501       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
1502       MachineInstr *MI = I;
1503       DebugLoc dl = MI->getDebugLoc();
1504
1505       if (isInt<16>(CalleeAmt)) {
1506         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
1507           .addReg(StackReg, RegState::Kill)
1508           .addImm(CalleeAmt);
1509       } else {
1510         MachineBasicBlock::iterator MBBI = I;
1511         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1512           .addImm(CalleeAmt >> 16);
1513         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1514           .addReg(TmpReg, RegState::Kill)
1515           .addImm(CalleeAmt & 0xFFFF);
1516         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
1517           .addReg(StackReg, RegState::Kill)
1518           .addReg(TmpReg);
1519       }
1520     }
1521   }
1522   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
1523   MBB.erase(I);
1524 }
1525
1526 bool
1527 PPCFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1528                                         MachineBasicBlock::iterator MI,
1529                                         const std::vector<CalleeSavedInfo> &CSI,
1530                                         const TargetRegisterInfo *TRI) const {
1531
1532   // Currently, this function only handles SVR4 32- and 64-bit ABIs.
1533   // Return false otherwise to maintain pre-existing behavior.
1534   if (!Subtarget.isSVR4ABI())
1535     return false;
1536
1537   MachineFunction *MF = MBB.getParent();
1538   const PPCInstrInfo &TII =
1539       *static_cast<const PPCInstrInfo *>(
1540           MF->getTarget().getSubtargetImpl()->getInstrInfo());
1541   bool CR2Spilled = false;
1542   bool CR3Spilled = false;
1543   bool CR4Spilled = false;
1544   unsigned CSIIndex = 0;
1545
1546   // Initialize insertion-point logic; we will be restoring in reverse
1547   // order of spill.
1548   MachineBasicBlock::iterator I = MI, BeforeI = I;
1549   bool AtStart = I == MBB.begin();
1550
1551   if (!AtStart)
1552     --BeforeI;
1553
1554   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1555     unsigned Reg = CSI[i].getReg();
1556
1557     // Only Darwin actually uses the VRSAVE register, but it can still appear
1558     // here if, for example, @llvm.eh.unwind.init() is used.  If we're not on
1559     // Darwin, ignore it.
1560     if (Reg == PPC::VRSAVE && !Subtarget.isDarwinABI())
1561       continue;
1562
1563     if (Reg == PPC::CR2) {
1564       CR2Spilled = true;
1565       // The spill slot is associated only with CR2, which is the
1566       // first nonvolatile spilled.  Save it here.
1567       CSIIndex = i;
1568       continue;
1569     } else if (Reg == PPC::CR3) {
1570       CR3Spilled = true;
1571       continue;
1572     } else if (Reg == PPC::CR4) {
1573       CR4Spilled = true;
1574       continue;
1575     } else {
1576       // When we first encounter a non-CR register after seeing at
1577       // least one CR register, restore all spilled CRs together.
1578       if ((CR2Spilled || CR3Spilled || CR4Spilled)
1579           && !(PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
1580         bool is31 = needsFP(*MF);
1581         restoreCRs(Subtarget.isPPC64(), is31,
1582                    CR2Spilled, CR3Spilled, CR4Spilled,
1583                    MBB, I, CSI, CSIIndex);
1584         CR2Spilled = CR3Spilled = CR4Spilled = false;
1585       }
1586
1587       // Default behavior for non-CR saves.
1588       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1589       TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(),
1590                                RC, TRI);
1591       assert(I != MBB.begin() &&
1592              "loadRegFromStackSlot didn't insert any code!");
1593       }
1594
1595     // Insert in reverse order.
1596     if (AtStart)
1597       I = MBB.begin();
1598     else {
1599       I = BeforeI;
1600       ++I;
1601     }
1602   }
1603
1604   // If we haven't yet spilled the CRs, do so now.
1605   if (CR2Spilled || CR3Spilled || CR4Spilled) {
1606     bool is31 = needsFP(*MF);
1607     restoreCRs(Subtarget.isPPC64(), is31, CR2Spilled, CR3Spilled, CR4Spilled,
1608                MBB, I, CSI, CSIIndex);
1609   }
1610
1611   return true;
1612 }