xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision bd5429ef38dec52c3cb25fdd0d56912559dc0104)
1 //===-- PPCRegisterInfo.cpp - PowerPC Register Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the PowerPC implementation of the TargetRegisterInfo
10 // class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCRegisterInfo.h"
15 #include "PPC.h"
16 #include "PPCFrameLowering.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.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/TargetFrameLowering.h"
31 #include "llvm/CodeGen/TargetInstrInfo.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include <cstdlib>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "reginfo"
48 
49 #define GET_REGINFO_TARGET_DESC
50 #include "PPCGenRegisterInfo.inc"
51 
52 STATISTIC(InflateGPRC, "Number of gprc inputs for getLargestLegalClass");
53 STATISTIC(InflateGP8RC, "Number of g8rc inputs for getLargestLegalClass");
54 
55 static cl::opt<bool>
56 EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
57          cl::desc("Enable use of a base pointer for complex stack frames"));
58 
59 static cl::opt<bool>
60 AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
61          cl::desc("Force the use of a base pointer in every function"));
62 
63 static cl::opt<bool>
64 EnableGPRToVecSpills("ppc-enable-gpr-to-vsr-spills", cl::Hidden, cl::init(false),
65          cl::desc("Enable spills from gpr to vsr rather than stack"));
66 
67 static cl::opt<bool>
68 StackPtrConst("ppc-stack-ptr-caller-preserved",
69                 cl::desc("Consider R1 caller preserved so stack saves of "
70                          "caller preserved registers can be LICM candidates"),
71                 cl::init(true), cl::Hidden);
72 
73 static unsigned offsetMinAlignForOpcode(unsigned OpC);
74 
75 PPCRegisterInfo::PPCRegisterInfo(const PPCTargetMachine &TM)
76   : PPCGenRegisterInfo(TM.isPPC64() ? PPC::LR8 : PPC::LR,
77                        TM.isPPC64() ? 0 : 1,
78                        TM.isPPC64() ? 0 : 1),
79     TM(TM) {
80   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
81   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
82   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
83   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
84   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
85   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
86   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
87   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
88   ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
89 
90   // 64-bit
91   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
92   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
93   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
94   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
95   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
96 
97   // VSX
98   ImmToIdxMap[PPC::DFLOADf32] = PPC::LXSSPX;
99   ImmToIdxMap[PPC::DFLOADf64] = PPC::LXSDX;
100   ImmToIdxMap[PPC::SPILLTOVSR_LD] = PPC::SPILLTOVSR_LDX;
101   ImmToIdxMap[PPC::SPILLTOVSR_ST] = PPC::SPILLTOVSR_STX;
102   ImmToIdxMap[PPC::DFSTOREf32] = PPC::STXSSPX;
103   ImmToIdxMap[PPC::DFSTOREf64] = PPC::STXSDX;
104   ImmToIdxMap[PPC::LXV] = PPC::LXVX;
105   ImmToIdxMap[PPC::LXSD] = PPC::LXSDX;
106   ImmToIdxMap[PPC::LXSSP] = PPC::LXSSPX;
107   ImmToIdxMap[PPC::STXV] = PPC::STXVX;
108   ImmToIdxMap[PPC::STXSD] = PPC::STXSDX;
109   ImmToIdxMap[PPC::STXSSP] = PPC::STXSSPX;
110 
111   // SPE
112   ImmToIdxMap[PPC::EVLDD] = PPC::EVLDDX;
113   ImmToIdxMap[PPC::EVSTDD] = PPC::EVSTDDX;
114   ImmToIdxMap[PPC::SPESTW] = PPC::SPESTWX;
115   ImmToIdxMap[PPC::SPELWZ] = PPC::SPELWZX;
116 }
117 
118 /// getPointerRegClass - Return the register class to use to hold pointers.
119 /// This is used for addressing modes.
120 const TargetRegisterClass *
121 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
122                                                                        const {
123   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
124   // when it checks for ZERO folding.
125   if (Kind == 1) {
126     if (TM.isPPC64())
127       return &PPC::G8RC_NOX0RegClass;
128     return &PPC::GPRC_NOR0RegClass;
129   }
130 
131   if (TM.isPPC64())
132     return &PPC::G8RCRegClass;
133   return &PPC::GPRCRegClass;
134 }
135 
136 const MCPhysReg*
137 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
138   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
139   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg) {
140     if (Subtarget.hasVSX())
141       return CSR_64_AllRegs_VSX_SaveList;
142     if (Subtarget.hasAltivec())
143       return CSR_64_AllRegs_Altivec_SaveList;
144     return CSR_64_AllRegs_SaveList;
145   }
146 
147   if (Subtarget.isDarwinABI())
148     return TM.isPPC64()
149                ? (Subtarget.hasAltivec() ? CSR_Darwin64_Altivec_SaveList
150                                          : CSR_Darwin64_SaveList)
151                : (Subtarget.hasAltivec() ? CSR_Darwin32_Altivec_SaveList
152                                          : CSR_Darwin32_SaveList);
153 
154   if (TM.isPPC64() && MF->getInfo<PPCFunctionInfo>()->isSplitCSR())
155     return CSR_SRV464_TLS_PE_SaveList;
156 
157   if (Subtarget.hasSPE())
158     return CSR_SVR432_SPE_SaveList;
159 
160   // On PPC64, we might need to save r2 (but only if it is not reserved).
161   bool SaveR2 = MF->getRegInfo().isAllocatable(PPC::X2);
162 
163   if (MF->getFunction().getCallingConv() == CallingConv::Cold) {
164     return TM.isPPC64()
165                ? (Subtarget.hasAltivec()
166                       ? (SaveR2 ? CSR_SVR64_ColdCC_R2_Altivec_SaveList
167                                 : CSR_SVR64_ColdCC_Altivec_SaveList)
168                       : (SaveR2 ? CSR_SVR64_ColdCC_R2_SaveList
169                                 : CSR_SVR64_ColdCC_SaveList))
170                : (Subtarget.hasAltivec() ? CSR_SVR32_ColdCC_Altivec_SaveList
171                                          : CSR_SVR32_ColdCC_SaveList);
172   }
173 
174   return TM.isPPC64()
175              ? (Subtarget.hasAltivec()
176                     ? (SaveR2 ? CSR_SVR464_R2_Altivec_SaveList
177                               : CSR_SVR464_Altivec_SaveList)
178                     : (SaveR2 ? CSR_SVR464_R2_SaveList : CSR_SVR464_SaveList))
179              : (Subtarget.hasAltivec() ? CSR_SVR432_Altivec_SaveList
180                                        : CSR_SVR432_SaveList);
181 }
182 
183 const MCPhysReg *
184 PPCRegisterInfo::getCalleeSavedRegsViaCopy(const MachineFunction *MF) const {
185   assert(MF && "Invalid MachineFunction pointer.");
186   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
187   if (Subtarget.isDarwinABI())
188     return nullptr;
189   if (!TM.isPPC64())
190     return nullptr;
191   if (MF->getFunction().getCallingConv() != CallingConv::CXX_FAST_TLS)
192     return nullptr;
193   if (!MF->getInfo<PPCFunctionInfo>()->isSplitCSR())
194     return nullptr;
195 
196   // On PPC64, we might need to save r2 (but only if it is not reserved).
197   bool SaveR2 = !getReservedRegs(*MF).test(PPC::X2);
198   if (Subtarget.hasAltivec())
199     return SaveR2
200       ? CSR_SVR464_R2_Altivec_ViaCopy_SaveList
201       : CSR_SVR464_Altivec_ViaCopy_SaveList;
202   else
203     return SaveR2
204       ? CSR_SVR464_R2_ViaCopy_SaveList
205       : CSR_SVR464_ViaCopy_SaveList;
206 }
207 
208 const uint32_t *
209 PPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
210                                       CallingConv::ID CC) const {
211   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
212   if (CC == CallingConv::AnyReg) {
213     if (Subtarget.hasVSX())
214       return CSR_64_AllRegs_VSX_RegMask;
215     if (Subtarget.hasAltivec())
216       return CSR_64_AllRegs_Altivec_RegMask;
217     return CSR_64_AllRegs_RegMask;
218   }
219 
220   if (Subtarget.isDarwinABI())
221     return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_Darwin64_Altivec_RegMask
222                                                   : CSR_Darwin64_RegMask)
223                         : (Subtarget.hasAltivec() ? CSR_Darwin32_Altivec_RegMask
224                                                   : CSR_Darwin32_RegMask);
225 
226   if (CC == CallingConv::Cold) {
227     return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_SVR64_ColdCC_Altivec_RegMask
228                                                   : CSR_SVR64_ColdCC_RegMask)
229                         : (Subtarget.hasAltivec() ? CSR_SVR32_ColdCC_Altivec_RegMask
230                                                   : CSR_SVR32_ColdCC_RegMask);
231   }
232 
233   return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_SVR464_Altivec_RegMask
234                                                 : CSR_SVR464_RegMask)
235                       : (Subtarget.hasAltivec() ? CSR_SVR432_Altivec_RegMask
236                                                 : CSR_SVR432_RegMask);
237 }
238 
239 const uint32_t*
240 PPCRegisterInfo::getNoPreservedMask() const {
241   return CSR_NoRegs_RegMask;
242 }
243 
244 void PPCRegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const {
245   for (unsigned PseudoReg : {PPC::ZERO, PPC::ZERO8, PPC::RM})
246     Mask[PseudoReg / 32] &= ~(1u << (PseudoReg % 32));
247 }
248 
249 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
250   BitVector Reserved(getNumRegs());
251   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
252   const PPCFrameLowering *TFI = getFrameLowering(MF);
253 
254   // The ZERO register is not really a register, but the representation of r0
255   // when used in instructions that treat r0 as the constant 0.
256   markSuperRegs(Reserved, PPC::ZERO);
257 
258   // The FP register is also not really a register, but is the representation
259   // of the frame pointer register used by ISD::FRAMEADDR.
260   markSuperRegs(Reserved, PPC::FP);
261 
262   // The BP register is also not really a register, but is the representation
263   // of the base pointer register used by setjmp.
264   markSuperRegs(Reserved, PPC::BP);
265 
266   // The counter registers must be reserved so that counter-based loops can
267   // be correctly formed (and the mtctr instructions are not DCE'd).
268   markSuperRegs(Reserved, PPC::CTR);
269   markSuperRegs(Reserved, PPC::CTR8);
270 
271   markSuperRegs(Reserved, PPC::R1);
272   markSuperRegs(Reserved, PPC::LR);
273   markSuperRegs(Reserved, PPC::LR8);
274   markSuperRegs(Reserved, PPC::RM);
275 
276   if (!Subtarget.isDarwinABI() || !Subtarget.hasAltivec())
277     markSuperRegs(Reserved, PPC::VRSAVE);
278 
279   // The SVR4 ABI reserves r2 and r13
280   if (Subtarget.isSVR4ABI()) {
281     // We only reserve r2 if we need to use the TOC pointer. If we have no
282     // explicit uses of the TOC pointer (meaning we're a leaf function with
283     // no constant-pool loads, etc.) and we have no potential uses inside an
284     // inline asm block, then we can treat r2 has an ordinary callee-saved
285     // register.
286     const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
287     if (!TM.isPPC64() || FuncInfo->usesTOCBasePtr() || MF.hasInlineAsm())
288       markSuperRegs(Reserved, PPC::R2);  // System-reserved register
289     markSuperRegs(Reserved, PPC::R13); // Small Data Area pointer register
290   }
291 
292   // On PPC64, r13 is the thread pointer. Never allocate this register.
293   if (TM.isPPC64())
294     markSuperRegs(Reserved, PPC::R13);
295 
296   if (TFI->needsFP(MF))
297     markSuperRegs(Reserved, PPC::R31);
298 
299   bool IsPositionIndependent = TM.isPositionIndependent();
300   if (hasBasePointer(MF)) {
301     if (Subtarget.isSVR4ABI() && !TM.isPPC64() && IsPositionIndependent)
302       markSuperRegs(Reserved, PPC::R29);
303     else
304       markSuperRegs(Reserved, PPC::R30);
305   }
306 
307   if (Subtarget.isSVR4ABI() && !TM.isPPC64() && IsPositionIndependent)
308     markSuperRegs(Reserved, PPC::R30);
309 
310   // Reserve Altivec registers when Altivec is unavailable.
311   if (!Subtarget.hasAltivec())
312     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
313          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
314       markSuperRegs(Reserved, *I);
315 
316   assert(checkAllSuperRegsMarked(Reserved));
317   return Reserved;
318 }
319 
320 bool PPCRegisterInfo::requiresFrameIndexScavenging(const MachineFunction &MF) const {
321   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
322   const PPCInstrInfo *InstrInfo =  Subtarget.getInstrInfo();
323   const MachineFrameInfo &MFI = MF.getFrameInfo();
324   const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
325 
326   // If the callee saved info is invalid we have to default to true for safety.
327   if (!MFI.isCalleeSavedInfoValid())
328     return true;
329 
330   // We will require the use of X-Forms because the frame is larger than what
331   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
332   // If we need an X-Form then we need a register to store the address offset.
333   unsigned FrameSize = MFI.getStackSize();
334   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
335   if (FrameSize & ~0x7FFF)
336     return true;
337 
338   // The callee saved info is valid so it can be traversed.
339   // Checking for registers that need saving that do not have load or store
340   // forms where the address offset is an immediate.
341   for (unsigned i = 0; i < Info.size(); i++) {
342     int FrIdx = Info[i].getFrameIdx();
343     unsigned Reg = Info[i].getReg();
344 
345     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(Reg);
346     if (!MFI.isFixedObjectIndex(FrIdx)) {
347       // This is not a fixed object. If it requires alignment then we may still
348       // need to use the XForm.
349       if (offsetMinAlignForOpcode(Opcode) > 1)
350         return true;
351     }
352 
353     // This is eiher:
354     // 1) A fixed frame index object which we know are aligned so
355     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
356     // need to consider the alignement here.
357     // 2) A not fixed object but in that case we now know that the min required
358     // alignment is no more than 1 based on the previous check.
359     if (InstrInfo->isXFormMemOp(Opcode))
360       return true;
361   }
362   return false;
363 }
364 
365 bool PPCRegisterInfo::isCallerPreservedPhysReg(unsigned PhysReg,
366                                                const MachineFunction &MF) const {
367   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
368   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
369   const MachineFrameInfo &MFI = MF.getFrameInfo();
370   if (!TM.isPPC64())
371     return false;
372 
373   if (!Subtarget.isSVR4ABI())
374     return false;
375   if (PhysReg == PPC::X2)
376     // X2 is guaranteed to be preserved within a function if it is reserved.
377     // The reason it's reserved is that it's the TOC pointer (and the function
378     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
379     // with no TOC access), we can't claim that it is preserved.
380     return (getReservedRegs(MF).test(PPC::X2));
381   if (StackPtrConst && (PhysReg == PPC::X1) && !MFI.hasVarSizedObjects()
382       && !MFI.hasOpaqueSPAdjustment())
383     // The value of the stack pointer does not change within a function after
384     // the prologue and before the epilogue if there are no dynamic allocations
385     // and no inline asm which clobbers X1.
386     return true;
387   return false;
388 }
389 
390 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
391                                               MachineFunction &MF) const {
392   const PPCFrameLowering *TFI = getFrameLowering(MF);
393   const unsigned DefaultSafety = 1;
394 
395   switch (RC->getID()) {
396   default:
397     return 0;
398   case PPC::G8RC_NOX0RegClassID:
399   case PPC::GPRC_NOR0RegClassID:
400   case PPC::SPERCRegClassID:
401   case PPC::SPE4RCRegClassID:
402   case PPC::G8RCRegClassID:
403   case PPC::GPRCRegClassID: {
404     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
405     return 32 - FP - DefaultSafety;
406   }
407   case PPC::F8RCRegClassID:
408   case PPC::F4RCRegClassID:
409   case PPC::QFRCRegClassID:
410   case PPC::QSRCRegClassID:
411   case PPC::QBRCRegClassID:
412   case PPC::VRRCRegClassID:
413   case PPC::VFRCRegClassID:
414   case PPC::VSLRCRegClassID:
415     return 32 - DefaultSafety;
416   case PPC::VSRCRegClassID:
417   case PPC::VSFRCRegClassID:
418   case PPC::VSSRCRegClassID:
419     return 64 - DefaultSafety;
420   case PPC::CRRCRegClassID:
421     return 8 - DefaultSafety;
422   }
423 }
424 
425 const TargetRegisterClass *
426 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
427                                            const MachineFunction &MF) const {
428   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
429   if (Subtarget.hasVSX()) {
430     // With VSX, we can inflate various sub-register classes to the full VSX
431     // register set.
432 
433     // For Power9 we allow the user to enable GPR to vector spills.
434     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
435     // support to spill GPRC.
436     if (TM.isELFv2ABI()) {
437       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
438           RC == &PPC::G8RCRegClass) {
439         InflateGP8RC++;
440         return &PPC::SPILLTOVSRRCRegClass;
441       }
442       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
443         InflateGPRC++;
444     }
445     if (RC == &PPC::F8RCRegClass)
446       return &PPC::VSFRCRegClass;
447     else if (RC == &PPC::VRRCRegClass)
448       return &PPC::VSRCRegClass;
449     else if (RC == &PPC::F4RCRegClass && Subtarget.hasP8Vector())
450       return &PPC::VSSRCRegClass;
451   }
452 
453   return TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // Stack Frame Processing methods
458 //===----------------------------------------------------------------------===//
459 
460 /// lowerDynamicAlloc - Generate the code for allocating an object in the
461 /// current frame.  The sequence of code will be in the general form
462 ///
463 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
464 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
465 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
466 ///
467 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
468   // Get the instruction.
469   MachineInstr &MI = *II;
470   // Get the instruction's basic block.
471   MachineBasicBlock &MBB = *MI.getParent();
472   // Get the basic block's function.
473   MachineFunction &MF = *MBB.getParent();
474   // Get the frame info.
475   MachineFrameInfo &MFI = MF.getFrameInfo();
476   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
477   // Get the instruction info.
478   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
479   // Determine whether 64-bit pointers are used.
480   bool LP64 = TM.isPPC64();
481   DebugLoc dl = MI.getDebugLoc();
482 
483   // Get the maximum call stack size.
484   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
485   // Get the total frame size.
486   unsigned FrameSize = MFI.getStackSize();
487 
488   // Get stack alignments.
489   const PPCFrameLowering *TFI = getFrameLowering(MF);
490   unsigned TargetAlign = TFI->getStackAlignment();
491   unsigned MaxAlign = MFI.getMaxAlignment();
492   assert((maxCallFrameSize & (MaxAlign-1)) == 0 &&
493          "Maximum call-frame size not sufficiently aligned");
494 
495   // Determine the previous frame's address.  If FrameSize can't be
496   // represented as 16 bits or we need special alignment, then we load the
497   // previous frame's address from 0(SP).  Why not do an addis of the hi?
498   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
499   // Constructing the constant and adding would take 3 instructions.
500   // Fortunately, a frame greater than 32K is rare.
501   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
502   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
503   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
504 
505   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
506     if (LP64)
507       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), Reg)
508         .addReg(PPC::X31)
509         .addImm(FrameSize);
510     else
511       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
512         .addReg(PPC::R31)
513         .addImm(FrameSize);
514   } else if (LP64) {
515     BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
516       .addImm(0)
517       .addReg(PPC::X1);
518   } else {
519     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
520       .addImm(0)
521       .addReg(PPC::R1);
522   }
523 
524   bool KillNegSizeReg = MI.getOperand(1).isKill();
525   unsigned NegSizeReg = MI.getOperand(1).getReg();
526 
527   // Grow the stack and update the stack pointer link, then determine the
528   // address of new allocated space.
529   if (LP64) {
530     if (MaxAlign > TargetAlign) {
531       unsigned UnalNegSizeReg = NegSizeReg;
532       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
533 
534       // Unfortunately, there is no andi, only andi., and we can't insert that
535       // here because we might clobber cr0 while it is live.
536       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
537         .addImm(~(MaxAlign-1));
538 
539       unsigned NegSizeReg1 = NegSizeReg;
540       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
541       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
542         .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
543         .addReg(NegSizeReg1, RegState::Kill);
544       KillNegSizeReg = true;
545     }
546 
547     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
548       .addReg(Reg, RegState::Kill)
549       .addReg(PPC::X1)
550       .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
551     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
552       .addReg(PPC::X1)
553       .addImm(maxCallFrameSize);
554   } else {
555     if (MaxAlign > TargetAlign) {
556       unsigned UnalNegSizeReg = NegSizeReg;
557       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
558 
559       // Unfortunately, there is no andi, only andi., and we can't insert that
560       // here because we might clobber cr0 while it is live.
561       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
562         .addImm(~(MaxAlign-1));
563 
564       unsigned NegSizeReg1 = NegSizeReg;
565       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
566       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
567         .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
568         .addReg(NegSizeReg1, RegState::Kill);
569       KillNegSizeReg = true;
570     }
571 
572     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
573       .addReg(Reg, RegState::Kill)
574       .addReg(PPC::R1)
575       .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
576     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
577       .addReg(PPC::R1)
578       .addImm(maxCallFrameSize);
579   }
580 
581   // Discard the DYNALLOC instruction.
582   MBB.erase(II);
583 }
584 
585 void PPCRegisterInfo::lowerDynamicAreaOffset(
586     MachineBasicBlock::iterator II) const {
587   // Get the instruction.
588   MachineInstr &MI = *II;
589   // Get the instruction's basic block.
590   MachineBasicBlock &MBB = *MI.getParent();
591   // Get the basic block's function.
592   MachineFunction &MF = *MBB.getParent();
593   // Get the frame info.
594   MachineFrameInfo &MFI = MF.getFrameInfo();
595   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
596   // Get the instruction info.
597   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
598 
599   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
600   bool is64Bit = TM.isPPC64();
601   DebugLoc dl = MI.getDebugLoc();
602   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
603           MI.getOperand(0).getReg())
604       .addImm(maxCallFrameSize);
605   MBB.erase(II);
606 }
607 
608 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
609 /// reserving a whole register (R0), we scrounge for one here. This generates
610 /// code like this:
611 ///
612 ///   mfcr rA                  ; Move the conditional register into GPR rA.
613 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
614 ///   stw rA, FI               ; Store rA to the frame.
615 ///
616 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
617                                       unsigned FrameIndex) const {
618   // Get the instruction.
619   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
620   // Get the instruction's basic block.
621   MachineBasicBlock &MBB = *MI.getParent();
622   MachineFunction &MF = *MBB.getParent();
623   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
624   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
625   DebugLoc dl = MI.getDebugLoc();
626 
627   bool LP64 = TM.isPPC64();
628   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
629   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
630 
631   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
632   unsigned SrcReg = MI.getOperand(0).getReg();
633 
634   // We need to store the CR in the low 4-bits of the saved value. First, issue
635   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
636   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
637       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
638 
639   // If the saved register wasn't CR0, shift the bits left so that they are in
640   // CR0's slot.
641   if (SrcReg != PPC::CR0) {
642     unsigned Reg1 = Reg;
643     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
644 
645     // rlwinm rA, rA, ShiftBits, 0, 31.
646     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
647       .addReg(Reg1, RegState::Kill)
648       .addImm(getEncodingValue(SrcReg) * 4)
649       .addImm(0)
650       .addImm(31);
651   }
652 
653   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
654                     .addReg(Reg, RegState::Kill),
655                     FrameIndex);
656 
657   // Discard the pseudo instruction.
658   MBB.erase(II);
659 }
660 
661 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
662                                       unsigned FrameIndex) const {
663   // Get the instruction.
664   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
665   // Get the instruction's basic block.
666   MachineBasicBlock &MBB = *MI.getParent();
667   MachineFunction &MF = *MBB.getParent();
668   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
669   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
670   DebugLoc dl = MI.getDebugLoc();
671 
672   bool LP64 = TM.isPPC64();
673   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
674   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
675 
676   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
677   unsigned DestReg = MI.getOperand(0).getReg();
678   assert(MI.definesRegister(DestReg) &&
679     "RESTORE_CR does not define its destination");
680 
681   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
682                               Reg), FrameIndex);
683 
684   // If the reloaded register isn't CR0, shift the bits right so that they are
685   // in the right CR's slot.
686   if (DestReg != PPC::CR0) {
687     unsigned Reg1 = Reg;
688     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
689 
690     unsigned ShiftBits = getEncodingValue(DestReg)*4;
691     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
692     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
693              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
694              .addImm(31);
695   }
696 
697   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
698              .addReg(Reg, RegState::Kill);
699 
700   // Discard the pseudo instruction.
701   MBB.erase(II);
702 }
703 
704 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
705                                          unsigned FrameIndex) const {
706   // Get the instruction.
707   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
708   // Get the instruction's basic block.
709   MachineBasicBlock &MBB = *MI.getParent();
710   MachineFunction &MF = *MBB.getParent();
711   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
712   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
713   DebugLoc dl = MI.getDebugLoc();
714 
715   bool LP64 = TM.isPPC64();
716   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
717   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
718 
719   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
720   unsigned SrcReg = MI.getOperand(0).getReg();
721 
722   // We need to move the CR field that contains the CR bit we are spilling.
723   // The super register may not be explicitly defined (i.e. it can be defined
724   // by a CR-logical that only defines the subreg) so we state that the CR
725   // field is undef. Also, in order to preserve the kill flag on the CR bit,
726   // we add it as an implicit use.
727   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
728       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
729       .addReg(SrcReg,
730               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
731 
732   // If the saved register wasn't CR0LT, shift the bits left so that the bit to
733   // store is the first one. Mask all but that bit.
734   unsigned Reg1 = Reg;
735   Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
736 
737   // rlwinm rA, rA, ShiftBits, 0, 0.
738   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
739     .addReg(Reg1, RegState::Kill)
740     .addImm(getEncodingValue(SrcReg))
741     .addImm(0).addImm(0);
742 
743   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
744                     .addReg(Reg, RegState::Kill),
745                     FrameIndex);
746 
747   // Discard the pseudo instruction.
748   MBB.erase(II);
749 }
750 
751 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
752                                       unsigned FrameIndex) const {
753   // Get the instruction.
754   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
755   // Get the instruction's basic block.
756   MachineBasicBlock &MBB = *MI.getParent();
757   MachineFunction &MF = *MBB.getParent();
758   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
759   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
760   DebugLoc dl = MI.getDebugLoc();
761 
762   bool LP64 = TM.isPPC64();
763   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
764   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
765 
766   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
767   unsigned DestReg = MI.getOperand(0).getReg();
768   assert(MI.definesRegister(DestReg) &&
769     "RESTORE_CRBIT does not define its destination");
770 
771   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
772                               Reg), FrameIndex);
773 
774   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
775 
776   unsigned RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
777   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
778           .addReg(getCRFromCRBit(DestReg));
779 
780   unsigned ShiftBits = getEncodingValue(DestReg);
781   // rlwimi r11, r10, 32-ShiftBits, ..., ...
782   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
783       .addReg(RegO, RegState::Kill)
784       .addReg(Reg, RegState::Kill)
785       .addImm(ShiftBits ? 32 - ShiftBits : 0)
786       .addImm(ShiftBits)
787       .addImm(ShiftBits);
788 
789   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
790           getCRFromCRBit(DestReg))
791       .addReg(RegO, RegState::Kill)
792       // Make sure we have a use dependency all the way through this
793       // sequence of instructions. We can't have the other bits in the CR
794       // modified in between the mfocrf and the mtocrf.
795       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
796 
797   // Discard the pseudo instruction.
798   MBB.erase(II);
799 }
800 
801 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
802                                           unsigned FrameIndex) const {
803   // Get the instruction.
804   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
805   // Get the instruction's basic block.
806   MachineBasicBlock &MBB = *MI.getParent();
807   MachineFunction &MF = *MBB.getParent();
808   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
809   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
810   DebugLoc dl = MI.getDebugLoc();
811 
812   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
813   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
814   unsigned SrcReg = MI.getOperand(0).getReg();
815 
816   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
817       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
818 
819   addFrameReference(
820       BuildMI(MBB, II, dl, TII.get(PPC::STW)).addReg(Reg, RegState::Kill),
821       FrameIndex);
822 
823   // Discard the pseudo instruction.
824   MBB.erase(II);
825 }
826 
827 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
828                                          unsigned FrameIndex) const {
829   // Get the instruction.
830   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
831   // Get the instruction's basic block.
832   MachineBasicBlock &MBB = *MI.getParent();
833   MachineFunction &MF = *MBB.getParent();
834   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
835   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
836   DebugLoc dl = MI.getDebugLoc();
837 
838   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
839   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
840   unsigned DestReg = MI.getOperand(0).getReg();
841   assert(MI.definesRegister(DestReg) &&
842     "RESTORE_VRSAVE does not define its destination");
843 
844   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
845                               Reg), FrameIndex);
846 
847   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
848              .addReg(Reg, RegState::Kill);
849 
850   // Discard the pseudo instruction.
851   MBB.erase(II);
852 }
853 
854 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
855                                            unsigned Reg, int &FrameIdx) const {
856   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
857   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
858   // ABI, return true to prevent allocating an additional frame slot.
859   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
860   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
861   // previously created the stack slot if needed, so return its FrameIdx.
862   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
863     if (TM.isPPC64())
864       FrameIdx = 0;
865     else {
866       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
867       FrameIdx = FI->getCRSpillFrameIndex();
868     }
869     return true;
870   }
871   return false;
872 }
873 
874 // If the offset must be a multiple of some value, return what that value is.
875 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
876   switch (OpC) {
877   default:
878     return 1;
879   case PPC::LWA:
880   case PPC::LWA_32:
881   case PPC::LD:
882   case PPC::LDU:
883   case PPC::STD:
884   case PPC::STDU:
885   case PPC::DFLOADf32:
886   case PPC::DFLOADf64:
887   case PPC::DFSTOREf32:
888   case PPC::DFSTOREf64:
889   case PPC::LXSD:
890   case PPC::LXSSP:
891   case PPC::STXSD:
892   case PPC::STXSSP:
893     return 4;
894   case PPC::LXV:
895   case PPC::STXV:
896     return 16;
897   }
898 }
899 
900 // If the offset must be a multiple of some value, return what that value is.
901 static unsigned offsetMinAlign(const MachineInstr &MI) {
902   unsigned OpC = MI.getOpcode();
903   return offsetMinAlignForOpcode(OpC);
904 }
905 
906 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
907 static unsigned getOffsetONFromFION(const MachineInstr &MI,
908                                     unsigned FIOperandNum) {
909   // Take into account whether it's an add or mem instruction
910   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
911   if (MI.isInlineAsm())
912     OffsetOperandNo = FIOperandNum - 1;
913   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
914            MI.getOpcode() == TargetOpcode::PATCHPOINT)
915     OffsetOperandNo = FIOperandNum + 1;
916 
917   return OffsetOperandNo;
918 }
919 
920 void
921 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
922                                      int SPAdj, unsigned FIOperandNum,
923                                      RegScavenger *RS) const {
924   assert(SPAdj == 0 && "Unexpected");
925 
926   // Get the instruction.
927   MachineInstr &MI = *II;
928   // Get the instruction's basic block.
929   MachineBasicBlock &MBB = *MI.getParent();
930   // Get the basic block's function.
931   MachineFunction &MF = *MBB.getParent();
932   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
933   // Get the instruction info.
934   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
935   // Get the frame info.
936   MachineFrameInfo &MFI = MF.getFrameInfo();
937   DebugLoc dl = MI.getDebugLoc();
938 
939   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
940 
941   // Get the frame index.
942   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
943 
944   // Get the frame pointer save index.  Users of this index are primarily
945   // DYNALLOC instructions.
946   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
947   int FPSI = FI->getFramePointerSaveIndex();
948   // Get the instruction opcode.
949   unsigned OpC = MI.getOpcode();
950 
951   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
952     lowerDynamicAreaOffset(II);
953     return;
954   }
955 
956   // Special case for dynamic alloca.
957   if (FPSI && FrameIndex == FPSI &&
958       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
959     lowerDynamicAlloc(II);
960     return;
961   }
962 
963   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
964   if (OpC == PPC::SPILL_CR) {
965     lowerCRSpilling(II, FrameIndex);
966     return;
967   } else if (OpC == PPC::RESTORE_CR) {
968     lowerCRRestore(II, FrameIndex);
969     return;
970   } else if (OpC == PPC::SPILL_CRBIT) {
971     lowerCRBitSpilling(II, FrameIndex);
972     return;
973   } else if (OpC == PPC::RESTORE_CRBIT) {
974     lowerCRBitRestore(II, FrameIndex);
975     return;
976   } else if (OpC == PPC::SPILL_VRSAVE) {
977     lowerVRSAVESpilling(II, FrameIndex);
978     return;
979   } else if (OpC == PPC::RESTORE_VRSAVE) {
980     lowerVRSAVERestore(II, FrameIndex);
981     return;
982   }
983 
984   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
985   MI.getOperand(FIOperandNum).ChangeToRegister(
986     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
987 
988   // If the instruction is not present in ImmToIdxMap, then it has no immediate
989   // form (and must be r+r).
990   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
991                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
992 
993   // Now add the frame object offset to the offset from r1.
994   int Offset = MFI.getObjectOffset(FrameIndex);
995   Offset += MI.getOperand(OffsetOperandNo).getImm();
996 
997   // If we're not using a Frame Pointer that has been set to the value of the
998   // SP before having the stack size subtracted from it, then add the stack size
999   // to Offset to get the correct offset.
1000   // Naked functions have stack size 0, although getStackSize may not reflect
1001   // that because we didn't call all the pieces that compute it for naked
1002   // functions.
1003   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1004     if (!(hasBasePointer(MF) && FrameIndex < 0))
1005       Offset += MFI.getStackSize();
1006   }
1007 
1008   // If we can, encode the offset directly into the instruction.  If this is a
1009   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1010   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1011   // clear can be encoded.  This is extremely uncommon, because normally you
1012   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1013   // happen in invalid code.
1014   assert(OpC != PPC::DBG_VALUE &&
1015          "This should be handled in a target-independent way");
1016   if (!noImmForm && ((isInt<16>(Offset) &&
1017                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1018                      OpC == TargetOpcode::STACKMAP ||
1019                      OpC == TargetOpcode::PATCHPOINT)) {
1020     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1021     return;
1022   }
1023 
1024   // The offset doesn't fit into a single register, scavenge one to build the
1025   // offset in.
1026 
1027   bool is64Bit = TM.isPPC64();
1028   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1029   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1030   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1031   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1032            SReg = MF.getRegInfo().createVirtualRegister(RC);
1033 
1034   // Insert a set of rA with the full offset value before the ld, st, or add
1035   if (isInt<16>(Offset))
1036     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1037       .addImm(Offset);
1038   else {
1039     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1040       .addImm(Offset >> 16);
1041     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1042       .addReg(SRegHi, RegState::Kill)
1043       .addImm(Offset);
1044   }
1045 
1046   // Convert into indexed form of the instruction:
1047   //
1048   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1049   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1050   unsigned OperandBase;
1051 
1052   if (noImmForm)
1053     OperandBase = 1;
1054   else if (OpC != TargetOpcode::INLINEASM &&
1055            OpC != TargetOpcode::INLINEASM_BR) {
1056     assert(ImmToIdxMap.count(OpC) &&
1057            "No indexed form of load or store available!");
1058     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1059     MI.setDesc(TII.get(NewOpcode));
1060     OperandBase = 1;
1061   } else {
1062     OperandBase = OffsetOperandNo;
1063   }
1064 
1065   unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
1066   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1067   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1068 }
1069 
1070 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1071   const PPCFrameLowering *TFI = getFrameLowering(MF);
1072 
1073   if (!TM.isPPC64())
1074     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1075   else
1076     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1077 }
1078 
1079 unsigned PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1080   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1081   if (!hasBasePointer(MF))
1082     return getFrameRegister(MF);
1083 
1084   if (TM.isPPC64())
1085     return PPC::X30;
1086 
1087   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1088     return PPC::R29;
1089 
1090   return PPC::R30;
1091 }
1092 
1093 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1094   if (!EnableBasePointer)
1095     return false;
1096   if (AlwaysBasePointer)
1097     return true;
1098 
1099   // If we need to realign the stack, then the stack pointer can no longer
1100   // serve as an offset into the caller's stack space. As a result, we need a
1101   // base pointer.
1102   return needsStackRealignment(MF);
1103 }
1104 
1105 /// Returns true if the instruction's frame index
1106 /// reference would be better served by a base register other than FP
1107 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1108 /// references it should create new base registers for.
1109 bool PPCRegisterInfo::
1110 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1111   assert(Offset < 0 && "Local offset must be negative");
1112 
1113   // It's the load/store FI references that cause issues, as it can be difficult
1114   // to materialize the offset if it won't fit in the literal field. Estimate
1115   // based on the size of the local frame and some conservative assumptions
1116   // about the rest of the stack frame (note, this is pre-regalloc, so
1117   // we don't know everything for certain yet) whether this offset is likely
1118   // to be out of range of the immediate. Return true if so.
1119 
1120   // We only generate virtual base registers for loads and stores that have
1121   // an r+i form. Return false for everything else.
1122   unsigned OpC = MI->getOpcode();
1123   if (!ImmToIdxMap.count(OpC))
1124     return false;
1125 
1126   // Don't generate a new virtual base register just to add zero to it.
1127   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1128       MI->getOperand(2).getImm() == 0)
1129     return false;
1130 
1131   MachineBasicBlock &MBB = *MI->getParent();
1132   MachineFunction &MF = *MBB.getParent();
1133   const PPCFrameLowering *TFI = getFrameLowering(MF);
1134   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1135 
1136   // If we likely don't need a stack frame, then we probably don't need a
1137   // virtual base register either.
1138   if (!StackEst)
1139     return false;
1140 
1141   // Estimate an offset from the stack pointer.
1142   // The incoming offset is relating to the SP at the start of the function,
1143   // but when we access the local it'll be relative to the SP after local
1144   // allocation, so adjust our SP-relative offset by that allocation size.
1145   Offset += StackEst;
1146 
1147   // The frame pointer will point to the end of the stack, so estimate the
1148   // offset as the difference between the object offset and the FP location.
1149   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1150 }
1151 
1152 /// Insert defining instruction(s) for BaseReg to
1153 /// be a pointer to FrameIdx at the beginning of the basic block.
1154 void PPCRegisterInfo::
1155 materializeFrameBaseRegister(MachineBasicBlock *MBB,
1156                              unsigned BaseReg, int FrameIdx,
1157                              int64_t Offset) const {
1158   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1159 
1160   MachineBasicBlock::iterator Ins = MBB->begin();
1161   DebugLoc DL;                  // Defaults to "unknown"
1162   if (Ins != MBB->end())
1163     DL = Ins->getDebugLoc();
1164 
1165   const MachineFunction &MF = *MBB->getParent();
1166   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1167   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1168   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1169   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1170   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1171 
1172   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1173     .addFrameIndex(FrameIdx).addImm(Offset);
1174 }
1175 
1176 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
1177                                         int64_t Offset) const {
1178   unsigned FIOperandNum = 0;
1179   while (!MI.getOperand(FIOperandNum).isFI()) {
1180     ++FIOperandNum;
1181     assert(FIOperandNum < MI.getNumOperands() &&
1182            "Instr doesn't have FrameIndex operand!");
1183   }
1184 
1185   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1186   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1187   Offset += MI.getOperand(OffsetOperandNo).getImm();
1188   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1189 
1190   MachineBasicBlock &MBB = *MI.getParent();
1191   MachineFunction &MF = *MBB.getParent();
1192   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1193   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1194   const MCInstrDesc &MCID = MI.getDesc();
1195   MachineRegisterInfo &MRI = MF.getRegInfo();
1196   MRI.constrainRegClass(BaseReg,
1197                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1198 }
1199 
1200 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1201                                          unsigned BaseReg,
1202                                          int64_t Offset) const {
1203   unsigned FIOperandNum = 0;
1204   while (!MI->getOperand(FIOperandNum).isFI()) {
1205     ++FIOperandNum;
1206     assert(FIOperandNum < MI->getNumOperands() &&
1207            "Instr doesn't have FrameIndex operand!");
1208   }
1209 
1210   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1211   Offset += MI->getOperand(OffsetOperandNo).getImm();
1212 
1213   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1214          MI->getOpcode() == TargetOpcode::STACKMAP ||
1215          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1216          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1217 }
1218