PPCRegisterInfo.cpp revision 212904
1//===- PPCRegisterInfo.cpp - PowerPC Register Information -------*- C++ -*-===//
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 PowerPC implementation of the TargetRegisterInfo
11// class.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "reginfo"
16#include "PPC.h"
17#include "PPCInstrBuilder.h"
18#include "PPCMachineFunctionInfo.h"
19#include "PPCRegisterInfo.h"
20#include "PPCFrameInfo.h"
21#include "PPCSubtarget.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/Function.h"
25#include "llvm/Type.h"
26#include "llvm/CodeGen/ValueTypes.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineLocation.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/RegisterScavenging.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/STLExtras.h"
45#include <cstdlib>
46
47// FIXME This disables some code that aligns the stack to a boundary
48// bigger than the default (16 bytes on Darwin) when there is a stack local
49// of greater alignment.  This does not currently work, because the delta
50// between old and new stack pointers is added to offsets that reference
51// incoming parameters after the prolog is generated, and the code that
52// does that doesn't handle a variable delta.  You don't want to do that
53// anyway; a better approach is to reserve another register that retains
54// to the incoming stack pointer, and reference parameters relative to that.
55#define ALIGN_STACK 0
56
57// FIXME (64-bit): Eventually enable by default.
58namespace llvm {
59cl::opt<bool> EnablePPC32RS("enable-ppc32-regscavenger",
60                                   cl::init(false),
61                                   cl::desc("Enable PPC32 register scavenger"),
62                                   cl::Hidden);
63cl::opt<bool> EnablePPC64RS("enable-ppc64-regscavenger",
64                                   cl::init(false),
65                                   cl::desc("Enable PPC64 register scavenger"),
66                                   cl::Hidden);
67}
68
69using namespace llvm;
70
71#define EnableRegisterScavenging \
72  ((EnablePPC32RS && !Subtarget.isPPC64()) || \
73   (EnablePPC64RS && Subtarget.isPPC64()))
74
75// FIXME (64-bit): Should be inlined.
76bool
77PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const {
78  return EnableRegisterScavenging;
79}
80
81/// getRegisterNumbering - Given the enum value for some register, e.g.
82/// PPC::F14, return the number that it corresponds to (e.g. 14).
83unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
84  using namespace PPC;
85  switch (RegEnum) {
86  case 0: return 0;
87  case R0 :  case X0 :  case F0 :  case V0 : case CR0:  case CR0LT: return  0;
88  case R1 :  case X1 :  case F1 :  case V1 : case CR1:  case CR0GT: return  1;
89  case R2 :  case X2 :  case F2 :  case V2 : case CR2:  case CR0EQ: return  2;
90  case R3 :  case X3 :  case F3 :  case V3 : case CR3:  case CR0UN: return  3;
91  case R4 :  case X4 :  case F4 :  case V4 : case CR4:  case CR1LT: return  4;
92  case R5 :  case X5 :  case F5 :  case V5 : case CR5:  case CR1GT: return  5;
93  case R6 :  case X6 :  case F6 :  case V6 : case CR6:  case CR1EQ: return  6;
94  case R7 :  case X7 :  case F7 :  case V7 : case CR7:  case CR1UN: return  7;
95  case R8 :  case X8 :  case F8 :  case V8 : case CR2LT: return  8;
96  case R9 :  case X9 :  case F9 :  case V9 : case CR2GT: return  9;
97  case R10:  case X10:  case F10:  case V10: case CR2EQ: return 10;
98  case R11:  case X11:  case F11:  case V11: case CR2UN: return 11;
99  case R12:  case X12:  case F12:  case V12: case CR3LT: return 12;
100  case R13:  case X13:  case F13:  case V13: case CR3GT: return 13;
101  case R14:  case X14:  case F14:  case V14: case CR3EQ: return 14;
102  case R15:  case X15:  case F15:  case V15: case CR3UN: return 15;
103  case R16:  case X16:  case F16:  case V16: case CR4LT: return 16;
104  case R17:  case X17:  case F17:  case V17: case CR4GT: return 17;
105  case R18:  case X18:  case F18:  case V18: case CR4EQ: return 18;
106  case R19:  case X19:  case F19:  case V19: case CR4UN: return 19;
107  case R20:  case X20:  case F20:  case V20: case CR5LT: return 20;
108  case R21:  case X21:  case F21:  case V21: case CR5GT: return 21;
109  case R22:  case X22:  case F22:  case V22: case CR5EQ: return 22;
110  case R23:  case X23:  case F23:  case V23: case CR5UN: return 23;
111  case R24:  case X24:  case F24:  case V24: case CR6LT: return 24;
112  case R25:  case X25:  case F25:  case V25: case CR6GT: return 25;
113  case R26:  case X26:  case F26:  case V26: case CR6EQ: return 26;
114  case R27:  case X27:  case F27:  case V27: case CR6UN: return 27;
115  case R28:  case X28:  case F28:  case V28: case CR7LT: return 28;
116  case R29:  case X29:  case F29:  case V29: case CR7GT: return 29;
117  case R30:  case X30:  case F30:  case V30: case CR7EQ: return 30;
118  case R31:  case X31:  case F31:  case V31: case CR7UN: return 31;
119  default:
120    llvm_unreachable("Unhandled reg in PPCRegisterInfo::getRegisterNumbering!");
121  }
122}
123
124PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
125                                 const TargetInstrInfo &tii)
126  : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
127    Subtarget(ST), TII(tii) {
128  ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
129  ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
130  ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
131  ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
132  ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
133  ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
134  ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
135  ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
136
137  // 64-bit
138  ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
139  ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
140  ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
141  ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
142  ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
143}
144
145/// getPointerRegClass - Return the register class to use to hold pointers.
146/// This is used for addressing modes.
147const TargetRegisterClass *
148PPCRegisterInfo::getPointerRegClass(unsigned Kind) const {
149  if (Subtarget.isPPC64())
150    return &PPC::G8RCRegClass;
151  return &PPC::GPRCRegClass;
152}
153
154const unsigned*
155PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
156  // 32-bit Darwin calling convention.
157  static const unsigned Darwin32_CalleeSavedRegs[] = {
158              PPC::R13, PPC::R14, PPC::R15,
159    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
160    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
161    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
162    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
163
164    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
165    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
166    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
167    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
168    PPC::F30, PPC::F31,
169
170    PPC::CR2, PPC::CR3, PPC::CR4,
171    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
172    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
173    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
174
175    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
176    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
177    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
178
179    PPC::LR,  0
180  };
181
182  // 32-bit SVR4 calling convention.
183  static const unsigned SVR4_CalleeSavedRegs[] = {
184                        PPC::R14, PPC::R15,
185    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
186    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
187    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
188    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
189
190    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
191    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
192    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
193    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
194    PPC::F30, PPC::F31,
195
196    PPC::CR2, PPC::CR3, PPC::CR4,
197
198    PPC::VRSAVE,
199
200    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
201    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
202    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
203
204    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
205    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
206    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
207
208    0
209  };
210  // 64-bit Darwin calling convention.
211  static const unsigned Darwin64_CalleeSavedRegs[] = {
212    PPC::X14, PPC::X15,
213    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
214    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
215    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
216    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
217
218    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
219    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
220    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
221    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
222    PPC::F30, PPC::F31,
223
224    PPC::CR2, PPC::CR3, PPC::CR4,
225    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
226    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
227    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
228
229    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
230    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
231    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
232
233    PPC::LR8,  0
234  };
235
236  // 64-bit SVR4 calling convention.
237  static const unsigned SVR4_64_CalleeSavedRegs[] = {
238    PPC::X14, PPC::X15,
239    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
240    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
241    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
242    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
243
244    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
245    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
246    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
247    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
248    PPC::F30, PPC::F31,
249
250    PPC::CR2, PPC::CR3, PPC::CR4,
251
252    PPC::VRSAVE,
253
254    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
255    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
256    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
257
258    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
259    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
260    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
261
262    0
263  };
264
265  if (Subtarget.isDarwinABI())
266    return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegs :
267                                 Darwin32_CalleeSavedRegs;
268
269  return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegs : SVR4_CalleeSavedRegs;
270}
271
272// needsFP - Return true if the specified function should have a dedicated frame
273// pointer register.  This is true if the function has variable sized allocas or
274// if frame pointer elimination is disabled.
275//
276static bool needsFP(const MachineFunction &MF) {
277  const MachineFrameInfo *MFI = MF.getFrameInfo();
278  // Naked functions have no stack frame pushed, so we don't have a frame pointer.
279  if (MF.getFunction()->hasFnAttr(Attribute::Naked))
280    return false;
281  return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects() ||
282    (GuaranteedTailCallOpt && MF.getInfo<PPCFunctionInfo>()->hasFastCall());
283}
284
285static bool spillsCR(const MachineFunction &MF) {
286  const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
287  return FuncInfo->isCRSpilled();
288}
289
290BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
291  BitVector Reserved(getNumRegs());
292  Reserved.set(PPC::R0);
293  Reserved.set(PPC::R1);
294  Reserved.set(PPC::LR);
295  Reserved.set(PPC::LR8);
296  Reserved.set(PPC::RM);
297
298  // The SVR4 ABI reserves r2 and r13
299  if (Subtarget.isSVR4ABI()) {
300    Reserved.set(PPC::R2);  // System-reserved register
301    Reserved.set(PPC::R13); // Small Data Area pointer register
302  }
303  // Reserve R2 on Darwin to hack around the problem of save/restore of CR
304  // when the stack frame is too big to address directly; we need two regs.
305  // This is a hack.
306  if (Subtarget.isDarwinABI()) {
307    Reserved.set(PPC::R2);
308  }
309
310  // On PPC64, r13 is the thread pointer. Never allocate this register.
311  // Note that this is over conservative, as it also prevents allocation of R31
312  // when the FP is not needed.
313  if (Subtarget.isPPC64()) {
314    Reserved.set(PPC::R13);
315    Reserved.set(PPC::R31);
316
317    if (!EnableRegisterScavenging)
318      Reserved.set(PPC::R0);    // FIXME (64-bit): Remove
319
320    Reserved.set(PPC::X0);
321    Reserved.set(PPC::X1);
322    Reserved.set(PPC::X13);
323    Reserved.set(PPC::X31);
324
325    // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
326    if (Subtarget.isSVR4ABI()) {
327      Reserved.set(PPC::X2);
328    }
329    // Reserve R2 on Darwin to hack around the problem of save/restore of CR
330    // when the stack frame is too big to address directly; we need two regs.
331    // This is a hack.
332    if (Subtarget.isDarwinABI()) {
333      Reserved.set(PPC::X2);
334    }
335  }
336
337  if (needsFP(MF))
338    Reserved.set(PPC::R31);
339
340  return Reserved;
341}
342
343//===----------------------------------------------------------------------===//
344// Stack Frame Processing methods
345//===----------------------------------------------------------------------===//
346
347// hasFP - Return true if the specified function actually has a dedicated frame
348// pointer register.  This is true if the function needs a frame pointer and has
349// a non-zero stack size.
350bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
351  const MachineFrameInfo *MFI = MF.getFrameInfo();
352  return MFI->getStackSize() && needsFP(MF);
353}
354
355/// MustSaveLR - Return true if this function requires that we save the LR
356/// register onto the stack in the prolog and restore it in the epilog of the
357/// function.
358static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
359  const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
360
361  // We need a save/restore of LR if there is any def of LR (which is
362  // defined by calls, including the PIC setup sequence), or if there is
363  // some use of the LR stack slot (e.g. for builtin_return_address).
364  // (LR comes in 32 and 64 bit versions.)
365  MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
366  return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
367}
368
369
370
371void PPCRegisterInfo::
372eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
373                              MachineBasicBlock::iterator I) const {
374  if (GuaranteedTailCallOpt && I->getOpcode() == PPC::ADJCALLSTACKUP) {
375    // Add (actually subtract) back the amount the callee popped on return.
376    if (int CalleeAmt =  I->getOperand(1).getImm()) {
377      bool is64Bit = Subtarget.isPPC64();
378      CalleeAmt *= -1;
379      unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
380      unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
381      unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
382      unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
383      unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
384      unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
385      MachineInstr *MI = I;
386      DebugLoc dl = MI->getDebugLoc();
387
388      if (isInt<16>(CalleeAmt)) {
389        BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg).addReg(StackReg).
390          addImm(CalleeAmt);
391      } else {
392        MachineBasicBlock::iterator MBBI = I;
393        BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
394          .addImm(CalleeAmt >> 16);
395        BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
396          .addReg(TmpReg, RegState::Kill)
397          .addImm(CalleeAmt & 0xFFFF);
398        BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
399          .addReg(StackReg)
400          .addReg(StackReg)
401          .addReg(TmpReg);
402      }
403    }
404  }
405  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
406  MBB.erase(I);
407}
408
409/// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered
410/// register first and then a spilled callee-saved register if that fails.
411static
412unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS,
413                             const TargetRegisterClass *RC, int SPAdj) {
414  assert(RS && "Register scavenging must be on");
415  unsigned Reg = RS->FindUnusedReg(RC);
416  // FIXME: move ARM callee-saved reg scan to target independent code, then
417  // search for already spilled CS register here.
418  if (Reg == 0)
419    Reg = RS->scavengeRegister(RC, II, SPAdj);
420  return Reg;
421}
422
423/// lowerDynamicAlloc - Generate the code for allocating an object in the
424/// current frame.  The sequence of code with be in the general form
425///
426///   addi   R0, SP, \#frameSize ; get the address of the previous frame
427///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
428///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
429///
430void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II,
431                                        int SPAdj, RegScavenger *RS) const {
432  // Get the instruction.
433  MachineInstr &MI = *II;
434  // Get the instruction's basic block.
435  MachineBasicBlock &MBB = *MI.getParent();
436  // Get the basic block's function.
437  MachineFunction &MF = *MBB.getParent();
438  // Get the frame info.
439  MachineFrameInfo *MFI = MF.getFrameInfo();
440  // Determine whether 64-bit pointers are used.
441  bool LP64 = Subtarget.isPPC64();
442  DebugLoc dl = MI.getDebugLoc();
443
444  // Get the maximum call stack size.
445  unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
446  // Get the total frame size.
447  unsigned FrameSize = MFI->getStackSize();
448
449  // Get stack alignments.
450  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
451  unsigned MaxAlign = MFI->getMaxAlignment();
452  if (MaxAlign > TargetAlign)
453    report_fatal_error("Dynamic alloca with large aligns not supported");
454
455  // Determine the previous frame's address.  If FrameSize can't be
456  // represented as 16 bits or we need special alignment, then we load the
457  // previous frame's address from 0(SP).  Why not do an addis of the hi?
458  // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
459  // Constructing the constant and adding would take 3 instructions.
460  // Fortunately, a frame greater than 32K is rare.
461  const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
462  const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
463  const TargetRegisterClass *RC = LP64 ? G8RC : GPRC;
464
465  // FIXME (64-bit): Use "findScratchRegister"
466  unsigned Reg;
467  if (EnableRegisterScavenging)
468    Reg = findScratchRegister(II, RS, RC, SPAdj);
469  else
470    Reg = PPC::R0;
471
472  if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
473    BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
474      .addReg(PPC::R31)
475      .addImm(FrameSize);
476  } else if (LP64) {
477    if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
478      BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
479        .addImm(0)
480        .addReg(PPC::X1);
481    else
482      BuildMI(MBB, II, dl, TII.get(PPC::LD), PPC::X0)
483        .addImm(0)
484        .addReg(PPC::X1);
485  } else {
486    BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
487      .addImm(0)
488      .addReg(PPC::R1);
489  }
490
491  // Grow the stack and update the stack pointer link, then determine the
492  // address of new allocated space.
493  if (LP64) {
494    if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
495      BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
496        .addReg(Reg, RegState::Kill)
497        .addReg(PPC::X1)
498        .addReg(MI.getOperand(1).getReg());
499    else
500      BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
501        .addReg(PPC::X0, RegState::Kill)
502        .addReg(PPC::X1)
503        .addReg(MI.getOperand(1).getReg());
504
505    if (!MI.getOperand(1).isKill())
506      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
507        .addReg(PPC::X1)
508        .addImm(maxCallFrameSize);
509    else
510      // Implicitly kill the register.
511      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
512        .addReg(PPC::X1)
513        .addImm(maxCallFrameSize)
514        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
515  } else {
516    BuildMI(MBB, II, dl, TII.get(PPC::STWUX))
517      .addReg(Reg, RegState::Kill)
518      .addReg(PPC::R1)
519      .addReg(MI.getOperand(1).getReg());
520
521    if (!MI.getOperand(1).isKill())
522      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
523        .addReg(PPC::R1)
524        .addImm(maxCallFrameSize);
525    else
526      // Implicitly kill the register.
527      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
528        .addReg(PPC::R1)
529        .addImm(maxCallFrameSize)
530        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
531  }
532
533  // Discard the DYNALLOC instruction.
534  MBB.erase(II);
535}
536
537/// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
538/// reserving a whole register (R0), we scrounge for one here. This generates
539/// code like this:
540///
541///   mfcr rA                  ; Move the conditional register into GPR rA.
542///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
543///   stw rA, FI               ; Store rA to the frame.
544///
545void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
546                                      unsigned FrameIndex, int SPAdj,
547                                      RegScavenger *RS) const {
548  // Get the instruction.
549  MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>, <FI>
550  // Get the instruction's basic block.
551  MachineBasicBlock &MBB = *MI.getParent();
552  DebugLoc dl = MI.getDebugLoc();
553
554  const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
555  const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
556  const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
557  unsigned Reg = findScratchRegister(II, RS, RC, SPAdj);
558  unsigned SrcReg = MI.getOperand(0).getReg();
559
560  // We need to store the CR in the low 4-bits of the saved value. First, issue
561  // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcReg.
562  BuildMI(MBB, II, dl, TII.get(PPC::MFCRpseud), Reg)
563          .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
564
565  // If the saved register wasn't CR0, shift the bits left so that they are in
566  // CR0's slot.
567  if (SrcReg != PPC::CR0)
568    // rlwinm rA, rA, ShiftBits, 0, 31.
569    BuildMI(MBB, II, dl, TII.get(PPC::RLWINM), Reg)
570      .addReg(Reg, RegState::Kill)
571      .addImm(PPCRegisterInfo::getRegisterNumbering(SrcReg) * 4)
572      .addImm(0)
573      .addImm(31);
574
575  addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
576                    .addReg(Reg, getKillRegState(MI.getOperand(1).getImm())),
577                    FrameIndex);
578
579  // Discard the pseudo instruction.
580  MBB.erase(II);
581}
582
583void
584PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
585                                     int SPAdj, RegScavenger *RS) const {
586  assert(SPAdj == 0 && "Unexpected");
587
588  // Get the instruction.
589  MachineInstr &MI = *II;
590  // Get the instruction's basic block.
591  MachineBasicBlock &MBB = *MI.getParent();
592  // Get the basic block's function.
593  MachineFunction &MF = *MBB.getParent();
594  // Get the frame info.
595  MachineFrameInfo *MFI = MF.getFrameInfo();
596  DebugLoc dl = MI.getDebugLoc();
597
598  // Find out which operand is the frame index.
599  unsigned FIOperandNo = 0;
600  while (!MI.getOperand(FIOperandNo).isFI()) {
601    ++FIOperandNo;
602    assert(FIOperandNo != MI.getNumOperands() &&
603           "Instr doesn't have FrameIndex operand!");
604  }
605  // Take into account whether it's an add or mem instruction
606  unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
607  if (MI.isInlineAsm())
608    OffsetOperandNo = FIOperandNo-1;
609
610  // Get the frame index.
611  int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
612
613  // Get the frame pointer save index.  Users of this index are primarily
614  // DYNALLOC instructions.
615  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
616  int FPSI = FI->getFramePointerSaveIndex();
617  // Get the instruction opcode.
618  unsigned OpC = MI.getOpcode();
619
620  // Special case for dynamic alloca.
621  if (FPSI && FrameIndex == FPSI &&
622      (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
623    lowerDynamicAlloc(II, SPAdj, RS);
624    return;
625  }
626
627  // Special case for pseudo-op SPILL_CR.
628  if (EnableRegisterScavenging) // FIXME (64-bit): Enable by default.
629    if (OpC == PPC::SPILL_CR) {
630      lowerCRSpilling(II, FrameIndex, SPAdj, RS);
631      return;
632    }
633
634  // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
635  MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
636                                              false);
637
638  // Figure out if the offset in the instruction is shifted right two bits. This
639  // is true for instructions like "STD", which the machine implicitly adds two
640  // low zeros to.
641  bool isIXAddr = false;
642  switch (OpC) {
643  case PPC::LWA:
644  case PPC::LD:
645  case PPC::STD:
646  case PPC::STD_32:
647    isIXAddr = true;
648    break;
649  }
650
651  // Now add the frame object offset to the offset from r1.
652  int Offset = MFI->getObjectOffset(FrameIndex);
653  if (!isIXAddr)
654    Offset += MI.getOperand(OffsetOperandNo).getImm();
655  else
656    Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
657
658  // If we're not using a Frame Pointer that has been set to the value of the
659  // SP before having the stack size subtracted from it, then add the stack size
660  // to Offset to get the correct offset.
661  // Naked functions have stack size 0, although getStackSize may not reflect that
662  // because we didn't call all the pieces that compute it for naked functions.
663  if (!MF.getFunction()->hasFnAttr(Attribute::Naked))
664    Offset += MFI->getStackSize();
665
666  // If we can, encode the offset directly into the instruction.  If this is a
667  // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
668  // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
669  // clear can be encoded.  This is extremely uncommon, because normally you
670  // only "std" to a stack slot that is at least 4-byte aligned, but it can
671  // happen in invalid code.
672  if (isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
673    if (isIXAddr)
674      Offset >>= 2;    // The actual encoded value has the low two bits zero.
675    MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
676    return;
677  }
678
679  // The offset doesn't fit into a single register, scavenge one to build the
680  // offset in.
681  // FIXME: figure out what SPAdj is doing here.
682
683  // FIXME (64-bit): Use "findScratchRegister".
684  unsigned SReg;
685  if (EnableRegisterScavenging)
686    SReg = findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj);
687  else
688    SReg = PPC::R0;
689
690  // Insert a set of rA with the full offset value before the ld, st, or add
691  BuildMI(MBB, II, dl, TII.get(PPC::LIS), SReg)
692    .addImm(Offset >> 16);
693  BuildMI(MBB, II, dl, TII.get(PPC::ORI), SReg)
694    .addReg(SReg, RegState::Kill)
695    .addImm(Offset);
696
697  // Convert into indexed form of the instruction:
698  //
699  //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
700  //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
701  unsigned OperandBase;
702
703  if (OpC != TargetOpcode::INLINEASM) {
704    assert(ImmToIdxMap.count(OpC) &&
705           "No indexed form of load or store available!");
706    unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
707    MI.setDesc(TII.get(NewOpcode));
708    OperandBase = 1;
709  } else {
710    OperandBase = OffsetOperandNo;
711  }
712
713  unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
714  MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
715  MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false);
716}
717
718/// VRRegNo - Map from a numbered VR register to its enum value.
719///
720static const unsigned short VRRegNo[] = {
721 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
722 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
723 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
724 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
725};
726
727/// RemoveVRSaveCode - We have found that this function does not need any code
728/// to manipulate the VRSAVE register, even though it uses vector registers.
729/// This can happen when the only registers used are known to be live in or out
730/// of the function.  Remove all of the VRSAVE related code from the function.
731static void RemoveVRSaveCode(MachineInstr *MI) {
732  MachineBasicBlock *Entry = MI->getParent();
733  MachineFunction *MF = Entry->getParent();
734
735  // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
736  MachineBasicBlock::iterator MBBI = MI;
737  ++MBBI;
738  assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
739  MBBI->eraseFromParent();
740
741  bool RemovedAllMTVRSAVEs = true;
742  // See if we can find and remove the MTVRSAVE instruction from all of the
743  // epilog blocks.
744  for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
745    // If last instruction is a return instruction, add an epilogue
746    if (!I->empty() && I->back().getDesc().isReturn()) {
747      bool FoundIt = false;
748      for (MBBI = I->end(); MBBI != I->begin(); ) {
749        --MBBI;
750        if (MBBI->getOpcode() == PPC::MTVRSAVE) {
751          MBBI->eraseFromParent();  // remove it.
752          FoundIt = true;
753          break;
754        }
755      }
756      RemovedAllMTVRSAVEs &= FoundIt;
757    }
758  }
759
760  // If we found and removed all MTVRSAVE instructions, remove the read of
761  // VRSAVE as well.
762  if (RemovedAllMTVRSAVEs) {
763    MBBI = MI;
764    assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
765    --MBBI;
766    assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
767    MBBI->eraseFromParent();
768  }
769
770  // Finally, nuke the UPDATE_VRSAVE.
771  MI->eraseFromParent();
772}
773
774// HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
775// instruction selector.  Based on the vector registers that have been used,
776// transform this into the appropriate ORI instruction.
777static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
778  MachineFunction *MF = MI->getParent()->getParent();
779  DebugLoc dl = MI->getDebugLoc();
780
781  unsigned UsedRegMask = 0;
782  for (unsigned i = 0; i != 32; ++i)
783    if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
784      UsedRegMask |= 1 << (31-i);
785
786  // Live in and live out values already must be in the mask, so don't bother
787  // marking them.
788  for (MachineRegisterInfo::livein_iterator
789       I = MF->getRegInfo().livein_begin(),
790       E = MF->getRegInfo().livein_end(); I != E; ++I) {
791    unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first);
792    if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
793      UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
794  }
795  for (MachineRegisterInfo::liveout_iterator
796       I = MF->getRegInfo().liveout_begin(),
797       E = MF->getRegInfo().liveout_end(); I != E; ++I) {
798    unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I);
799    if (VRRegNo[RegNo] == *I)              // If this really is a vector reg.
800      UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
801  }
802
803  // If no registers are used, turn this into a copy.
804  if (UsedRegMask == 0) {
805    // Remove all VRSAVE code.
806    RemoveVRSaveCode(MI);
807    return;
808  }
809
810  unsigned SrcReg = MI->getOperand(1).getReg();
811  unsigned DstReg = MI->getOperand(0).getReg();
812
813  if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
814    if (DstReg != SrcReg)
815      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
816        .addReg(SrcReg)
817        .addImm(UsedRegMask);
818    else
819      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
820        .addReg(SrcReg, RegState::Kill)
821        .addImm(UsedRegMask);
822  } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
823    if (DstReg != SrcReg)
824      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
825        .addReg(SrcReg)
826        .addImm(UsedRegMask >> 16);
827    else
828      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
829        .addReg(SrcReg, RegState::Kill)
830        .addImm(UsedRegMask >> 16);
831  } else {
832    if (DstReg != SrcReg)
833      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
834        .addReg(SrcReg)
835        .addImm(UsedRegMask >> 16);
836    else
837      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
838        .addReg(SrcReg, RegState::Kill)
839        .addImm(UsedRegMask >> 16);
840
841    BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
842      .addReg(DstReg, RegState::Kill)
843      .addImm(UsedRegMask & 0xFFFF);
844  }
845
846  // Remove the old UPDATE_VRSAVE instruction.
847  MI->eraseFromParent();
848}
849
850/// determineFrameLayout - Determine the size of the frame and maximum call
851/// frame size.
852void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const {
853  MachineFrameInfo *MFI = MF.getFrameInfo();
854
855  // Get the number of bytes to allocate from the FrameInfo
856  unsigned FrameSize = MFI->getStackSize();
857
858  // Get the alignments provided by the target, and the maximum alignment
859  // (if any) of the fixed frame objects.
860  unsigned MaxAlign = MFI->getMaxAlignment();
861  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
862  unsigned AlignMask = TargetAlign - 1;  //
863
864  // If we are a leaf function, and use up to 224 bytes of stack space,
865  // don't have a frame pointer, calls, or dynamic alloca then we do not need
866  // to adjust the stack pointer (we fit in the Red Zone).
867  bool DisableRedZone = MF.getFunction()->hasFnAttr(Attribute::NoRedZone);
868  // FIXME SVR4 The 32-bit SVR4 ABI has no red zone.
869  if (!DisableRedZone &&
870      FrameSize <= 224 &&                          // Fits in red zone.
871      !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
872      !MFI->adjustsStack() &&                      // No calls.
873      (!ALIGN_STACK || MaxAlign <= TargetAlign)) { // No special alignment.
874    // No need for frame
875    MFI->setStackSize(0);
876    return;
877  }
878
879  // Get the maximum call frame size of all the calls.
880  unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
881
882  // Maximum call frame needs to be at least big enough for linkage and 8 args.
883  unsigned minCallFrameSize =
884    PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(),
885                                      Subtarget.isDarwinABI());
886  maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
887
888  // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
889  // that allocations will be aligned.
890  if (MFI->hasVarSizedObjects())
891    maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
892
893  // Update maximum call frame size.
894  MFI->setMaxCallFrameSize(maxCallFrameSize);
895
896  // Include call frame size in total.
897  FrameSize += maxCallFrameSize;
898
899  // Make sure the frame is aligned.
900  FrameSize = (FrameSize + AlignMask) & ~AlignMask;
901
902  // Update frame info.
903  MFI->setStackSize(FrameSize);
904}
905
906void
907PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
908                                                      RegScavenger *RS) const {
909  //  Save and clear the LR state.
910  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
911  unsigned LR = getRARegister();
912  FI->setMustSaveLR(MustSaveLR(MF, LR));
913  MF.getRegInfo().setPhysRegUnused(LR);
914
915  //  Save R31 if necessary
916  int FPSI = FI->getFramePointerSaveIndex();
917  bool isPPC64 = Subtarget.isPPC64();
918  bool isDarwinABI  = Subtarget.isDarwinABI();
919  MachineFrameInfo *MFI = MF.getFrameInfo();
920
921  // If the frame pointer save index hasn't been defined yet.
922  if (!FPSI && needsFP(MF)) {
923    // Find out what the fix offset of the frame pointer save area.
924    int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
925                                                           isDarwinABI);
926    // Allocate the frame index for frame pointer save area.
927    FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
928    // Save the result.
929    FI->setFramePointerSaveIndex(FPSI);
930  }
931
932  // Reserve stack space to move the linkage area to in case of a tail call.
933  int TCSPDelta = 0;
934  if (GuaranteedTailCallOpt && (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
935    MF.getFrameInfo()->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
936  }
937
938  // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
939  // a large stack, which will require scavenging a register to materialize a
940  // large offset.
941  // FIXME: this doesn't actually check stack size, so is a bit pessimistic
942  // FIXME: doesn't detect whether or not we need to spill vXX, which requires
943  //        r0 for now.
944
945  if (EnableRegisterScavenging) // FIXME (64-bit): Enable.
946    if (needsFP(MF) || spillsCR(MF)) {
947      const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
948      const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
949      const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
950      RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
951                                                         RC->getAlignment(),
952                                                         false));
953    }
954}
955
956void
957PPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
958                                                     const {
959  // Early exit if not using the SVR4 ABI.
960  if (!Subtarget.isSVR4ABI()) {
961    return;
962  }
963
964  // Get callee saved register information.
965  MachineFrameInfo *FFI = MF.getFrameInfo();
966  const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
967
968  // Early exit if no callee saved registers are modified!
969  if (CSI.empty() && !needsFP(MF)) {
970    return;
971  }
972
973  unsigned MinGPR = PPC::R31;
974  unsigned MinG8R = PPC::X31;
975  unsigned MinFPR = PPC::F31;
976  unsigned MinVR = PPC::V31;
977
978  bool HasGPSaveArea = false;
979  bool HasG8SaveArea = false;
980  bool HasFPSaveArea = false;
981  bool HasCRSaveArea = false;
982  bool HasVRSAVESaveArea = false;
983  bool HasVRSaveArea = false;
984
985  SmallVector<CalleeSavedInfo, 18> GPRegs;
986  SmallVector<CalleeSavedInfo, 18> G8Regs;
987  SmallVector<CalleeSavedInfo, 18> FPRegs;
988  SmallVector<CalleeSavedInfo, 18> VRegs;
989
990  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
991    unsigned Reg = CSI[i].getReg();
992    if (PPC::GPRCRegisterClass->contains(Reg)) {
993      HasGPSaveArea = true;
994
995      GPRegs.push_back(CSI[i]);
996
997      if (Reg < MinGPR) {
998        MinGPR = Reg;
999      }
1000    } else if (PPC::G8RCRegisterClass->contains(Reg)) {
1001      HasG8SaveArea = true;
1002
1003      G8Regs.push_back(CSI[i]);
1004
1005      if (Reg < MinG8R) {
1006        MinG8R = Reg;
1007      }
1008    } else if (PPC::F8RCRegisterClass->contains(Reg)) {
1009      HasFPSaveArea = true;
1010
1011      FPRegs.push_back(CSI[i]);
1012
1013      if (Reg < MinFPR) {
1014        MinFPR = Reg;
1015      }
1016// FIXME SVR4: Disable CR save area for now.
1017    } else if (PPC::CRBITRCRegisterClass->contains(Reg)
1018               || PPC::CRRCRegisterClass->contains(Reg)) {
1019//      HasCRSaveArea = true;
1020    } else if (PPC::VRSAVERCRegisterClass->contains(Reg)) {
1021      HasVRSAVESaveArea = true;
1022    } else if (PPC::VRRCRegisterClass->contains(Reg)) {
1023      HasVRSaveArea = true;
1024
1025      VRegs.push_back(CSI[i]);
1026
1027      if (Reg < MinVR) {
1028        MinVR = Reg;
1029      }
1030    } else {
1031      llvm_unreachable("Unknown RegisterClass!");
1032    }
1033  }
1034
1035  PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1036
1037  int64_t LowerBound = 0;
1038
1039  // Take into account stack space reserved for tail calls.
1040  int TCSPDelta = 0;
1041  if (GuaranteedTailCallOpt && (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1042    LowerBound = TCSPDelta;
1043  }
1044
1045  // The Floating-point register save area is right below the back chain word
1046  // of the previous stack frame.
1047  if (HasFPSaveArea) {
1048    for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1049      int FI = FPRegs[i].getFrameIdx();
1050
1051      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1052    }
1053
1054    LowerBound -= (31 - getRegisterNumbering(MinFPR) + 1) * 8;
1055  }
1056
1057  // Check whether the frame pointer register is allocated. If so, make sure it
1058  // is spilled to the correct offset.
1059  if (needsFP(MF)) {
1060    HasGPSaveArea = true;
1061
1062    int FI = PFI->getFramePointerSaveIndex();
1063    assert(FI && "No Frame Pointer Save Slot!");
1064
1065    FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1066  }
1067
1068  // General register save area starts right below the Floating-point
1069  // register save area.
1070  if (HasGPSaveArea || HasG8SaveArea) {
1071    // Move general register save area spill slots down, taking into account
1072    // the size of the Floating-point register save area.
1073    for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1074      int FI = GPRegs[i].getFrameIdx();
1075
1076      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1077    }
1078
1079    // Move general register save area spill slots down, taking into account
1080    // the size of the Floating-point register save area.
1081    for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1082      int FI = G8Regs[i].getFrameIdx();
1083
1084      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1085    }
1086
1087    unsigned MinReg = std::min<unsigned>(getRegisterNumbering(MinGPR),
1088                                         getRegisterNumbering(MinG8R));
1089
1090    if (Subtarget.isPPC64()) {
1091      LowerBound -= (31 - MinReg + 1) * 8;
1092    } else {
1093      LowerBound -= (31 - MinReg + 1) * 4;
1094    }
1095  }
1096
1097  // The CR save area is below the general register save area.
1098  if (HasCRSaveArea) {
1099    // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1100    //             which have the CR/CRBIT register class?
1101    // Adjust the frame index of the CR spill slot.
1102    for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1103      unsigned Reg = CSI[i].getReg();
1104
1105      if (PPC::CRBITRCRegisterClass->contains(Reg) ||
1106          PPC::CRRCRegisterClass->contains(Reg)) {
1107        int FI = CSI[i].getFrameIdx();
1108
1109        FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1110      }
1111    }
1112
1113    LowerBound -= 4; // The CR save area is always 4 bytes long.
1114  }
1115
1116  if (HasVRSAVESaveArea) {
1117    // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1118    //             which have the VRSAVE register class?
1119    // Adjust the frame index of the VRSAVE spill slot.
1120    for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1121      unsigned Reg = CSI[i].getReg();
1122
1123      if (PPC::VRSAVERCRegisterClass->contains(Reg)) {
1124        int FI = CSI[i].getFrameIdx();
1125
1126        FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1127      }
1128    }
1129
1130    LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1131  }
1132
1133  if (HasVRSaveArea) {
1134    // Insert alignment padding, we need 16-byte alignment.
1135    LowerBound = (LowerBound - 15) & ~(15);
1136
1137    for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1138      int FI = VRegs[i].getFrameIdx();
1139
1140      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1141    }
1142  }
1143}
1144
1145void
1146PPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
1147  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
1148  MachineBasicBlock::iterator MBBI = MBB.begin();
1149  MachineFrameInfo *MFI = MF.getFrameInfo();
1150  MachineModuleInfo &MMI = MF.getMMI();
1151  DebugLoc dl;
1152  bool needsFrameMoves = MMI.hasDebugInfo() ||
1153       !MF.getFunction()->doesNotThrow() ||
1154       UnwindTablesMandatory;
1155
1156  // Prepare for frame info.
1157  MCSymbol *FrameLabel = 0;
1158
1159  // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
1160  // process it.
1161  for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
1162    if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
1163      HandleVRSaveUpdate(MBBI, TII);
1164      break;
1165    }
1166  }
1167
1168  // Move MBBI back to the beginning of the function.
1169  MBBI = MBB.begin();
1170
1171  // Work out frame sizes.
1172  determineFrameLayout(MF);
1173  unsigned FrameSize = MFI->getStackSize();
1174
1175  int NegFrameSize = -FrameSize;
1176
1177  // Get processor type.
1178  bool isPPC64 = Subtarget.isPPC64();
1179  // Get operating system
1180  bool isDarwinABI = Subtarget.isDarwinABI();
1181  // Check if the link register (LR) must be saved.
1182  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1183  bool MustSaveLR = FI->mustSaveLR();
1184  // Do we have a frame pointer for this function?
1185  bool HasFP = hasFP(MF) && FrameSize;
1186
1187  int LROffset = PPCFrameInfo::getReturnSaveOffset(isPPC64, isDarwinABI);
1188
1189  int FPOffset = 0;
1190  if (HasFP) {
1191    if (Subtarget.isSVR4ABI()) {
1192      MachineFrameInfo *FFI = MF.getFrameInfo();
1193      int FPIndex = FI->getFramePointerSaveIndex();
1194      assert(FPIndex && "No Frame Pointer Save Slot!");
1195      FPOffset = FFI->getObjectOffset(FPIndex);
1196    } else {
1197      FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64, isDarwinABI);
1198    }
1199  }
1200
1201  if (isPPC64) {
1202    if (MustSaveLR)
1203      BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR8), PPC::X0);
1204
1205    if (HasFP)
1206      BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
1207        .addReg(PPC::X31)
1208        .addImm(FPOffset/4)
1209        .addReg(PPC::X1);
1210
1211    if (MustSaveLR)
1212      BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
1213        .addReg(PPC::X0)
1214        .addImm(LROffset / 4)
1215        .addReg(PPC::X1);
1216  } else {
1217    if (MustSaveLR)
1218      BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR), PPC::R0);
1219
1220    if (HasFP)
1221      BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
1222        .addReg(PPC::R31)
1223        .addImm(FPOffset)
1224        .addReg(PPC::R1);
1225
1226    if (MustSaveLR)
1227      BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
1228        .addReg(PPC::R0)
1229        .addImm(LROffset)
1230        .addReg(PPC::R1);
1231  }
1232
1233  // Skip if a leaf routine.
1234  if (!FrameSize) return;
1235
1236  // Get stack alignments.
1237  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1238  unsigned MaxAlign = MFI->getMaxAlignment();
1239
1240  // Adjust stack pointer: r1 += NegFrameSize.
1241  // If there is a preferred stack alignment, align R1 now
1242  if (!isPPC64) {
1243    // PPC32.
1244    if (ALIGN_STACK && MaxAlign > TargetAlign) {
1245      assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
1246             "Invalid alignment!");
1247      assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
1248
1249      BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), PPC::R0)
1250        .addReg(PPC::R1)
1251        .addImm(0)
1252        .addImm(32 - Log2_32(MaxAlign))
1253        .addImm(31);
1254      BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC) ,PPC::R0)
1255        .addReg(PPC::R0, RegState::Kill)
1256        .addImm(NegFrameSize);
1257      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
1258        .addReg(PPC::R1)
1259        .addReg(PPC::R1)
1260        .addReg(PPC::R0);
1261    } else if (isInt<16>(NegFrameSize)) {
1262      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1)
1263        .addReg(PPC::R1)
1264        .addImm(NegFrameSize)
1265        .addReg(PPC::R1);
1266    } else {
1267      BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
1268        .addImm(NegFrameSize >> 16);
1269      BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
1270        .addReg(PPC::R0, RegState::Kill)
1271        .addImm(NegFrameSize & 0xFFFF);
1272      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
1273        .addReg(PPC::R1)
1274        .addReg(PPC::R1)
1275        .addReg(PPC::R0);
1276    }
1277  } else {    // PPC64.
1278    if (ALIGN_STACK && MaxAlign > TargetAlign) {
1279      assert(isPowerOf2_32(MaxAlign) && isInt<16>(MaxAlign) &&
1280             "Invalid alignment!");
1281      assert(isInt<16>(NegFrameSize) && "Unhandled stack size and alignment!");
1282
1283      BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), PPC::X0)
1284        .addReg(PPC::X1)
1285        .addImm(0)
1286        .addImm(64 - Log2_32(MaxAlign));
1287      BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC8), PPC::X0)
1288        .addReg(PPC::X0)
1289        .addImm(NegFrameSize);
1290      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
1291        .addReg(PPC::X1)
1292        .addReg(PPC::X1)
1293        .addReg(PPC::X0);
1294    } else if (isInt<16>(NegFrameSize)) {
1295      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1)
1296        .addReg(PPC::X1)
1297        .addImm(NegFrameSize / 4)
1298        .addReg(PPC::X1);
1299    } else {
1300      BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
1301        .addImm(NegFrameSize >> 16);
1302      BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
1303        .addReg(PPC::X0, RegState::Kill)
1304        .addImm(NegFrameSize & 0xFFFF);
1305      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
1306        .addReg(PPC::X1)
1307        .addReg(PPC::X1)
1308        .addReg(PPC::X0);
1309    }
1310  }
1311
1312  std::vector<MachineMove> &Moves = MMI.getFrameMoves();
1313
1314  // Add the "machine moves" for the instructions we generated above, but in
1315  // reverse order.
1316  if (needsFrameMoves) {
1317    // Mark effective beginning of when frame pointer becomes valid.
1318    FrameLabel = MMI.getContext().CreateTempSymbol();
1319    BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(FrameLabel);
1320
1321    // Show update of SP.
1322    if (NegFrameSize) {
1323      MachineLocation SPDst(MachineLocation::VirtualFP);
1324      MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
1325      Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
1326    } else {
1327      MachineLocation SP(isPPC64 ? PPC::X31 : PPC::R31);
1328      Moves.push_back(MachineMove(FrameLabel, SP, SP));
1329    }
1330
1331    if (HasFP) {
1332      MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
1333      MachineLocation FPSrc(isPPC64 ? PPC::X31 : PPC::R31);
1334      Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
1335    }
1336
1337    if (MustSaveLR) {
1338      MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
1339      MachineLocation LRSrc(isPPC64 ? PPC::LR8 : PPC::LR);
1340      Moves.push_back(MachineMove(FrameLabel, LRDst, LRSrc));
1341    }
1342  }
1343
1344  MCSymbol *ReadyLabel = 0;
1345
1346  // If there is a frame pointer, copy R1 into R31
1347  if (HasFP) {
1348    if (!isPPC64) {
1349      BuildMI(MBB, MBBI, dl, TII.get(PPC::OR), PPC::R31)
1350        .addReg(PPC::R1)
1351        .addReg(PPC::R1);
1352    } else {
1353      BuildMI(MBB, MBBI, dl, TII.get(PPC::OR8), PPC::X31)
1354        .addReg(PPC::X1)
1355        .addReg(PPC::X1);
1356    }
1357
1358    if (needsFrameMoves) {
1359      ReadyLabel = MMI.getContext().CreateTempSymbol();
1360
1361      // Mark effective beginning of when frame pointer is ready.
1362      BuildMI(MBB, MBBI, dl, TII.get(PPC::PROLOG_LABEL)).addSym(ReadyLabel);
1363
1364      MachineLocation FPDst(HasFP ? (isPPC64 ? PPC::X31 : PPC::R31) :
1365                                    (isPPC64 ? PPC::X1 : PPC::R1));
1366      MachineLocation FPSrc(MachineLocation::VirtualFP);
1367      Moves.push_back(MachineMove(ReadyLabel, FPDst, FPSrc));
1368    }
1369  }
1370
1371  if (needsFrameMoves) {
1372    MCSymbol *Label = HasFP ? ReadyLabel : FrameLabel;
1373
1374    // Add callee saved registers to move list.
1375    const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1376    for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
1377      int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
1378      unsigned Reg = CSI[I].getReg();
1379      if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
1380      MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
1381      MachineLocation CSSrc(Reg);
1382      Moves.push_back(MachineMove(Label, CSDst, CSSrc));
1383    }
1384  }
1385}
1386
1387void PPCRegisterInfo::emitEpilogue(MachineFunction &MF,
1388                                   MachineBasicBlock &MBB) const {
1389  MachineBasicBlock::iterator MBBI = prior(MBB.end());
1390  unsigned RetOpcode = MBBI->getOpcode();
1391  DebugLoc dl;
1392
1393  assert( (RetOpcode == PPC::BLR ||
1394           RetOpcode == PPC::TCRETURNri ||
1395           RetOpcode == PPC::TCRETURNdi ||
1396           RetOpcode == PPC::TCRETURNai ||
1397           RetOpcode == PPC::TCRETURNri8 ||
1398           RetOpcode == PPC::TCRETURNdi8 ||
1399           RetOpcode == PPC::TCRETURNai8) &&
1400         "Can only insert epilog into returning blocks");
1401
1402  // Get alignment info so we know how to restore r1
1403  const MachineFrameInfo *MFI = MF.getFrameInfo();
1404  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1405  unsigned MaxAlign = MFI->getMaxAlignment();
1406
1407  // Get the number of bytes allocated from the FrameInfo.
1408  int FrameSize = MFI->getStackSize();
1409
1410  // Get processor type.
1411  bool isPPC64 = Subtarget.isPPC64();
1412  // Get operating system
1413  bool isDarwinABI = Subtarget.isDarwinABI();
1414  // Check if the link register (LR) has been saved.
1415  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1416  bool MustSaveLR = FI->mustSaveLR();
1417  // Do we have a frame pointer for this function?
1418  bool HasFP = hasFP(MF) && FrameSize;
1419
1420  int LROffset = PPCFrameInfo::getReturnSaveOffset(isPPC64, isDarwinABI);
1421
1422  int FPOffset = 0;
1423  if (HasFP) {
1424    if (Subtarget.isSVR4ABI()) {
1425      MachineFrameInfo *FFI = MF.getFrameInfo();
1426      int FPIndex = FI->getFramePointerSaveIndex();
1427      assert(FPIndex && "No Frame Pointer Save Slot!");
1428      FPOffset = FFI->getObjectOffset(FPIndex);
1429    } else {
1430      FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64, isDarwinABI);
1431    }
1432  }
1433
1434  bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
1435    RetOpcode == PPC::TCRETURNdi ||
1436    RetOpcode == PPC::TCRETURNai ||
1437    RetOpcode == PPC::TCRETURNri8 ||
1438    RetOpcode == PPC::TCRETURNdi8 ||
1439    RetOpcode == PPC::TCRETURNai8;
1440
1441  if (UsesTCRet) {
1442    int MaxTCRetDelta = FI->getTailCallSPDelta();
1443    MachineOperand &StackAdjust = MBBI->getOperand(1);
1444    assert(StackAdjust.isImm() && "Expecting immediate value.");
1445    // Adjust stack pointer.
1446    int StackAdj = StackAdjust.getImm();
1447    int Delta = StackAdj - MaxTCRetDelta;
1448    assert((Delta >= 0) && "Delta must be positive");
1449    if (MaxTCRetDelta>0)
1450      FrameSize += (StackAdj +Delta);
1451    else
1452      FrameSize += StackAdj;
1453  }
1454
1455  if (FrameSize) {
1456    // The loaded (or persistent) stack pointer value is offset by the 'stwu'
1457    // on entry to the function.  Add this offset back now.
1458    if (!isPPC64) {
1459      // If this function contained a fastcc call and GuaranteedTailCallOpt is
1460      // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1461      // call which invalidates the stack pointer value in SP(0). So we use the
1462      // value of R31 in this case.
1463      if (FI->hasFastCall() && isInt<16>(FrameSize)) {
1464        assert(hasFP(MF) && "Expecting a valid the frame pointer.");
1465        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
1466          .addReg(PPC::R31).addImm(FrameSize);
1467      } else if(FI->hasFastCall()) {
1468        BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
1469          .addImm(FrameSize >> 16);
1470        BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
1471          .addReg(PPC::R0, RegState::Kill)
1472          .addImm(FrameSize & 0xFFFF);
1473        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD4))
1474          .addReg(PPC::R1)
1475          .addReg(PPC::R31)
1476          .addReg(PPC::R0);
1477      } else if (isInt<16>(FrameSize) &&
1478                 (!ALIGN_STACK || TargetAlign >= MaxAlign) &&
1479                 !MFI->hasVarSizedObjects()) {
1480        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
1481          .addReg(PPC::R1).addImm(FrameSize);
1482      } else {
1483        BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ),PPC::R1)
1484          .addImm(0).addReg(PPC::R1);
1485      }
1486    } else {
1487      if (FI->hasFastCall() && isInt<16>(FrameSize)) {
1488        assert(hasFP(MF) && "Expecting a valid the frame pointer.");
1489        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
1490          .addReg(PPC::X31).addImm(FrameSize);
1491      } else if(FI->hasFastCall()) {
1492        BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
1493          .addImm(FrameSize >> 16);
1494        BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
1495          .addReg(PPC::X0, RegState::Kill)
1496          .addImm(FrameSize & 0xFFFF);
1497        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD8))
1498          .addReg(PPC::X1)
1499          .addReg(PPC::X31)
1500          .addReg(PPC::X0);
1501      } else if (isInt<16>(FrameSize) && TargetAlign >= MaxAlign &&
1502            !MFI->hasVarSizedObjects()) {
1503        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
1504           .addReg(PPC::X1).addImm(FrameSize);
1505      } else {
1506        BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X1)
1507           .addImm(0).addReg(PPC::X1);
1508      }
1509    }
1510  }
1511
1512  if (isPPC64) {
1513    if (MustSaveLR)
1514      BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X0)
1515        .addImm(LROffset/4).addReg(PPC::X1);
1516
1517    if (HasFP)
1518      BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X31)
1519        .addImm(FPOffset/4).addReg(PPC::X1);
1520
1521    if (MustSaveLR)
1522      BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR8)).addReg(PPC::X0);
1523  } else {
1524    if (MustSaveLR)
1525      BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R0)
1526          .addImm(LROffset).addReg(PPC::R1);
1527
1528    if (HasFP)
1529      BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R31)
1530          .addImm(FPOffset).addReg(PPC::R1);
1531
1532    if (MustSaveLR)
1533      BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR)).addReg(PPC::R0);
1534  }
1535
1536  // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1537  // call optimization
1538  if (GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1539      MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1540     PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1541     unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1542     unsigned StackReg = isPPC64 ? PPC::X1 : PPC::R1;
1543     unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
1544     unsigned TmpReg = isPPC64 ? PPC::X0 : PPC::R0;
1545     unsigned ADDIInstr = isPPC64 ? PPC::ADDI8 : PPC::ADDI;
1546     unsigned ADDInstr = isPPC64 ? PPC::ADD8 : PPC::ADD4;
1547     unsigned LISInstr = isPPC64 ? PPC::LIS8 : PPC::LIS;
1548     unsigned ORIInstr = isPPC64 ? PPC::ORI8 : PPC::ORI;
1549
1550     if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
1551       BuildMI(MBB, MBBI, dl, TII.get(ADDIInstr), StackReg)
1552         .addReg(StackReg).addImm(CallerAllocatedAmt);
1553     } else {
1554       BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1555          .addImm(CallerAllocatedAmt >> 16);
1556       BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1557          .addReg(TmpReg, RegState::Kill)
1558          .addImm(CallerAllocatedAmt & 0xFFFF);
1559       BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
1560          .addReg(StackReg)
1561          .addReg(FPReg)
1562          .addReg(TmpReg);
1563     }
1564  } else if (RetOpcode == PPC::TCRETURNdi) {
1565    MBBI = prior(MBB.end());
1566    MachineOperand &JumpTarget = MBBI->getOperand(0);
1567    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1568      addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1569  } else if (RetOpcode == PPC::TCRETURNri) {
1570    MBBI = prior(MBB.end());
1571    assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1572    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1573  } else if (RetOpcode == PPC::TCRETURNai) {
1574    MBBI = prior(MBB.end());
1575    MachineOperand &JumpTarget = MBBI->getOperand(0);
1576    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1577  } else if (RetOpcode == PPC::TCRETURNdi8) {
1578    MBBI = prior(MBB.end());
1579    MachineOperand &JumpTarget = MBBI->getOperand(0);
1580    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1581      addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1582  } else if (RetOpcode == PPC::TCRETURNri8) {
1583    MBBI = prior(MBB.end());
1584    assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1585    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1586  } else if (RetOpcode == PPC::TCRETURNai8) {
1587    MBBI = prior(MBB.end());
1588    MachineOperand &JumpTarget = MBBI->getOperand(0);
1589    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1590  }
1591}
1592
1593unsigned PPCRegisterInfo::getRARegister() const {
1594  return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
1595}
1596
1597unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1598  if (!Subtarget.isPPC64())
1599    return hasFP(MF) ? PPC::R31 : PPC::R1;
1600  else
1601    return hasFP(MF) ? PPC::X31 : PPC::X1;
1602}
1603
1604void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
1605                                                                         const {
1606  // Initial state of the frame pointer is R1.
1607  MachineLocation Dst(MachineLocation::VirtualFP);
1608  MachineLocation Src(PPC::R1, 0);
1609  Moves.push_back(MachineMove(0, Dst, Src));
1610}
1611
1612unsigned PPCRegisterInfo::getEHExceptionRegister() const {
1613  return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
1614}
1615
1616unsigned PPCRegisterInfo::getEHHandlerRegister() const {
1617  return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
1618}
1619
1620int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1621  // FIXME: Most probably dwarf numbers differs for Linux and Darwin
1622  return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1623}
1624
1625#include "PPCGenRegisterInfo.inc"
1626