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