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