xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision a10fff51d9d6bdf99676dd432fa5c528b83c51bd)
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 MRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "reginfo"
15 #include "PPC.h"
16 #include "PPCInstrBuilder.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCRegisterInfo.h"
19 #include "PPCFrameInfo.h"
20 #include "PPCSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Type.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineLocation.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/ADT/BitVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include <cstdlib>
41 using namespace llvm;
42 
43 /// getRegisterNumbering - Given the enum value for some register, e.g.
44 /// PPC::F14, return the number that it corresponds to (e.g. 14).
45 unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
46   using namespace PPC;
47   switch (RegEnum) {
48   case R0 :  case X0 :  case F0 :  case V0 : case CR0:  return  0;
49   case R1 :  case X1 :  case F1 :  case V1 : case CR1:  return  1;
50   case R2 :  case X2 :  case F2 :  case V2 : case CR2:  return  2;
51   case R3 :  case X3 :  case F3 :  case V3 : case CR3:  return  3;
52   case R4 :  case X4 :  case F4 :  case V4 : case CR4:  return  4;
53   case R5 :  case X5 :  case F5 :  case V5 : case CR5:  return  5;
54   case R6 :  case X6 :  case F6 :  case V6 : case CR6:  return  6;
55   case R7 :  case X7 :  case F7 :  case V7 : case CR7:  return  7;
56   case R8 :  case X8 :  case F8 :  case V8 : return  8;
57   case R9 :  case X9 :  case F9 :  case V9 : return  9;
58   case R10:  case X10:  case F10:  case V10: return 10;
59   case R11:  case X11:  case F11:  case V11: return 11;
60   case R12:  case X12:  case F12:  case V12: return 12;
61   case R13:  case X13:  case F13:  case V13: return 13;
62   case R14:  case X14:  case F14:  case V14: return 14;
63   case R15:  case X15:  case F15:  case V15: return 15;
64   case R16:  case X16:  case F16:  case V16: return 16;
65   case R17:  case X17:  case F17:  case V17: return 17;
66   case R18:  case X18:  case F18:  case V18: return 18;
67   case R19:  case X19:  case F19:  case V19: return 19;
68   case R20:  case X20:  case F20:  case V20: return 20;
69   case R21:  case X21:  case F21:  case V21: return 21;
70   case R22:  case X22:  case F22:  case V22: return 22;
71   case R23:  case X23:  case F23:  case V23: return 23;
72   case R24:  case X24:  case F24:  case V24: return 24;
73   case R25:  case X25:  case F25:  case V25: return 25;
74   case R26:  case X26:  case F26:  case V26: return 26;
75   case R27:  case X27:  case F27:  case V27: return 27;
76   case R28:  case X28:  case F28:  case V28: return 28;
77   case R29:  case X29:  case F29:  case V29: return 29;
78   case R30:  case X30:  case F30:  case V30: return 30;
79   case R31:  case X31:  case F31:  case V31: return 31;
80   default:
81     cerr << "Unhandled reg in PPCRegisterInfo::getRegisterNumbering!\n";
82     abort();
83   }
84 }
85 
86 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
87                                  const TargetInstrInfo &tii)
88   : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
89     Subtarget(ST), TII(tii) {
90   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
91   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
92   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
93   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
94   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
95   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
96   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
97   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
98 
99   // 64-bit
100   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
101   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
102   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
103   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
104   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
105 }
106 
107 static void StoreRegToStackSlot(const TargetInstrInfo &TII,
108                                 unsigned SrcReg, bool isKill, int FrameIdx,
109                                 const TargetRegisterClass *RC,
110                                 SmallVectorImpl<MachineInstr*> &NewMIs) {
111   if (RC == PPC::GPRCRegisterClass) {
112     if (SrcReg != PPC::LR) {
113       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
114                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
115     } else {
116       // FIXME: this spills LR immediately to memory in one step.  To do this,
117       // we use R11, which we know cannot be used in the prolog/epilog.  This is
118       // a hack.
119       NewMIs.push_back(BuildMI(TII.get(PPC::MFLR), PPC::R11));
120       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
121                               .addReg(PPC::R11, false, false, isKill), FrameIdx));
122     }
123   } else if (RC == PPC::G8RCRegisterClass) {
124     if (SrcReg != PPC::LR8) {
125       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STD))
126                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
127     } else {
128       // FIXME: this spills LR immediately to memory in one step.  To do this,
129       // we use R11, which we know cannot be used in the prolog/epilog.  This is
130       // a hack.
131       NewMIs.push_back(BuildMI(TII.get(PPC::MFLR8), PPC::X11));
132       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STD))
133                               .addReg(PPC::X11, false, false, isKill), FrameIdx));
134     }
135   } else if (RC == PPC::F8RCRegisterClass) {
136     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STFD))
137                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
138   } else if (RC == PPC::F4RCRegisterClass) {
139     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STFS))
140                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
141   } else if (RC == PPC::CRRCRegisterClass) {
142     // FIXME: We use R0 here, because it isn't available for RA.
143     // We need to store the CR in the low 4-bits of the saved value.  First,
144     // issue a MFCR to save all of the CRBits.
145     NewMIs.push_back(BuildMI(TII.get(PPC::MFCR), PPC::R0));
146 
147     // If the saved register wasn't CR0, shift the bits left so that they are in
148     // CR0's slot.
149     if (SrcReg != PPC::CR0) {
150       unsigned ShiftBits = PPCRegisterInfo::getRegisterNumbering(SrcReg)*4;
151       // rlwinm r0, r0, ShiftBits, 0, 31.
152       NewMIs.push_back(BuildMI(TII.get(PPC::RLWINM), PPC::R0)
153                        .addReg(PPC::R0).addImm(ShiftBits).addImm(0).addImm(31));
154     }
155 
156     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
157                                .addReg(PPC::R0, false, false, isKill), FrameIdx));
158   } else if (RC == PPC::VRRCRegisterClass) {
159     // We don't have indexed addressing for vector loads.  Emit:
160     // R0 = ADDI FI#
161     // STVX VAL, 0, R0
162     //
163     // FIXME: We use R0 here, because it isn't available for RA.
164     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::ADDI), PPC::R0),
165                                        FrameIdx, 0, 0));
166     NewMIs.push_back(BuildMI(TII.get(PPC::STVX))
167            .addReg(SrcReg, false, false, isKill).addReg(PPC::R0).addReg(PPC::R0));
168   } else {
169     assert(0 && "Unknown regclass!");
170     abort();
171   }
172 }
173 
174 void
175 PPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
176                                      MachineBasicBlock::iterator MI,
177                                      unsigned SrcReg, bool isKill, int FrameIdx,
178                                      const TargetRegisterClass *RC) const {
179   SmallVector<MachineInstr*, 4> NewMIs;
180   StoreRegToStackSlot(TII, SrcReg, isKill, FrameIdx, RC, NewMIs);
181   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
182     MBB.insert(MI, NewMIs[i]);
183 }
184 
185 void PPCRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
186                                      bool isKill,
187                                      SmallVectorImpl<MachineOperand> &Addr,
188                                      const TargetRegisterClass *RC,
189                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
190   if (Addr[0].isFrameIndex()) {
191     StoreRegToStackSlot(TII, SrcReg, isKill, Addr[0].getIndex(), RC, NewMIs);
192     return;
193   }
194 
195   unsigned Opc = 0;
196   if (RC == PPC::GPRCRegisterClass) {
197     Opc = PPC::STW;
198   } else if (RC == PPC::G8RCRegisterClass) {
199     Opc = PPC::STD;
200   } else if (RC == PPC::F8RCRegisterClass) {
201     Opc = PPC::STFD;
202   } else if (RC == PPC::F4RCRegisterClass) {
203     Opc = PPC::STFS;
204   } else if (RC == PPC::VRRCRegisterClass) {
205     Opc = PPC::STVX;
206   } else {
207     assert(0 && "Unknown regclass!");
208     abort();
209   }
210   MachineInstrBuilder MIB = BuildMI(TII.get(Opc))
211     .addReg(SrcReg, false, false, isKill);
212   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
213     MachineOperand &MO = Addr[i];
214     if (MO.isRegister())
215       MIB.addReg(MO.getReg());
216     else if (MO.isImmediate())
217       MIB.addImm(MO.getImm());
218     else
219       MIB.addFrameIndex(MO.getIndex());
220   }
221   NewMIs.push_back(MIB);
222   return;
223 }
224 
225 static void LoadRegFromStackSlot(const TargetInstrInfo &TII,
226                                  unsigned DestReg, int FrameIdx,
227                                  const TargetRegisterClass *RC,
228                                  SmallVectorImpl<MachineInstr*> &NewMIs) {
229   if (RC == PPC::GPRCRegisterClass) {
230     if (DestReg != PPC::LR) {
231       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), DestReg),
232                                          FrameIdx));
233     } else {
234       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), PPC::R11),
235                                          FrameIdx));
236       NewMIs.push_back(BuildMI(TII.get(PPC::MTLR)).addReg(PPC::R11));
237     }
238   } else if (RC == PPC::G8RCRegisterClass) {
239     if (DestReg != PPC::LR8) {
240       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LD), DestReg),
241                                          FrameIdx));
242     } else {
243       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LD), PPC::R11),
244                                          FrameIdx));
245       NewMIs.push_back(BuildMI(TII.get(PPC::MTLR8)).addReg(PPC::R11));
246     }
247   } else if (RC == PPC::F8RCRegisterClass) {
248     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LFD), DestReg),
249                                        FrameIdx));
250   } else if (RC == PPC::F4RCRegisterClass) {
251     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LFS), DestReg),
252                                        FrameIdx));
253   } else if (RC == PPC::CRRCRegisterClass) {
254     // FIXME: We use R0 here, because it isn't available for RA.
255     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), PPC::R0),
256                                        FrameIdx));
257 
258     // If the reloaded register isn't CR0, shift the bits right so that they are
259     // in the right CR's slot.
260     if (DestReg != PPC::CR0) {
261       unsigned ShiftBits = PPCRegisterInfo::getRegisterNumbering(DestReg)*4;
262       // rlwinm r11, r11, 32-ShiftBits, 0, 31.
263       NewMIs.push_back(BuildMI(TII.get(PPC::RLWINM), PPC::R0)
264                     .addReg(PPC::R0).addImm(32-ShiftBits).addImm(0).addImm(31));
265     }
266 
267     NewMIs.push_back(BuildMI(TII.get(PPC::MTCRF), DestReg).addReg(PPC::R0));
268   } else if (RC == PPC::VRRCRegisterClass) {
269     // We don't have indexed addressing for vector loads.  Emit:
270     // R0 = ADDI FI#
271     // Dest = LVX 0, R0
272     //
273     // FIXME: We use R0 here, because it isn't available for RA.
274     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::ADDI), PPC::R0),
275                                        FrameIdx, 0, 0));
276     NewMIs.push_back(BuildMI(TII.get(PPC::LVX),DestReg).addReg(PPC::R0)
277                      .addReg(PPC::R0));
278   } else {
279     assert(0 && "Unknown regclass!");
280     abort();
281   }
282 }
283 
284 void
285 PPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
286                                       MachineBasicBlock::iterator MI,
287                                       unsigned DestReg, int FrameIdx,
288                                       const TargetRegisterClass *RC) const {
289   SmallVector<MachineInstr*, 4> NewMIs;
290   LoadRegFromStackSlot(TII, DestReg, FrameIdx, RC, NewMIs);
291   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
292     MBB.insert(MI, NewMIs[i]);
293 }
294 
295 void PPCRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
296                                       SmallVectorImpl<MachineOperand> &Addr,
297                                       const TargetRegisterClass *RC,
298                                   SmallVectorImpl<MachineInstr*> &NewMIs) const{
299   if (Addr[0].isFrameIndex()) {
300     LoadRegFromStackSlot(TII, DestReg, Addr[0].getIndex(), RC, NewMIs);
301     return;
302   }
303 
304   unsigned Opc = 0;
305   if (RC == PPC::GPRCRegisterClass) {
306     assert(DestReg != PPC::LR && "Can't handle this yet!");
307     Opc = PPC::LWZ;
308   } else if (RC == PPC::G8RCRegisterClass) {
309     assert(DestReg != PPC::LR8 && "Can't handle this yet!");
310     Opc = PPC::LD;
311   } else if (RC == PPC::F8RCRegisterClass) {
312     Opc = PPC::LFD;
313   } else if (RC == PPC::F4RCRegisterClass) {
314     Opc = PPC::LFS;
315   } else if (RC == PPC::VRRCRegisterClass) {
316     Opc = PPC::LVX;
317   } else {
318     assert(0 && "Unknown regclass!");
319     abort();
320   }
321   MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
322   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
323     MachineOperand &MO = Addr[i];
324     if (MO.isRegister())
325       MIB.addReg(MO.getReg());
326     else if (MO.isImmediate())
327       MIB.addImm(MO.getImm());
328     else
329       MIB.addFrameIndex(MO.getIndex());
330   }
331   NewMIs.push_back(MIB);
332   return;
333 }
334 
335 void PPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
336                                    MachineBasicBlock::iterator MI,
337                                    unsigned DestReg, unsigned SrcReg,
338                                    const TargetRegisterClass *DestRC,
339                                    const TargetRegisterClass *SrcRC) const {
340   if (DestRC != SrcRC) {
341     cerr << "Not yet supported!";
342     abort();
343   }
344 
345   if (DestRC == PPC::GPRCRegisterClass) {
346     BuildMI(MBB, MI, TII.get(PPC::OR), DestReg).addReg(SrcReg).addReg(SrcReg);
347   } else if (DestRC == PPC::G8RCRegisterClass) {
348     BuildMI(MBB, MI, TII.get(PPC::OR8), DestReg).addReg(SrcReg).addReg(SrcReg);
349   } else if (DestRC == PPC::F4RCRegisterClass) {
350     BuildMI(MBB, MI, TII.get(PPC::FMRS), DestReg).addReg(SrcReg);
351   } else if (DestRC == PPC::F8RCRegisterClass) {
352     BuildMI(MBB, MI, TII.get(PPC::FMRD), DestReg).addReg(SrcReg);
353   } else if (DestRC == PPC::CRRCRegisterClass) {
354     BuildMI(MBB, MI, TII.get(PPC::MCRF), DestReg).addReg(SrcReg);
355   } else if (DestRC == PPC::VRRCRegisterClass) {
356     BuildMI(MBB, MI, TII.get(PPC::VOR), DestReg).addReg(SrcReg).addReg(SrcReg);
357   } else {
358     cerr << "Attempt to copy register that is not GPR or FPR";
359     abort();
360   }
361 }
362 
363 void PPCRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
364                                     MachineBasicBlock::iterator I,
365                                     unsigned DestReg,
366                                     const MachineInstr *Orig) const {
367   MachineInstr *MI = Orig->clone();
368   MI->getOperand(0).setReg(DestReg);
369   MBB.insert(I, MI);
370 }
371 
372 const unsigned*
373 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
374   // 32-bit Darwin calling convention.
375   static const unsigned Macho32_CalleeSavedRegs[] = {
376               PPC::R13, PPC::R14, PPC::R15,
377     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
378     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
379     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
380     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
381 
382     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
383     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
384     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
385     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
386     PPC::F30, PPC::F31,
387 
388     PPC::CR2, PPC::CR3, PPC::CR4,
389     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
390     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
391     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
392 
393     PPC::LR,  0
394   };
395 
396   static const unsigned ELF32_CalleeSavedRegs[] = {
397               PPC::R13, PPC::R14, PPC::R15,
398     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
399     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
400     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
401     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
402 
403                                   PPC::F9,
404     PPC::F10, PPC::F11, PPC::F12, PPC::F13,
405     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
406     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
407     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
408     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
409     PPC::F30, PPC::F31,
410 
411     PPC::CR2, PPC::CR3, PPC::CR4,
412     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
413     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
414     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
415 
416     PPC::LR,  0
417   };
418   // 64-bit Darwin calling convention.
419   static const unsigned Macho64_CalleeSavedRegs[] = {
420     PPC::X14, PPC::X15,
421     PPC::X16, PPC::X17, PPC::X18, PPC::X19,
422     PPC::X20, PPC::X21, PPC::X22, PPC::X23,
423     PPC::X24, PPC::X25, PPC::X26, PPC::X27,
424     PPC::X28, PPC::X29, PPC::X30, PPC::X31,
425 
426     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
427     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
428     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
429     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
430     PPC::F30, PPC::F31,
431 
432     PPC::CR2, PPC::CR3, PPC::CR4,
433     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
434     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
435     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
436 
437     PPC::LR8,  0
438   };
439 
440   if (Subtarget.isMachoABI())
441     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegs :
442                                  Macho32_CalleeSavedRegs;
443 
444   // ELF 32.
445   return ELF32_CalleeSavedRegs;
446 }
447 
448 const TargetRegisterClass* const*
449 PPCRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
450   // 32-bit Macho calling convention.
451   static const TargetRegisterClass * const Macho32_CalleeSavedRegClasses[] = {
452                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
453     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
454     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
455     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
456     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
457 
458     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
459     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
460     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
461     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
462     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
463 
464     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
465 
466     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
467     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
468     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
469 
470     &PPC::GPRCRegClass, 0
471   };
472 
473   static const TargetRegisterClass * const ELF32_CalleeSavedRegClasses[] = {
474                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
475     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
476     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
477     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
478     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
479 
480                                                              &PPC::F8RCRegClass,
481     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
482     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
483     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
484     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
485     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
486     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
487 
488     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
489 
490     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
491     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
492     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
493 
494     &PPC::GPRCRegClass, 0
495   };
496 
497   // 64-bit Macho calling convention.
498   static const TargetRegisterClass * const Macho64_CalleeSavedRegClasses[] = {
499     &PPC::G8RCRegClass,&PPC::G8RCRegClass,
500     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
501     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
502     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
503     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
504 
505     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
506     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
507     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
508     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
509     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
510 
511     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
512 
513     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
514     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
515     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
516 
517     &PPC::G8RCRegClass, 0
518   };
519 
520   if (Subtarget.isMachoABI())
521     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegClasses :
522                                  Macho32_CalleeSavedRegClasses;
523 
524   // ELF 32.
525   return ELF32_CalleeSavedRegClasses;
526 }
527 
528 // needsFP - Return true if the specified function should have a dedicated frame
529 // pointer register.  This is true if the function has variable sized allocas or
530 // if frame pointer elimination is disabled.
531 //
532 static bool needsFP(const MachineFunction &MF) {
533   const MachineFrameInfo *MFI = MF.getFrameInfo();
534   return NoFramePointerElim || MFI->hasVarSizedObjects();
535 }
536 
537 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
538   BitVector Reserved(getNumRegs());
539   Reserved.set(PPC::R0);
540   Reserved.set(PPC::R1);
541   Reserved.set(PPC::LR);
542   // In Linux, r2 is reserved for the OS.
543   if (!Subtarget.isDarwin())
544     Reserved.set(PPC::R2);
545   // On PPC64, r13 is the thread pointer.  Never allocate this register.
546   // Note that this is overconservative, as it also prevents allocation of
547   // R31 when the FP is not needed.
548   if (Subtarget.isPPC64()) {
549     Reserved.set(PPC::R13);
550     Reserved.set(PPC::R31);
551   }
552   if (needsFP(MF))
553     Reserved.set(PPC::R31);
554   return Reserved;
555 }
556 
557 /// foldMemoryOperand - PowerPC (like most RISC's) can only fold spills into
558 /// copy instructions, turning them into load/store instructions.
559 MachineInstr *PPCRegisterInfo::foldMemoryOperand(MachineInstr *MI,
560                                               SmallVectorImpl<unsigned> &Ops,
561                                               int FrameIndex) const {
562   if (Ops.size() != 1) return NULL;
563 
564   // Make sure this is a reg-reg copy.  Note that we can't handle MCRF, because
565   // it takes more than one instruction to store it.
566   unsigned Opc = MI->getOpcode();
567   unsigned OpNum = Ops[0];
568 
569   MachineInstr *NewMI = NULL;
570   if ((Opc == PPC::OR &&
571        MI->getOperand(1).getReg() == MI->getOperand(2).getReg())) {
572     if (OpNum == 0) {  // move -> store
573       unsigned InReg = MI->getOperand(1).getReg();
574       NewMI = addFrameReference(BuildMI(TII.get(PPC::STW)).addReg(InReg),
575                                 FrameIndex);
576     } else {           // move -> load
577       unsigned OutReg = MI->getOperand(0).getReg();
578       NewMI = addFrameReference(BuildMI(TII.get(PPC::LWZ), OutReg),
579                                 FrameIndex);
580     }
581   } else if ((Opc == PPC::OR8 &&
582               MI->getOperand(1).getReg() == MI->getOperand(2).getReg())) {
583     if (OpNum == 0) {  // move -> store
584       unsigned InReg = MI->getOperand(1).getReg();
585       NewMI = addFrameReference(BuildMI(TII.get(PPC::STD)).addReg(InReg),
586                                 FrameIndex);
587     } else {           // move -> load
588       unsigned OutReg = MI->getOperand(0).getReg();
589       NewMI = addFrameReference(BuildMI(TII.get(PPC::LD), OutReg), FrameIndex);
590     }
591   } else if (Opc == PPC::FMRD) {
592     if (OpNum == 0) {  // move -> store
593       unsigned InReg = MI->getOperand(1).getReg();
594       NewMI = addFrameReference(BuildMI(TII.get(PPC::STFD)).addReg(InReg),
595                                 FrameIndex);
596     } else {           // move -> load
597       unsigned OutReg = MI->getOperand(0).getReg();
598       NewMI = addFrameReference(BuildMI(TII.get(PPC::LFD), OutReg), FrameIndex);
599     }
600   } else if (Opc == PPC::FMRS) {
601     if (OpNum == 0) {  // move -> store
602       unsigned InReg = MI->getOperand(1).getReg();
603       NewMI = addFrameReference(BuildMI(TII.get(PPC::STFS)).addReg(InReg),
604                                 FrameIndex);
605     } else {           // move -> load
606       unsigned OutReg = MI->getOperand(0).getReg();
607       NewMI = addFrameReference(BuildMI(TII.get(PPC::LFS), OutReg), FrameIndex);
608     }
609   }
610 
611   if (NewMI)
612     NewMI->copyKillDeadInfo(MI);
613   return NewMI;
614 }
615 
616 bool PPCRegisterInfo::canFoldMemoryOperand(MachineInstr *MI,
617                                          SmallVectorImpl<unsigned> &Ops) const {
618   if (Ops.size() != 1) return false;
619 
620   // Make sure this is a reg-reg copy.  Note that we can't handle MCRF, because
621   // it takes more than one instruction to store it.
622   unsigned Opc = MI->getOpcode();
623 
624   if ((Opc == PPC::OR &&
625        MI->getOperand(1).getReg() == MI->getOperand(2).getReg()))
626     return true;
627   else if ((Opc == PPC::OR8 &&
628               MI->getOperand(1).getReg() == MI->getOperand(2).getReg()))
629     return true;
630   else if (Opc == PPC::FMRD || Opc == PPC::FMRS)
631     return true;
632 
633   return false;
634 }
635 
636 //===----------------------------------------------------------------------===//
637 // Stack Frame Processing methods
638 //===----------------------------------------------------------------------===//
639 
640 // hasFP - Return true if the specified function actually has a dedicated frame
641 // pointer register.  This is true if the function needs a frame pointer and has
642 // a non-zero stack size.
643 bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
644   const MachineFrameInfo *MFI = MF.getFrameInfo();
645   return MFI->getStackSize() && needsFP(MF);
646 }
647 
648 /// MustSaveLR - Return true if this function requires that we save the LR
649 /// register onto the stack in the prolog and restore it in the epilog of the
650 /// function.
651 static bool MustSaveLR(const MachineFunction &MF) {
652   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
653 
654   // We need an save/restore of LR if there is any use/def of LR explicitly, or
655   // if there is some use of the LR stack slot (e.g. for builtin_return_address.
656   return MFI->usesLR() || MFI->isLRStoreRequired() ||
657          // FIXME: Anything that has a call should clobber the LR register,
658          // isn't this redundant??
659          MF.getFrameInfo()->hasCalls();
660 }
661 
662 void PPCRegisterInfo::
663 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
664                               MachineBasicBlock::iterator I) const {
665   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
666   MBB.erase(I);
667 }
668 
669 /// LowerDynamicAlloc - Generate the code for allocating an object in the
670 /// current frame.  The sequence of code with be in the general form
671 ///
672 ///   addi   R0, SP, #frameSize ; get the address of the previous frame
673 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
674 ///   addi   Rnew, SP, #maxCalFrameSize ; get the top of the allocation
675 ///
676 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
677   // Get the instruction.
678   MachineInstr &MI = *II;
679   // Get the instruction's basic block.
680   MachineBasicBlock &MBB = *MI.getParent();
681   // Get the basic block's function.
682   MachineFunction &MF = *MBB.getParent();
683   // Get the frame info.
684   MachineFrameInfo *MFI = MF.getFrameInfo();
685   // Determine whether 64-bit pointers are used.
686   bool LP64 = Subtarget.isPPC64();
687 
688   // Get the maximum call stack size.
689   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
690   // Get the total frame size.
691   unsigned FrameSize = MFI->getStackSize();
692 
693   // Get stack alignments.
694   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
695   unsigned MaxAlign = MFI->getMaxAlignment();
696   assert(MaxAlign <= TargetAlign &&
697          "Dynamic alloca with large aligns not supported");
698 
699   // Determine the previous frame's address.  If FrameSize can't be
700   // represented as 16 bits or we need special alignment, then we load the
701   // previous frame's address from 0(SP).  Why not do an addis of the hi?
702   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
703   // Constructing the constant and adding would take 3 instructions.
704   // Fortunately, a frame greater than 32K is rare.
705   if (MaxAlign < TargetAlign && isInt16(FrameSize)) {
706     BuildMI(MBB, II, TII.get(PPC::ADDI), PPC::R0)
707       .addReg(PPC::R31)
708       .addImm(FrameSize);
709   } else if (LP64) {
710     BuildMI(MBB, II, TII.get(PPC::LD), PPC::X0)
711       .addImm(0)
712       .addReg(PPC::X1);
713   } else {
714     BuildMI(MBB, II, TII.get(PPC::LWZ), PPC::R0)
715       .addImm(0)
716       .addReg(PPC::R1);
717   }
718 
719   // Grow the stack and update the stack pointer link, then
720   // determine the address of new allocated space.
721   if (LP64) {
722     BuildMI(MBB, II, TII.get(PPC::STDUX))
723       .addReg(PPC::X0)
724       .addReg(PPC::X1)
725       .addReg(MI.getOperand(1).getReg());
726     BuildMI(MBB, II, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
727       .addReg(PPC::X1)
728       .addImm(maxCallFrameSize);
729   } else {
730     BuildMI(MBB, II, TII.get(PPC::STWUX))
731       .addReg(PPC::R0)
732       .addReg(PPC::R1)
733       .addReg(MI.getOperand(1).getReg());
734     BuildMI(MBB, II, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
735       .addReg(PPC::R1)
736       .addImm(maxCallFrameSize);
737   }
738 
739   // Discard the DYNALLOC instruction.
740   MBB.erase(II);
741 }
742 
743 void PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
744                                           int SPAdj, RegScavenger *RS) const {
745   assert(SPAdj == 0 && "Unexpected");
746 
747   // Get the instruction.
748   MachineInstr &MI = *II;
749   // Get the instruction's basic block.
750   MachineBasicBlock &MBB = *MI.getParent();
751   // Get the basic block's function.
752   MachineFunction &MF = *MBB.getParent();
753   // Get the frame info.
754   MachineFrameInfo *MFI = MF.getFrameInfo();
755 
756   // Find out which operand is the frame index.
757   unsigned FIOperandNo = 0;
758   while (!MI.getOperand(FIOperandNo).isFrameIndex()) {
759     ++FIOperandNo;
760     assert(FIOperandNo != MI.getNumOperands() &&
761            "Instr doesn't have FrameIndex operand!");
762   }
763   // Take into account whether it's an add or mem instruction
764   unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
765   if (MI.getOpcode() == TargetInstrInfo::INLINEASM)
766     OffsetOperandNo = FIOperandNo-1;
767 
768   // Get the frame index.
769   int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
770 
771   // Get the frame pointer save index.  Users of this index are primarily
772   // DYNALLOC instructions.
773   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
774   int FPSI = FI->getFramePointerSaveIndex();
775   // Get the instruction opcode.
776   unsigned OpC = MI.getOpcode();
777 
778   // Special case for dynamic alloca.
779   if (FPSI && FrameIndex == FPSI &&
780       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
781     lowerDynamicAlloc(II);
782     return;
783   }
784 
785   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
786   MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
787                                               false);
788 
789   // Figure out if the offset in the instruction is shifted right two bits. This
790   // is true for instructions like "STD", which the machine implicitly adds two
791   // low zeros to.
792   bool isIXAddr = false;
793   switch (OpC) {
794   case PPC::LWA:
795   case PPC::LD:
796   case PPC::STD:
797   case PPC::STD_32:
798     isIXAddr = true;
799     break;
800   }
801 
802   // Now add the frame object offset to the offset from r1.
803   int Offset = MFI->getObjectOffset(FrameIndex);
804   if (!isIXAddr)
805     Offset += MI.getOperand(OffsetOperandNo).getImm();
806   else
807     Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
808 
809   // If we're not using a Frame Pointer that has been set to the value of the
810   // SP before having the stack size subtracted from it, then add the stack size
811   // to Offset to get the correct offset.
812   Offset += MFI->getStackSize();
813 
814   // If we can, encode the offset directly into the instruction.  If this is a
815   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
816   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
817   // clear can be encoded.  This is extremely uncommon, because normally you
818   // only "std" to a stack slot that is at least 4-byte aligned, but it can
819   // happen in invalid code.
820   if (isInt16(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
821     if (isIXAddr)
822       Offset >>= 2;    // The actual encoded value has the low two bits zero.
823     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
824     return;
825   }
826 
827   // Insert a set of r0 with the full offset value before the ld, st, or add
828   BuildMI(MBB, II, TII.get(PPC::LIS), PPC::R0).addImm(Offset >> 16);
829   BuildMI(MBB, II, TII.get(PPC::ORI), PPC::R0).addReg(PPC::R0).addImm(Offset);
830 
831   // Convert into indexed form of the instruction
832   // sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
833   // addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
834   unsigned OperandBase;
835   if (OpC != TargetInstrInfo::INLINEASM) {
836     assert(ImmToIdxMap.count(OpC) &&
837            "No indexed form of load or store available!");
838     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
839     MI.setInstrDescriptor(TII.get(NewOpcode));
840     OperandBase = 1;
841   } else {
842     OperandBase = OffsetOperandNo;
843   }
844 
845   unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
846   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
847   MI.getOperand(OperandBase+1).ChangeToRegister(PPC::R0, false);
848 }
849 
850 /// VRRegNo - Map from a numbered VR register to its enum value.
851 ///
852 static const unsigned short VRRegNo[] = {
853  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
854  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
855  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
856  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
857 };
858 
859 /// RemoveVRSaveCode - We have found that this function does not need any code
860 /// to manipulate the VRSAVE register, even though it uses vector registers.
861 /// This can happen when the only registers used are known to be live in or out
862 /// of the function.  Remove all of the VRSAVE related code from the function.
863 static void RemoveVRSaveCode(MachineInstr *MI) {
864   MachineBasicBlock *Entry = MI->getParent();
865   MachineFunction *MF = Entry->getParent();
866 
867   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
868   MachineBasicBlock::iterator MBBI = MI;
869   ++MBBI;
870   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
871   MBBI->eraseFromParent();
872 
873   bool RemovedAllMTVRSAVEs = true;
874   // See if we can find and remove the MTVRSAVE instruction from all of the
875   // epilog blocks.
876   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
877   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
878     // If last instruction is a return instruction, add an epilogue
879     if (!I->empty() && TII.isReturn(I->back().getOpcode())) {
880       bool FoundIt = false;
881       for (MBBI = I->end(); MBBI != I->begin(); ) {
882         --MBBI;
883         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
884           MBBI->eraseFromParent();  // remove it.
885           FoundIt = true;
886           break;
887         }
888       }
889       RemovedAllMTVRSAVEs &= FoundIt;
890     }
891   }
892 
893   // If we found and removed all MTVRSAVE instructions, remove the read of
894   // VRSAVE as well.
895   if (RemovedAllMTVRSAVEs) {
896     MBBI = MI;
897     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
898     --MBBI;
899     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
900     MBBI->eraseFromParent();
901   }
902 
903   // Finally, nuke the UPDATE_VRSAVE.
904   MI->eraseFromParent();
905 }
906 
907 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
908 // instruction selector.  Based on the vector registers that have been used,
909 // transform this into the appropriate ORI instruction.
910 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
911   MachineFunction *MF = MI->getParent()->getParent();
912 
913   unsigned UsedRegMask = 0;
914   for (unsigned i = 0; i != 32; ++i)
915     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
916       UsedRegMask |= 1 << (31-i);
917 
918   // Live in and live out values already must be in the mask, so don't bother
919   // marking them.
920   for (MachineRegisterInfo::livein_iterator
921        I = MF->getRegInfo().livein_begin(),
922        E = MF->getRegInfo().livein_end(); I != E; ++I) {
923     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first);
924     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
925       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
926   }
927   for (MachineRegisterInfo::liveout_iterator
928        I = MF->getRegInfo().liveout_begin(),
929        E = MF->getRegInfo().liveout_end(); I != E; ++I) {
930     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I);
931     if (VRRegNo[RegNo] == *I)              // If this really is a vector reg.
932       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
933   }
934 
935   unsigned SrcReg = MI->getOperand(1).getReg();
936   unsigned DstReg = MI->getOperand(0).getReg();
937   // If no registers are used, turn this into a copy.
938   if (UsedRegMask == 0) {
939     // Remove all VRSAVE code.
940     RemoveVRSaveCode(MI);
941     return;
942   } else if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
943     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
944         .addReg(SrcReg).addImm(UsedRegMask);
945   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
946     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
947         .addReg(SrcReg).addImm(UsedRegMask >> 16);
948   } else {
949     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
950        .addReg(SrcReg).addImm(UsedRegMask >> 16);
951     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
952       .addReg(DstReg).addImm(UsedRegMask & 0xFFFF);
953   }
954 
955   // Remove the old UPDATE_VRSAVE instruction.
956   MI->eraseFromParent();
957 }
958 
959 /// determineFrameLayout - Determine the size of the frame and maximum call
960 /// frame size.
961 void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const {
962   MachineFrameInfo *MFI = MF.getFrameInfo();
963 
964   // Get the number of bytes to allocate from the FrameInfo
965   unsigned FrameSize = MFI->getStackSize();
966 
967   // Get the alignments provided by the target, and the maximum alignment
968   // (if any) of the fixed frame objects.
969   unsigned MaxAlign = MFI->getMaxAlignment();
970   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
971   unsigned AlignMask = TargetAlign - 1;  //
972 
973   // If we are a leaf function, and use up to 224 bytes of stack space,
974   // don't have a frame pointer, calls, or dynamic alloca then we do not need
975   // to adjust the stack pointer (we fit in the Red Zone).
976   if (FrameSize <= 224 &&             // Fits in red zone.
977       !MFI->hasVarSizedObjects() &&   // No dynamic alloca.
978       !MFI->hasCalls() &&             // No calls.
979       MaxAlign <= TargetAlign) {      // No special alignment.
980     // No need for frame
981     MFI->setStackSize(0);
982     return;
983   }
984 
985   // Get the maximum call frame size of all the calls.
986   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
987 
988   // Maximum call frame needs to be at least big enough for linkage and 8 args.
989   unsigned minCallFrameSize =
990     PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(),
991                                       Subtarget.isMachoABI());
992   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
993 
994   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
995   // that allocations will be aligned.
996   if (MFI->hasVarSizedObjects())
997     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
998 
999   // Update maximum call frame size.
1000   MFI->setMaxCallFrameSize(maxCallFrameSize);
1001 
1002   // Include call frame size in total.
1003   FrameSize += maxCallFrameSize;
1004 
1005   // Make sure the frame is aligned.
1006   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
1007 
1008   // Update frame info.
1009   MFI->setStackSize(FrameSize);
1010 }
1011 
1012 void PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1013                                                            RegScavenger *RS)
1014   const {
1015   //  Save and clear the LR state.
1016   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1017   unsigned LR = getRARegister();
1018   FI->setUsesLR(MF.getRegInfo().isPhysRegUsed(LR));
1019   MF.getRegInfo().setPhysRegUnused(LR);
1020 
1021   //  Save R31 if necessary
1022   int FPSI = FI->getFramePointerSaveIndex();
1023   bool IsPPC64 = Subtarget.isPPC64();
1024   bool IsELF32_ABI = Subtarget.isELF32_ABI();
1025   bool IsMachoABI  = Subtarget.isMachoABI();
1026   const MachineFrameInfo *MFI = MF.getFrameInfo();
1027 
1028   // If the frame pointer save index hasn't been defined yet.
1029   if (!FPSI && (NoFramePointerElim || MFI->hasVarSizedObjects()) &&
1030       IsELF32_ABI) {
1031     // Find out what the fix offset of the frame pointer save area.
1032     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64,
1033                                                            IsMachoABI);
1034     // Allocate the frame index for frame pointer save area.
1035     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
1036     // Save the result.
1037     FI->setFramePointerSaveIndex(FPSI);
1038   }
1039 
1040 }
1041 
1042 void PPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
1043   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
1044   MachineBasicBlock::iterator MBBI = MBB.begin();
1045   MachineFrameInfo *MFI = MF.getFrameInfo();
1046   MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
1047 
1048   // Prepare for frame info.
1049   unsigned FrameLabelId = 0;
1050 
1051   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
1052   // process it.
1053   for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
1054     if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
1055       HandleVRSaveUpdate(MBBI, TII);
1056       break;
1057     }
1058   }
1059 
1060   // Move MBBI back to the beginning of the function.
1061   MBBI = MBB.begin();
1062 
1063   // Work out frame sizes.
1064   determineFrameLayout(MF);
1065   unsigned FrameSize = MFI->getStackSize();
1066 
1067   int NegFrameSize = -FrameSize;
1068 
1069   // Get processor type.
1070   bool IsPPC64 = Subtarget.isPPC64();
1071   // Get operating system
1072   bool IsMachoABI = Subtarget.isMachoABI();
1073   // Check if the link register (LR) has been used.
1074   bool UsesLR = MustSaveLR(MF);
1075   // Do we have a frame pointer for this function?
1076   bool HasFP = hasFP(MF) && FrameSize;
1077 
1078   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
1079   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
1080 
1081   if (IsPPC64) {
1082     if (UsesLR)
1083       BuildMI(MBB, MBBI, TII.get(PPC::MFLR8), PPC::X0);
1084 
1085     if (HasFP)
1086       BuildMI(MBB, MBBI, TII.get(PPC::STD))
1087          .addReg(PPC::X31).addImm(FPOffset/4).addReg(PPC::X1);
1088 
1089     if (UsesLR)
1090       BuildMI(MBB, MBBI, TII.get(PPC::STD))
1091          .addReg(PPC::X0).addImm(LROffset/4).addReg(PPC::X1);
1092   } else {
1093     if (UsesLR)
1094       BuildMI(MBB, MBBI, TII.get(PPC::MFLR), PPC::R0);
1095 
1096     if (HasFP)
1097       BuildMI(MBB, MBBI, TII.get(PPC::STW))
1098         .addReg(PPC::R31).addImm(FPOffset).addReg(PPC::R1);
1099 
1100     if (UsesLR)
1101       BuildMI(MBB, MBBI, TII.get(PPC::STW))
1102         .addReg(PPC::R0).addImm(LROffset).addReg(PPC::R1);
1103   }
1104 
1105   // Skip if a leaf routine.
1106   if (!FrameSize) return;
1107 
1108   // Get stack alignments.
1109   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1110   unsigned MaxAlign = MFI->getMaxAlignment();
1111 
1112   if (MMI && MMI->needsFrameInfo()) {
1113     // Mark effective beginning of when frame pointer becomes valid.
1114     FrameLabelId = MMI->NextLabelID();
1115     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(FrameLabelId);
1116   }
1117 
1118   // Adjust stack pointer: r1 += NegFrameSize.
1119   // If there is a preferred stack alignment, align R1 now
1120   if (!IsPPC64) {
1121     // PPC32.
1122     if (MaxAlign > TargetAlign) {
1123       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1124       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1125       BuildMI(MBB, MBBI, TII.get(PPC::RLWINM), PPC::R0)
1126         .addReg(PPC::R1).addImm(0).addImm(32-Log2_32(MaxAlign)).addImm(31);
1127       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC) ,PPC::R0).addReg(PPC::R0)
1128         .addImm(NegFrameSize);
1129       BuildMI(MBB, MBBI, TII.get(PPC::STWUX))
1130         .addReg(PPC::R1).addReg(PPC::R1).addReg(PPC::R0);
1131     } else if (isInt16(NegFrameSize)) {
1132       BuildMI(MBB, MBBI, TII.get(PPC::STWU),
1133               PPC::R1).addReg(PPC::R1).addImm(NegFrameSize).addReg(PPC::R1);
1134     } else {
1135       BuildMI(MBB, MBBI, TII.get(PPC::LIS), PPC::R0).addImm(NegFrameSize >> 16);
1136       BuildMI(MBB, MBBI, TII.get(PPC::ORI), PPC::R0).addReg(PPC::R0)
1137         .addImm(NegFrameSize & 0xFFFF);
1138       BuildMI(MBB, MBBI, TII.get(PPC::STWUX)).addReg(PPC::R1).addReg(PPC::R1)
1139         .addReg(PPC::R0);
1140     }
1141   } else {    // PPC64.
1142     if (MaxAlign > TargetAlign) {
1143       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1144       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1145       BuildMI(MBB, MBBI, TII.get(PPC::RLDICL), PPC::X0)
1146         .addReg(PPC::X1).addImm(0).addImm(64-Log2_32(MaxAlign));
1147       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC8), PPC::X0).addReg(PPC::X0)
1148         .addImm(NegFrameSize);
1149       BuildMI(MBB, MBBI, TII.get(PPC::STDUX))
1150         .addReg(PPC::X1).addReg(PPC::X1).addReg(PPC::X0);
1151     } else if (isInt16(NegFrameSize)) {
1152       BuildMI(MBB, MBBI, TII.get(PPC::STDU), PPC::X1)
1153              .addReg(PPC::X1).addImm(NegFrameSize/4).addReg(PPC::X1);
1154     } else {
1155       BuildMI(MBB, MBBI, TII.get(PPC::LIS8), PPC::X0).addImm(NegFrameSize >>16);
1156       BuildMI(MBB, MBBI, TII.get(PPC::ORI8), PPC::X0).addReg(PPC::X0)
1157         .addImm(NegFrameSize & 0xFFFF);
1158       BuildMI(MBB, MBBI, TII.get(PPC::STDUX)).addReg(PPC::X1).addReg(PPC::X1)
1159         .addReg(PPC::X0);
1160     }
1161   }
1162 
1163   if (MMI && MMI->needsFrameInfo()) {
1164     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
1165 
1166     if (NegFrameSize) {
1167       // Show update of SP.
1168       MachineLocation SPDst(MachineLocation::VirtualFP);
1169       MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
1170       Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
1171     } else {
1172       MachineLocation SP(IsPPC64 ? PPC::X31 : PPC::R31);
1173       Moves.push_back(MachineMove(FrameLabelId, SP, SP));
1174     }
1175 
1176     if (HasFP) {
1177       MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
1178       MachineLocation FPSrc(IsPPC64 ? PPC::X31 : PPC::R31);
1179       Moves.push_back(MachineMove(FrameLabelId, FPDst, FPSrc));
1180     }
1181 
1182     // Add callee saved registers to move list.
1183     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1184     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
1185       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
1186       unsigned Reg = CSI[I].getReg();
1187       if (Reg == PPC::LR || Reg == PPC::LR8) continue;
1188       MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
1189       MachineLocation CSSrc(Reg);
1190       Moves.push_back(MachineMove(FrameLabelId, CSDst, CSSrc));
1191     }
1192 
1193     MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
1194     MachineLocation LRSrc(IsPPC64 ? PPC::LR8 : PPC::LR);
1195     Moves.push_back(MachineMove(FrameLabelId, LRDst, LRSrc));
1196 
1197     // Mark effective beginning of when frame pointer is ready.
1198     unsigned ReadyLabelId = MMI->NextLabelID();
1199     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(ReadyLabelId);
1200 
1201     MachineLocation FPDst(HasFP ? (IsPPC64 ? PPC::X31 : PPC::R31) :
1202                                   (IsPPC64 ? PPC::X1 : PPC::R1));
1203     MachineLocation FPSrc(MachineLocation::VirtualFP);
1204     Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
1205   }
1206 
1207   // If there is a frame pointer, copy R1 into R31
1208   if (HasFP) {
1209     if (!IsPPC64) {
1210       BuildMI(MBB, MBBI, TII.get(PPC::OR), PPC::R31).addReg(PPC::R1)
1211         .addReg(PPC::R1);
1212     } else {
1213       BuildMI(MBB, MBBI, TII.get(PPC::OR8), PPC::X31).addReg(PPC::X1)
1214         .addReg(PPC::X1);
1215     }
1216   }
1217 }
1218 
1219 void PPCRegisterInfo::emitEpilogue(MachineFunction &MF,
1220                                    MachineBasicBlock &MBB) const {
1221   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1222   assert(MBBI->getOpcode() == PPC::BLR &&
1223          "Can only insert epilog into returning blocks");
1224 
1225   // Get alignment info so we know how to restore r1
1226   const MachineFrameInfo *MFI = MF.getFrameInfo();
1227   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1228   unsigned MaxAlign = MFI->getMaxAlignment();
1229 
1230   // Get the number of bytes allocated from the FrameInfo.
1231   unsigned FrameSize = MFI->getStackSize();
1232 
1233   // Get processor type.
1234   bool IsPPC64 = Subtarget.isPPC64();
1235   // Get operating system
1236   bool IsMachoABI = Subtarget.isMachoABI();
1237   // Check if the link register (LR) has been used.
1238   bool UsesLR = MustSaveLR(MF);
1239   // Do we have a frame pointer for this function?
1240   bool HasFP = hasFP(MF) && FrameSize;
1241 
1242   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
1243   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
1244 
1245   if (FrameSize) {
1246     // The loaded (or persistent) stack pointer value is offset by the 'stwu'
1247     // on entry to the function.  Add this offset back now.
1248     if (!Subtarget.isPPC64()) {
1249       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1250             !MFI->hasVarSizedObjects()) {
1251           BuildMI(MBB, MBBI, TII.get(PPC::ADDI), PPC::R1)
1252               .addReg(PPC::R1).addImm(FrameSize);
1253       } else {
1254         BuildMI(MBB, MBBI, TII.get(PPC::LWZ),PPC::R1).addImm(0).addReg(PPC::R1);
1255       }
1256     } else {
1257       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1258             !MFI->hasVarSizedObjects()) {
1259         BuildMI(MBB, MBBI, TII.get(PPC::ADDI8), PPC::X1)
1260            .addReg(PPC::X1).addImm(FrameSize);
1261       } else {
1262         BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X1).addImm(0).addReg(PPC::X1);
1263       }
1264     }
1265   }
1266 
1267   if (IsPPC64) {
1268     if (UsesLR)
1269       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X0)
1270         .addImm(LROffset/4).addReg(PPC::X1);
1271 
1272     if (HasFP)
1273       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X31)
1274         .addImm(FPOffset/4).addReg(PPC::X1);
1275 
1276     if (UsesLR)
1277       BuildMI(MBB, MBBI, TII.get(PPC::MTLR8)).addReg(PPC::X0);
1278   } else {
1279     if (UsesLR)
1280       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R0)
1281           .addImm(LROffset).addReg(PPC::R1);
1282 
1283     if (HasFP)
1284       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R31)
1285           .addImm(FPOffset).addReg(PPC::R1);
1286 
1287     if (UsesLR)
1288       BuildMI(MBB, MBBI, TII.get(PPC::MTLR)).addReg(PPC::R0);
1289   }
1290 }
1291 
1292 unsigned PPCRegisterInfo::getRARegister() const {
1293   return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
1294 }
1295 
1296 unsigned PPCRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1297   if (!Subtarget.isPPC64())
1298     return hasFP(MF) ? PPC::R31 : PPC::R1;
1299   else
1300     return hasFP(MF) ? PPC::X31 : PPC::X1;
1301 }
1302 
1303 void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
1304                                                                          const {
1305   // Initial state of the frame pointer is R1.
1306   MachineLocation Dst(MachineLocation::VirtualFP);
1307   MachineLocation Src(PPC::R1, 0);
1308   Moves.push_back(MachineMove(0, Dst, Src));
1309 }
1310 
1311 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
1312   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
1313 }
1314 
1315 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
1316   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
1317 }
1318 
1319 int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1320   // FIXME: Most probably dwarf numbers differs for Linux and Darwin
1321   return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1322 }
1323 
1324 #include "PPCGenRegisterInfo.inc"
1325 
1326