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