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