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