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