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