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