DebugInfo: remove target-specific Frame Index handling for DBG_VALUE MachineInstrs
[oota-llvm.git] / lib / Target / PowerPC / PPCRegisterInfo.cpp
1 //===-- PPCRegisterInfo.cpp - PowerPC Register 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 PowerPC implementation of the TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "reginfo"
16 #include "PPCRegisterInfo.h"
17 #include "PPC.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrBuilder.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCSubtarget.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegisterScavenging.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetFrameLowering.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include <cstdlib>
45
46 #define GET_REGINFO_TARGET_DESC
47 #include "PPCGenRegisterInfo.inc"
48
49 using namespace llvm;
50
51 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST)
52   : PPCGenRegisterInfo(ST.isPPC64() ? PPC::LR8 : PPC::LR,
53                        ST.isPPC64() ? 0 : 1,
54                        ST.isPPC64() ? 0 : 1),
55     Subtarget(ST) {
56   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
57   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
58   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
59   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
60   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
61   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
62   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
63   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
64
65   // 64-bit
66   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
67   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
68   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
69   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
70   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
71 }
72
73 /// getPointerRegClass - Return the register class to use to hold pointers.
74 /// This is used for addressing modes.
75 const TargetRegisterClass *
76 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
77                                                                        const {
78   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
79   // when it checks for ZERO folding.
80   if (Kind == 1) {
81     if (Subtarget.isPPC64())
82       return &PPC::G8RC_NOX0RegClass;
83     return &PPC::GPRC_NOR0RegClass;
84   }
85
86   if (Subtarget.isPPC64())
87     return &PPC::G8RCRegClass;
88   return &PPC::GPRCRegClass;
89 }
90
91 const uint16_t*
92 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
93   if (Subtarget.isDarwinABI())
94     return Subtarget.isPPC64() ? CSR_Darwin64_SaveList :
95                                  CSR_Darwin32_SaveList;
96
97   return Subtarget.isPPC64() ? CSR_SVR464_SaveList : CSR_SVR432_SaveList;
98 }
99
100 const uint32_t*
101 PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
102   if (Subtarget.isDarwinABI())
103     return Subtarget.isPPC64() ? CSR_Darwin64_RegMask :
104                                  CSR_Darwin32_RegMask;
105
106   return Subtarget.isPPC64() ? CSR_SVR464_RegMask : CSR_SVR432_RegMask;
107 }
108
109 const uint32_t*
110 PPCRegisterInfo::getNoPreservedMask() const {
111   // The naming here is inverted: The CSR_NoRegs_Altivec has the
112   // Altivec registers masked so that they're not saved and restored around
113   // instructions with this preserved mask.
114
115   if (!Subtarget.hasAltivec())
116     return CSR_NoRegs_Altivec_RegMask;
117
118   if (Subtarget.isDarwin())
119     return CSR_NoRegs_Darwin_RegMask;
120   return CSR_NoRegs_RegMask;
121 }
122
123 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
124   BitVector Reserved(getNumRegs());
125   const PPCFrameLowering *PPCFI =
126     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
127
128   // The ZERO register is not really a register, but the representation of r0
129   // when used in instructions that treat r0 as the constant 0.
130   Reserved.set(PPC::ZERO);
131   Reserved.set(PPC::ZERO8);
132
133   // The FP register is also not really a register, but is the representation
134   // of the frame pointer register used by ISD::FRAMEADDR.
135   Reserved.set(PPC::FP);
136   Reserved.set(PPC::FP8);
137
138   // The counter registers must be reserved so that counter-based loops can
139   // be correctly formed (and the mtctr instructions are not DCE'd).
140   Reserved.set(PPC::CTR);
141   Reserved.set(PPC::CTR8);
142
143   Reserved.set(PPC::R1);
144   Reserved.set(PPC::LR);
145   Reserved.set(PPC::LR8);
146   Reserved.set(PPC::RM);
147
148   // The SVR4 ABI reserves r2 and r13
149   if (Subtarget.isSVR4ABI()) {
150     Reserved.set(PPC::R2);  // System-reserved register
151     Reserved.set(PPC::R13); // Small Data Area pointer register
152   }
153   
154   // On PPC64, r13 is the thread pointer. Never allocate this register.
155   if (Subtarget.isPPC64()) {
156     Reserved.set(PPC::R13);
157
158     Reserved.set(PPC::X1);
159     Reserved.set(PPC::X13);
160
161     if (PPCFI->needsFP(MF))
162       Reserved.set(PPC::X31);
163
164     // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
165     if (Subtarget.isSVR4ABI()) {
166       Reserved.set(PPC::X2);
167     }
168   }
169
170   if (PPCFI->needsFP(MF))
171     Reserved.set(PPC::R31);
172
173   return Reserved;
174 }
175
176 unsigned
177 PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
178                                          MachineFunction &MF) const {
179   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
180   const unsigned DefaultSafety = 1;
181
182   switch (RC->getID()) {
183   default:
184     return 0;
185   case PPC::G8RC_NOX0RegClassID:
186   case PPC::GPRC_NOR0RegClassID: 
187   case PPC::G8RCRegClassID:
188   case PPC::GPRCRegClassID: {
189     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
190     return 32 - FP - DefaultSafety;
191   }
192   case PPC::F8RCRegClassID:
193   case PPC::F4RCRegClassID:
194   case PPC::VRRCRegClassID:
195     return 32 - DefaultSafety;
196   case PPC::CRRCRegClassID:
197     return 8 - DefaultSafety;
198   }
199 }
200
201 //===----------------------------------------------------------------------===//
202 // Stack Frame Processing methods
203 //===----------------------------------------------------------------------===//
204
205 /// lowerDynamicAlloc - Generate the code for allocating an object in the
206 /// current frame.  The sequence of code with be in the general form
207 ///
208 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
209 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
210 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
211 ///
212 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
213   // Get the instruction.
214   MachineInstr &MI = *II;
215   // Get the instruction's basic block.
216   MachineBasicBlock &MBB = *MI.getParent();
217   // Get the basic block's function.
218   MachineFunction &MF = *MBB.getParent();
219   // Get the frame info.
220   MachineFrameInfo *MFI = MF.getFrameInfo();
221   // Get the instruction info.
222   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
223   // Determine whether 64-bit pointers are used.
224   bool LP64 = Subtarget.isPPC64();
225   DebugLoc dl = MI.getDebugLoc();
226
227   // Get the maximum call stack size.
228   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
229   // Get the total frame size.
230   unsigned FrameSize = MFI->getStackSize();
231   
232   // Get stack alignments.
233   unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
234   unsigned MaxAlign = MFI->getMaxAlignment();
235   if (MaxAlign > TargetAlign)
236     report_fatal_error("Dynamic alloca with large aligns not supported");
237
238   // Determine the previous frame's address.  If FrameSize can't be
239   // represented as 16 bits or we need special alignment, then we load the
240   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
241   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
242   // Constructing the constant and adding would take 3 instructions. 
243   // Fortunately, a frame greater than 32K is rare.
244   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
245   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
246   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
247   
248   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
249     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
250       .addReg(PPC::R31)
251       .addImm(FrameSize);
252   } else if (LP64) {
253     BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
254       .addImm(0)
255       .addReg(PPC::X1);
256   } else {
257     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
258       .addImm(0)
259       .addReg(PPC::R1);
260   }
261   
262   // Grow the stack and update the stack pointer link, then determine the
263   // address of new allocated space.
264   if (LP64) {
265     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
266       .addReg(Reg, RegState::Kill)
267       .addReg(PPC::X1)
268       .addReg(MI.getOperand(1).getReg());
269     if (!MI.getOperand(1).isKill())
270       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
271         .addReg(PPC::X1)
272         .addImm(maxCallFrameSize);
273     else
274       // Implicitly kill the register.
275       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
276         .addReg(PPC::X1)
277         .addImm(maxCallFrameSize)
278         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
279   } else {
280     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
281       .addReg(Reg, RegState::Kill)
282       .addReg(PPC::R1)
283       .addReg(MI.getOperand(1).getReg());
284
285     if (!MI.getOperand(1).isKill())
286       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
287         .addReg(PPC::R1)
288         .addImm(maxCallFrameSize);
289     else
290       // Implicitly kill the register.
291       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
292         .addReg(PPC::R1)
293         .addImm(maxCallFrameSize)
294         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
295   }
296   
297   // Discard the DYNALLOC instruction.
298   MBB.erase(II);
299 }
300
301 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
302 /// reserving a whole register (R0), we scrounge for one here. This generates
303 /// code like this:
304 ///
305 ///   mfcr rA                  ; Move the conditional register into GPR rA.
306 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
307 ///   stw rA, FI               ; Store rA to the frame.
308 ///
309 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
310                                       unsigned FrameIndex) const {
311   // Get the instruction.
312   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
313   // Get the instruction's basic block.
314   MachineBasicBlock &MBB = *MI.getParent();
315   MachineFunction &MF = *MBB.getParent();
316   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
317   DebugLoc dl = MI.getDebugLoc();
318
319   bool LP64 = Subtarget.isPPC64();
320   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
321   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
322
323   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
324   unsigned SrcReg = MI.getOperand(0).getReg();
325
326   // We need to store the CR in the low 4-bits of the saved value. First, issue
327   // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcReg.
328   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFCR8pseud : PPC::MFCRpseud), Reg)
329           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
330     
331   // If the saved register wasn't CR0, shift the bits left so that they are in
332   // CR0's slot.
333   if (SrcReg != PPC::CR0) {
334     unsigned Reg1 = Reg;
335     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
336
337     // rlwinm rA, rA, ShiftBits, 0, 31.
338     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
339       .addReg(Reg1, RegState::Kill)
340       .addImm(getEncodingValue(SrcReg) * 4)
341       .addImm(0)
342       .addImm(31);
343   }
344
345   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
346                     .addReg(Reg, RegState::Kill),
347                     FrameIndex);
348
349   // Discard the pseudo instruction.
350   MBB.erase(II);
351 }
352
353 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
354                                       unsigned FrameIndex) const {
355   // Get the instruction.
356   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
357   // Get the instruction's basic block.
358   MachineBasicBlock &MBB = *MI.getParent();
359   MachineFunction &MF = *MBB.getParent();
360   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
361   DebugLoc dl = MI.getDebugLoc();
362
363   bool LP64 = Subtarget.isPPC64();
364   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
365   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
366
367   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
368   unsigned DestReg = MI.getOperand(0).getReg();
369   assert(MI.definesRegister(DestReg) &&
370     "RESTORE_CR does not define its destination");
371
372   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
373                               Reg), FrameIndex);
374
375   // If the reloaded register isn't CR0, shift the bits right so that they are
376   // in the right CR's slot.
377   if (DestReg != PPC::CR0) {
378     unsigned Reg1 = Reg;
379     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
380
381     unsigned ShiftBits = getEncodingValue(DestReg)*4;
382     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
383     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
384              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
385              .addImm(31);
386   }
387
388   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTCRF8 : PPC::MTCRF), DestReg)
389              .addReg(Reg, RegState::Kill);
390
391   // Discard the pseudo instruction.
392   MBB.erase(II);
393 }
394
395 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
396                                           unsigned FrameIndex) const {
397   // Get the instruction.
398   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
399   // Get the instruction's basic block.
400   MachineBasicBlock &MBB = *MI.getParent();
401   MachineFunction &MF = *MBB.getParent();
402   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
403   DebugLoc dl = MI.getDebugLoc();
404
405   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
406   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
407   unsigned SrcReg = MI.getOperand(0).getReg();
408
409   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
410           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
411     
412   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
413                     .addReg(Reg, RegState::Kill),
414                     FrameIndex);
415
416   // Discard the pseudo instruction.
417   MBB.erase(II);
418 }
419
420 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
421                                          unsigned FrameIndex) const {
422   // Get the instruction.
423   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
424   // Get the instruction's basic block.
425   MachineBasicBlock &MBB = *MI.getParent();
426   MachineFunction &MF = *MBB.getParent();
427   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
428   DebugLoc dl = MI.getDebugLoc();
429
430   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
431   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
432   unsigned DestReg = MI.getOperand(0).getReg();
433   assert(MI.definesRegister(DestReg) &&
434     "RESTORE_VRSAVE does not define its destination");
435
436   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
437                               Reg), FrameIndex);
438
439   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
440              .addReg(Reg, RegState::Kill);
441
442   // Discard the pseudo instruction.
443   MBB.erase(II);
444 }
445
446 bool
447 PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
448                                       unsigned Reg, int &FrameIdx) const {
449
450   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
451   // ABI, return true to prevent allocating an additional frame slot.
452   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
453   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
454   // previously created the stack slot if needed, so return its FrameIdx.
455   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
456     if (Subtarget.isPPC64())
457       FrameIdx = 0;
458     else {
459       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
460       FrameIdx = FI->getCRSpillFrameIndex();
461     }
462     return true;
463   }
464   return false;
465 }
466
467 // Figure out if the offset in the instruction must be a multiple of 4.
468 // This is true for instructions like "STD".
469 static bool usesIXAddr(const MachineInstr &MI) {
470   unsigned OpC = MI.getOpcode();
471
472   switch (OpC) {
473   default:
474     return false;
475   case PPC::LWA:
476   case PPC::LD:
477   case PPC::STD:
478     return true;
479   }
480 }
481
482 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
483 static unsigned getOffsetONFromFION(const MachineInstr &MI,
484                                     unsigned FIOperandNum) {
485   // Take into account whether it's an add or mem instruction
486   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
487   if (MI.isInlineAsm())
488     OffsetOperandNo = FIOperandNum-1;
489
490   return OffsetOperandNo;
491 }
492
493 void
494 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
495                                      int SPAdj, unsigned FIOperandNum,
496                                      RegScavenger *RS) const {
497   assert(SPAdj == 0 && "Unexpected");
498
499   // Get the instruction.
500   MachineInstr &MI = *II;
501   // Get the instruction's basic block.
502   MachineBasicBlock &MBB = *MI.getParent();
503   // Get the basic block's function.
504   MachineFunction &MF = *MBB.getParent();
505   // Get the instruction info.
506   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
507   // Get the frame info.
508   MachineFrameInfo *MFI = MF.getFrameInfo();
509   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
510   DebugLoc dl = MI.getDebugLoc();
511
512   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
513
514   // Get the frame index.
515   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
516
517   // Get the frame pointer save index.  Users of this index are primarily
518   // DYNALLOC instructions.
519   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
520   int FPSI = FI->getFramePointerSaveIndex();
521   // Get the instruction opcode.
522   unsigned OpC = MI.getOpcode();
523   
524   // Special case for dynamic alloca.
525   if (FPSI && FrameIndex == FPSI &&
526       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
527     lowerDynamicAlloc(II);
528     return;
529   }
530
531   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
532   if (OpC == PPC::SPILL_CR) {
533     lowerCRSpilling(II, FrameIndex);
534     return;
535   } else if (OpC == PPC::RESTORE_CR) {
536     lowerCRRestore(II, FrameIndex);
537     return;
538   } else if (OpC == PPC::SPILL_VRSAVE) {
539     lowerVRSAVESpilling(II, FrameIndex);
540     return;
541   } else if (OpC == PPC::RESTORE_VRSAVE) {
542     lowerVRSAVERestore(II, FrameIndex);
543     return;
544   }
545
546   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
547
548   bool is64Bit = Subtarget.isPPC64();
549   MI.getOperand(FIOperandNum).ChangeToRegister(TFI->hasFP(MF) ?
550                                               (is64Bit ? PPC::X31 : PPC::R31) :
551                                                 (is64Bit ? PPC::X1 : PPC::R1),
552                                               false);
553
554   // Figure out if the offset in the instruction is shifted right two bits.
555   bool isIXAddr = usesIXAddr(MI);
556
557   // If the instruction is not present in ImmToIdxMap, then it has no immediate
558   // form (and must be r+r).
559   bool noImmForm = !MI.isInlineAsm() && !ImmToIdxMap.count(OpC);
560
561   // Now add the frame object offset to the offset from r1.
562   int Offset = MFI->getObjectOffset(FrameIndex);
563   Offset += MI.getOperand(OffsetOperandNo).getImm();
564
565   // If we're not using a Frame Pointer that has been set to the value of the
566   // SP before having the stack size subtracted from it, then add the stack size
567   // to Offset to get the correct offset.
568   // Naked functions have stack size 0, although getStackSize may not reflect that
569   // because we didn't call all the pieces that compute it for naked functions.
570   if (!MF.getFunction()->getAttributes().
571         hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked))
572     Offset += MFI->getStackSize();
573
574   // If we can, encode the offset directly into the instruction.  If this is a
575   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
576   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
577   // clear can be encoded.  This is extremely uncommon, because normally you
578   // only "std" to a stack slot that is at least 4-byte aligned, but it can
579   // happen in invalid code.
580   assert(OpC != PPC::DBG_VALUE &&
581          "This should be handle in a target independent way");
582   if (!noImmForm && isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
583     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
584     return;
585   }
586
587   // The offset doesn't fit into a single register, scavenge one to build the
588   // offset in.
589
590   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
591   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
592   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
593   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
594            SReg = MF.getRegInfo().createVirtualRegister(RC);
595
596   // Insert a set of rA with the full offset value before the ld, st, or add
597   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
598     .addImm(Offset >> 16);
599   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
600     .addReg(SRegHi, RegState::Kill)
601     .addImm(Offset);
602
603   // Convert into indexed form of the instruction:
604   // 
605   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
606   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
607   unsigned OperandBase;
608
609   if (noImmForm)
610     OperandBase = 1;
611   else if (OpC != TargetOpcode::INLINEASM) {
612     assert(ImmToIdxMap.count(OpC) &&
613            "No indexed form of load or store available!");
614     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
615     MI.setDesc(TII.get(NewOpcode));
616     OperandBase = 1;
617   } else {
618     OperandBase = OffsetOperandNo;
619   }
620
621   unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
622   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
623   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
624 }
625
626 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
627   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
628
629   if (!Subtarget.isPPC64())
630     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
631   else
632     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
633 }
634
635 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
636   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
637 }
638
639 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
640   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
641 }
642
643 /// Returns true if the instruction's frame index
644 /// reference would be better served by a base register other than FP
645 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
646 /// references it should create new base registers for.
647 bool PPCRegisterInfo::
648 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
649   assert(Offset < 0 && "Local offset must be negative");
650
651   unsigned FIOperandNum = 0;
652   while (!MI->getOperand(FIOperandNum).isFI()) {
653     ++FIOperandNum;
654     assert(FIOperandNum < MI->getNumOperands() &&
655            "Instr doesn't have FrameIndex operand!");
656   }
657
658   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
659   Offset += MI->getOperand(OffsetOperandNo).getImm();
660
661   // It's the load/store FI references that cause issues, as it can be difficult
662   // to materialize the offset if it won't fit in the literal field. Estimate
663   // based on the size of the local frame and some conservative assumptions
664   // about the rest of the stack frame (note, this is pre-regalloc, so
665   // we don't know everything for certain yet) whether this offset is likely
666   // to be out of range of the immediate. Return true if so.
667
668   // We only generate virtual base registers for loads and stores that have
669   // an r+i form. Return false for everything else.
670   unsigned OpC = MI->getOpcode();
671   if (!ImmToIdxMap.count(OpC))
672     return false;
673
674   // Don't generate a new virtual base register just to add zero to it.
675   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
676       MI->getOperand(2).getImm() == 0)
677     return false;
678
679   MachineBasicBlock &MBB = *MI->getParent();
680   MachineFunction &MF = *MBB.getParent();
681
682   const PPCFrameLowering *PPCFI =
683     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
684   unsigned StackEst =
685     PPCFI->determineFrameLayout(MF, false, true);
686
687   // If we likely don't need a stack frame, then we probably don't need a
688   // virtual base register either.
689   if (!StackEst)
690     return false;
691
692   // Estimate an offset from the stack pointer.
693   // The incoming offset is relating to the SP at the start of the function,
694   // but when we access the local it'll be relative to the SP after local
695   // allocation, so adjust our SP-relative offset by that allocation size.
696   Offset += StackEst;
697
698   // The frame pointer will point to the end of the stack, so estimate the
699   // offset as the difference between the object offset and the FP location.
700   return !isFrameOffsetLegal(MI, Offset);
701 }
702
703 /// Insert defining instruction(s) for BaseReg to
704 /// be a pointer to FrameIdx at the beginning of the basic block.
705 void PPCRegisterInfo::
706 materializeFrameBaseRegister(MachineBasicBlock *MBB,
707                              unsigned BaseReg, int FrameIdx,
708                              int64_t Offset) const {
709   unsigned ADDriOpc = Subtarget.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
710
711   MachineBasicBlock::iterator Ins = MBB->begin();
712   DebugLoc DL;                  // Defaults to "unknown"
713   if (Ins != MBB->end())
714     DL = Ins->getDebugLoc();
715
716   const MachineFunction &MF = *MBB->getParent();
717   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
718   const MCInstrDesc &MCID = TII.get(ADDriOpc);
719   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
720   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
721
722   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
723     .addFrameIndex(FrameIdx).addImm(Offset);
724 }
725
726 void
727 PPCRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
728                                    unsigned BaseReg, int64_t Offset) const {
729   MachineInstr &MI = *I;
730
731   unsigned FIOperandNum = 0;
732   while (!MI.getOperand(FIOperandNum).isFI()) {
733     ++FIOperandNum;
734     assert(FIOperandNum < MI.getNumOperands() &&
735            "Instr doesn't have FrameIndex operand!");
736   }
737
738   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
739   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
740   Offset += MI.getOperand(OffsetOperandNo).getImm();
741   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
742 }
743
744 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
745                                          int64_t Offset) const {
746   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
747          (isInt<16>(Offset) && (!usesIXAddr(*MI) || (Offset & 3) == 0));
748 }
749