xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision 1c450c3d7ec01d9daaf9f2651da93b01e7790ffd)
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 "PPCFrameLowering.h"
16 #include "PPCInstrBuilder.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/CodeGen/TargetFrameLowering.h"
30 #include "llvm/CodeGen/TargetInstrInfo.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include <cstdlib>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "reginfo"
47 
48 #define GET_REGINFO_TARGET_DESC
49 #include "PPCGenRegisterInfo.inc"
50 
51 STATISTIC(InflateGPRC, "Number of gprc inputs for getLargestLegalClass");
52 STATISTIC(InflateGP8RC, "Number of g8rc inputs for getLargestLegalClass");
53 
54 static cl::opt<bool>
55 EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
56          cl::desc("Enable use of a base pointer for complex stack frames"));
57 
58 static cl::opt<bool>
59 AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
60          cl::desc("Force the use of a base pointer in every function"));
61 
62 static cl::opt<bool>
63 EnableGPRToVecSpills("ppc-enable-gpr-to-vsr-spills", cl::Hidden, cl::init(false),
64          cl::desc("Enable spills from gpr to vsr rather than stack"));
65 
66 static cl::opt<bool>
67 StackPtrConst("ppc-stack-ptr-caller-preserved",
68                 cl::desc("Consider R1 caller preserved so stack saves of "
69                          "caller preserved registers can be LICM candidates"),
70                 cl::init(true), cl::Hidden);
71 
72 static cl::opt<unsigned>
73 MaxCRBitSpillDist("ppc-max-crbit-spill-dist",
74                   cl::desc("Maximum search distance for definition of CR bit "
75                            "spill on ppc"),
76                   cl::Hidden, cl::init(100));
77 
78 // Copies/moves of physical accumulators are expensive operations
79 // that should be avoided whenever possible. MMA instructions are
80 // meant to be used in performance-sensitive computational kernels.
81 // This option is provided, at least for the time being, to give the
82 // user a tool to detect this expensive operation and either rework
83 // their code or report a compiler bug if that turns out to be the
84 // cause.
85 #ifndef NDEBUG
86 static cl::opt<bool>
87 ReportAccMoves("ppc-report-acc-moves",
88                cl::desc("Emit information about accumulator register spills "
89                         "and copies"),
90                cl::Hidden, cl::init(false));
91 #endif
92 
93 static unsigned offsetMinAlignForOpcode(unsigned OpC);
94 
95 PPCRegisterInfo::PPCRegisterInfo(const PPCTargetMachine &TM)
96   : PPCGenRegisterInfo(TM.isPPC64() ? PPC::LR8 : PPC::LR,
97                        TM.isPPC64() ? 0 : 1,
98                        TM.isPPC64() ? 0 : 1),
99     TM(TM) {
100   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
101   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
102   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
103   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
104   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
105   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
106   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
107   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
108   ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
109 
110   // 64-bit
111   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
112   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
113   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
114   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
115   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
116 
117   // VSX
118   ImmToIdxMap[PPC::DFLOADf32] = PPC::LXSSPX;
119   ImmToIdxMap[PPC::DFLOADf64] = PPC::LXSDX;
120   ImmToIdxMap[PPC::SPILLTOVSR_LD] = PPC::SPILLTOVSR_LDX;
121   ImmToIdxMap[PPC::SPILLTOVSR_ST] = PPC::SPILLTOVSR_STX;
122   ImmToIdxMap[PPC::DFSTOREf32] = PPC::STXSSPX;
123   ImmToIdxMap[PPC::DFSTOREf64] = PPC::STXSDX;
124   ImmToIdxMap[PPC::LXV] = PPC::LXVX;
125   ImmToIdxMap[PPC::LXSD] = PPC::LXSDX;
126   ImmToIdxMap[PPC::LXSSP] = PPC::LXSSPX;
127   ImmToIdxMap[PPC::STXV] = PPC::STXVX;
128   ImmToIdxMap[PPC::STXSD] = PPC::STXSDX;
129   ImmToIdxMap[PPC::STXSSP] = PPC::STXSSPX;
130 
131   // SPE
132   ImmToIdxMap[PPC::EVLDD] = PPC::EVLDDX;
133   ImmToIdxMap[PPC::EVSTDD] = PPC::EVSTDDX;
134   ImmToIdxMap[PPC::SPESTW] = PPC::SPESTWX;
135   ImmToIdxMap[PPC::SPELWZ] = PPC::SPELWZX;
136 }
137 
138 /// getPointerRegClass - Return the register class to use to hold pointers.
139 /// This is used for addressing modes.
140 const TargetRegisterClass *
141 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
142                                                                        const {
143   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
144   // when it checks for ZERO folding.
145   if (Kind == 1) {
146     if (TM.isPPC64())
147       return &PPC::G8RC_NOX0RegClass;
148     return &PPC::GPRC_NOR0RegClass;
149   }
150 
151   if (TM.isPPC64())
152     return &PPC::G8RCRegClass;
153   return &PPC::GPRCRegClass;
154 }
155 
156 const MCPhysReg*
157 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
158   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
159   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg) {
160     if (!TM.isPPC64() && Subtarget.isAIXABI())
161       report_fatal_error("AnyReg unimplemented on 32-bit AIX.");
162     if (Subtarget.hasVSX()) {
163       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
164         return CSR_64_AllRegs_AIX_Dflt_VSX_SaveList;
165       return CSR_64_AllRegs_VSX_SaveList;
166     }
167     if (Subtarget.hasAltivec()) {
168       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
169         return CSR_64_AllRegs_AIX_Dflt_Altivec_SaveList;
170       return CSR_64_AllRegs_Altivec_SaveList;
171     }
172     return CSR_64_AllRegs_SaveList;
173   }
174 
175   // On PPC64, we might need to save r2 (but only if it is not reserved).
176   // We do not need to treat R2 as callee-saved when using PC-Relative calls
177   // because any direct uses of R2 will cause it to be reserved. If the function
178   // is a leaf or the only uses of R2 are implicit uses for calls, the calls
179   // will use the @notoc relocation which will cause this function to set the
180   // st_other bit to 1, thereby communicating to its caller that it arbitrarily
181   // clobbers the TOC.
182   bool SaveR2 = MF->getRegInfo().isAllocatable(PPC::X2) &&
183                 !Subtarget.isUsingPCRelativeCalls();
184 
185   // Cold calling convention CSRs.
186   if (MF->getFunction().getCallingConv() == CallingConv::Cold) {
187     if (Subtarget.isAIXABI())
188       report_fatal_error("Cold calling unimplemented on AIX.");
189     if (TM.isPPC64()) {
190       if (Subtarget.hasAltivec())
191         return SaveR2 ? CSR_SVR64_ColdCC_R2_Altivec_SaveList
192                       : CSR_SVR64_ColdCC_Altivec_SaveList;
193       return SaveR2 ? CSR_SVR64_ColdCC_R2_SaveList
194                     : CSR_SVR64_ColdCC_SaveList;
195     }
196     // 32-bit targets.
197     if (Subtarget.hasAltivec())
198       return CSR_SVR32_ColdCC_Altivec_SaveList;
199     else if (Subtarget.hasSPE())
200       return CSR_SVR32_ColdCC_SPE_SaveList;
201     return CSR_SVR32_ColdCC_SaveList;
202   }
203   // Standard calling convention CSRs.
204   if (TM.isPPC64()) {
205     if (Subtarget.hasAltivec() &&
206         (!Subtarget.isAIXABI() || TM.getAIXExtendedAltivecABI())) {
207       return SaveR2 ? CSR_PPC64_R2_Altivec_SaveList
208                     : CSR_PPC64_Altivec_SaveList;
209     }
210     return SaveR2 ? CSR_PPC64_R2_SaveList : CSR_PPC64_SaveList;
211   }
212   // 32-bit targets.
213   if (Subtarget.isAIXABI()) {
214     if (Subtarget.hasAltivec())
215       return TM.getAIXExtendedAltivecABI() ? CSR_AIX32_Altivec_SaveList
216                                            : CSR_AIX32_SaveList;
217     return CSR_AIX32_SaveList;
218   }
219   if (Subtarget.hasAltivec())
220     return CSR_SVR432_Altivec_SaveList;
221   else if (Subtarget.hasSPE())
222     return CSR_SVR432_SPE_SaveList;
223   return CSR_SVR432_SaveList;
224 }
225 
226 const uint32_t *
227 PPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
228                                       CallingConv::ID CC) const {
229   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
230   if (CC == CallingConv::AnyReg) {
231     if (Subtarget.hasVSX()) {
232       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
233         return CSR_64_AllRegs_AIX_Dflt_VSX_RegMask;
234       return CSR_64_AllRegs_VSX_RegMask;
235     }
236     if (Subtarget.hasAltivec()) {
237       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
238         return CSR_64_AllRegs_AIX_Dflt_Altivec_RegMask;
239       return CSR_64_AllRegs_Altivec_RegMask;
240     }
241     return CSR_64_AllRegs_RegMask;
242   }
243 
244   if (Subtarget.isAIXABI()) {
245     return TM.isPPC64()
246                ? ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
247                       ? CSR_PPC64_Altivec_RegMask
248                       : CSR_PPC64_RegMask)
249                : ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
250                       ? CSR_AIX32_Altivec_RegMask
251                       : CSR_AIX32_RegMask);
252   }
253 
254   if (CC == CallingConv::Cold) {
255     return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_SVR64_ColdCC_Altivec_RegMask
256                                                   : CSR_SVR64_ColdCC_RegMask)
257                         : (Subtarget.hasAltivec() ? CSR_SVR32_ColdCC_Altivec_RegMask
258                                                   : (Subtarget.hasSPE()
259                                                   ? CSR_SVR32_ColdCC_SPE_RegMask
260                                                   : CSR_SVR32_ColdCC_RegMask));
261   }
262 
263   return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_PPC64_Altivec_RegMask
264                                                 : CSR_PPC64_RegMask)
265                       : (Subtarget.hasAltivec()
266                              ? CSR_SVR432_Altivec_RegMask
267                              : (Subtarget.hasSPE() ? CSR_SVR432_SPE_RegMask
268                                                    : CSR_SVR432_RegMask));
269 }
270 
271 const uint32_t*
272 PPCRegisterInfo::getNoPreservedMask() const {
273   return CSR_NoRegs_RegMask;
274 }
275 
276 void PPCRegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const {
277   for (unsigned PseudoReg : {PPC::ZERO, PPC::ZERO8, PPC::RM})
278     Mask[PseudoReg / 32] &= ~(1u << (PseudoReg % 32));
279 }
280 
281 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
282   BitVector Reserved(getNumRegs());
283   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
284   const PPCFrameLowering *TFI = getFrameLowering(MF);
285 
286   // The ZERO register is not really a register, but the representation of r0
287   // when used in instructions that treat r0 as the constant 0.
288   markSuperRegs(Reserved, PPC::ZERO);
289 
290   // The FP register is also not really a register, but is the representation
291   // of the frame pointer register used by ISD::FRAMEADDR.
292   markSuperRegs(Reserved, PPC::FP);
293 
294   // The BP register is also not really a register, but is the representation
295   // of the base pointer register used by setjmp.
296   markSuperRegs(Reserved, PPC::BP);
297 
298   // The counter registers must be reserved so that counter-based loops can
299   // be correctly formed (and the mtctr instructions are not DCE'd).
300   markSuperRegs(Reserved, PPC::CTR);
301   markSuperRegs(Reserved, PPC::CTR8);
302 
303   markSuperRegs(Reserved, PPC::R1);
304   markSuperRegs(Reserved, PPC::LR);
305   markSuperRegs(Reserved, PPC::LR8);
306   markSuperRegs(Reserved, PPC::RM);
307 
308   markSuperRegs(Reserved, PPC::VRSAVE);
309 
310   // The SVR4 ABI reserves r2 and r13
311   if (Subtarget.isSVR4ABI()) {
312     // We only reserve r2 if we need to use the TOC pointer. If we have no
313     // explicit uses of the TOC pointer (meaning we're a leaf function with
314     // no constant-pool loads, etc.) and we have no potential uses inside an
315     // inline asm block, then we can treat r2 has an ordinary callee-saved
316     // register.
317     const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
318     if (!TM.isPPC64() || FuncInfo->usesTOCBasePtr() || MF.hasInlineAsm())
319       markSuperRegs(Reserved, PPC::R2);  // System-reserved register
320     markSuperRegs(Reserved, PPC::R13); // Small Data Area pointer register
321   }
322 
323   // Always reserve r2 on AIX for now.
324   // TODO: Make r2 allocatable on AIX/XCOFF for some leaf functions.
325   if (Subtarget.isAIXABI())
326     markSuperRegs(Reserved, PPC::R2);  // System-reserved register
327 
328   // On PPC64, r13 is the thread pointer. Never allocate this register.
329   if (TM.isPPC64())
330     markSuperRegs(Reserved, PPC::R13);
331 
332   if (TFI->needsFP(MF))
333     markSuperRegs(Reserved, PPC::R31);
334 
335   bool IsPositionIndependent = TM.isPositionIndependent();
336   if (hasBasePointer(MF)) {
337     if (Subtarget.is32BitELFABI() && IsPositionIndependent)
338       markSuperRegs(Reserved, PPC::R29);
339     else
340       markSuperRegs(Reserved, PPC::R30);
341   }
342 
343   if (Subtarget.is32BitELFABI() && IsPositionIndependent)
344     markSuperRegs(Reserved, PPC::R30);
345 
346   // Reserve Altivec registers when Altivec is unavailable.
347   if (!Subtarget.hasAltivec())
348     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
349          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
350       markSuperRegs(Reserved, *I);
351 
352   if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
353       !TM.getAIXExtendedAltivecABI()) {
354     //  In the AIX default Altivec ABI, vector registers VR20-VR31 are reserved
355     //  and cannot be used.
356     for (auto Reg : CSR_Altivec_SaveList) {
357       if (Reg == 0)
358         break;
359       markSuperRegs(Reserved, Reg);
360       for (MCRegAliasIterator AS(Reg, this, true); AS.isValid(); ++AS) {
361         Reserved.set(*AS);
362       }
363     }
364   }
365 
366   assert(checkAllSuperRegsMarked(Reserved));
367   return Reserved;
368 }
369 
370 bool PPCRegisterInfo::requiresFrameIndexScavenging(const MachineFunction &MF) const {
371   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
372   const PPCInstrInfo *InstrInfo =  Subtarget.getInstrInfo();
373   const MachineFrameInfo &MFI = MF.getFrameInfo();
374   const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
375 
376   LLVM_DEBUG(dbgs() << "requiresFrameIndexScavenging for " << MF.getName()
377                     << ".\n");
378   // If the callee saved info is invalid we have to default to true for safety.
379   if (!MFI.isCalleeSavedInfoValid()) {
380     LLVM_DEBUG(dbgs() << "TRUE - Invalid callee saved info.\n");
381     return true;
382   }
383 
384   // We will require the use of X-Forms because the frame is larger than what
385   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
386   // If we need an X-Form then we need a register to store the address offset.
387   unsigned FrameSize = MFI.getStackSize();
388   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
389   if (FrameSize & ~0x7FFF) {
390     LLVM_DEBUG(dbgs() << "TRUE - Frame size is too large for D-Form.\n");
391     return true;
392   }
393 
394   // The callee saved info is valid so it can be traversed.
395   // Checking for registers that need saving that do not have load or store
396   // forms where the address offset is an immediate.
397   for (unsigned i = 0; i < Info.size(); i++) {
398     // If the spill is to a register no scavenging is required.
399     if (Info[i].isSpilledToReg())
400       continue;
401 
402     int FrIdx = Info[i].getFrameIdx();
403     unsigned Reg = Info[i].getReg();
404 
405     const TargetRegisterClass *RC = getMinimalPhysRegClass(Reg);
406     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(RC);
407     if (!MFI.isFixedObjectIndex(FrIdx)) {
408       // This is not a fixed object. If it requires alignment then we may still
409       // need to use the XForm.
410       if (offsetMinAlignForOpcode(Opcode) > 1) {
411         LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
412                           << " for register " << printReg(Reg, this) << ".\n");
413         LLVM_DEBUG(dbgs() << "TRUE - Not fixed frame object that requires "
414                           << "alignment.\n");
415         return true;
416       }
417     }
418 
419     // This is eiher:
420     // 1) A fixed frame index object which we know are aligned so
421     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
422     // need to consider the alignment here.
423     // 2) A not fixed object but in that case we now know that the min required
424     // alignment is no more than 1 based on the previous check.
425     if (InstrInfo->isXFormMemOp(Opcode)) {
426       LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
427                         << " for register " << printReg(Reg, this) << ".\n");
428       LLVM_DEBUG(dbgs() << "TRUE - Memory operand is X-Form.\n");
429       return true;
430     }
431   }
432   LLVM_DEBUG(dbgs() << "FALSE - Scavenging is not required.\n");
433   return false;
434 }
435 
436 bool PPCRegisterInfo::requiresVirtualBaseRegisters(
437     const MachineFunction &MF) const {
438   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
439   // Do not use virtual base registers when ROP protection is turned on.
440   // Virtual base registers break the layout of the local variable space and may
441   // push the ROP Hash location past the 512 byte range of the ROP store
442   // instruction.
443   return !Subtarget.hasROPProtect();
444 }
445 
446 bool PPCRegisterInfo::isCallerPreservedPhysReg(MCRegister PhysReg,
447                                                const MachineFunction &MF) const {
448   assert(Register::isPhysicalRegister(PhysReg));
449   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
450   const MachineFrameInfo &MFI = MF.getFrameInfo();
451 
452   if (!Subtarget.is64BitELFABI() && !Subtarget.isAIXABI())
453     return false;
454   if (PhysReg == Subtarget.getTOCPointerRegister())
455     // X2/R2 is guaranteed to be preserved within a function if it is reserved.
456     // The reason it's reserved is that it's the TOC pointer (and the function
457     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
458     // with no TOC access), we can't claim that it is preserved.
459     return (getReservedRegs(MF).test(PhysReg));
460   if (StackPtrConst && PhysReg == Subtarget.getStackPointerRegister() &&
461       !MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
462     // The value of the stack pointer does not change within a function after
463     // the prologue and before the epilogue if there are no dynamic allocations
464     // and no inline asm which clobbers X1/R1.
465     return true;
466   return false;
467 }
468 
469 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
470                                               MachineFunction &MF) const {
471   const PPCFrameLowering *TFI = getFrameLowering(MF);
472   const unsigned DefaultSafety = 1;
473 
474   switch (RC->getID()) {
475   default:
476     return 0;
477   case PPC::G8RC_NOX0RegClassID:
478   case PPC::GPRC_NOR0RegClassID:
479   case PPC::SPERCRegClassID:
480   case PPC::G8RCRegClassID:
481   case PPC::GPRCRegClassID: {
482     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
483     return 32 - FP - DefaultSafety;
484   }
485   case PPC::F4RCRegClassID:
486   case PPC::F8RCRegClassID:
487   case PPC::VSLRCRegClassID:
488     return 32 - DefaultSafety;
489   case PPC::VFRCRegClassID:
490   case PPC::VRRCRegClassID: {
491     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
492     // Vector registers VR20-VR31 are reserved and cannot be used in the default
493     // Altivec ABI on AIX.
494     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
495       return 20 - DefaultSafety;
496   }
497     return 32 - DefaultSafety;
498   case PPC::VSFRCRegClassID:
499   case PPC::VSSRCRegClassID:
500   case PPC::VSRCRegClassID: {
501     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
502     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
503       // Vector registers VR20-VR31 are reserved and cannot be used in the
504       // default Altivec ABI on AIX.
505       return 52 - DefaultSafety;
506   }
507     return 64 - DefaultSafety;
508   case PPC::CRRCRegClassID:
509     return 8 - DefaultSafety;
510   }
511 }
512 
513 const TargetRegisterClass *
514 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
515                                            const MachineFunction &MF) const {
516   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
517   const auto *DefaultSuperclass =
518       TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
519   if (Subtarget.hasVSX()) {
520     // With VSX, we can inflate various sub-register classes to the full VSX
521     // register set.
522 
523     // For Power9 we allow the user to enable GPR to vector spills.
524     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
525     // support to spill GPRC.
526     if (TM.isELFv2ABI() || Subtarget.isAIXABI()) {
527       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
528           RC == &PPC::G8RCRegClass) {
529         InflateGP8RC++;
530         return &PPC::SPILLTOVSRRCRegClass;
531       }
532       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
533         InflateGPRC++;
534     }
535 
536     for (const auto *I = RC->getSuperClasses(); *I; ++I) {
537       if (getRegSizeInBits(**I) != getRegSizeInBits(*RC))
538         continue;
539 
540       switch ((*I)->getID()) {
541       case PPC::VSSRCRegClassID:
542         return Subtarget.hasP8Vector() ? *I : DefaultSuperclass;
543       case PPC::VSFRCRegClassID:
544       case PPC::VSRCRegClassID:
545         return *I;
546       case PPC::VSRpRCRegClassID:
547         return Subtarget.pairedVectorMemops() ? *I : DefaultSuperclass;
548       case PPC::ACCRCRegClassID:
549       case PPC::UACCRCRegClassID:
550         return Subtarget.hasMMA() ? *I : DefaultSuperclass;
551       }
552     }
553   }
554 
555   return DefaultSuperclass;
556 }
557 
558 //===----------------------------------------------------------------------===//
559 // Stack Frame Processing methods
560 //===----------------------------------------------------------------------===//
561 
562 /// lowerDynamicAlloc - Generate the code for allocating an object in the
563 /// current frame.  The sequence of code will be in the general form
564 ///
565 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
566 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
567 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
568 ///
569 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
570   // Get the instruction.
571   MachineInstr &MI = *II;
572   // Get the instruction's basic block.
573   MachineBasicBlock &MBB = *MI.getParent();
574   // Get the basic block's function.
575   MachineFunction &MF = *MBB.getParent();
576   // Get the frame info.
577   MachineFrameInfo &MFI = MF.getFrameInfo();
578   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
579   // Get the instruction info.
580   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
581   // Determine whether 64-bit pointers are used.
582   bool LP64 = TM.isPPC64();
583   DebugLoc dl = MI.getDebugLoc();
584 
585   // Get the maximum call stack size.
586   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
587   Align MaxAlign = MFI.getMaxAlign();
588   assert(isAligned(MaxAlign, maxCallFrameSize) &&
589          "Maximum call-frame size not sufficiently aligned");
590   (void)MaxAlign;
591 
592   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
593   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
594   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
595   bool KillNegSizeReg = MI.getOperand(1).isKill();
596   Register NegSizeReg = MI.getOperand(1).getReg();
597 
598   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
599   // Grow the stack and update the stack pointer link, then determine the
600   // address of new allocated space.
601   if (LP64) {
602     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
603         .addReg(Reg, RegState::Kill)
604         .addReg(PPC::X1)
605         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
606     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
607         .addReg(PPC::X1)
608         .addImm(maxCallFrameSize);
609   } else {
610     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
611         .addReg(Reg, RegState::Kill)
612         .addReg(PPC::R1)
613         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
614     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
615         .addReg(PPC::R1)
616         .addImm(maxCallFrameSize);
617   }
618 
619   // Discard the DYNALLOC instruction.
620   MBB.erase(II);
621 }
622 
623 /// To accomplish dynamic stack allocation, we have to calculate exact size
624 /// subtracted from the stack pointer according alignment information and get
625 /// previous frame pointer.
626 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
627                                            Register &NegSizeReg,
628                                            bool &KillNegSizeReg,
629                                            Register &FramePointer) const {
630   // Get the instruction.
631   MachineInstr &MI = *II;
632   // Get the instruction's basic block.
633   MachineBasicBlock &MBB = *MI.getParent();
634   // Get the basic block's function.
635   MachineFunction &MF = *MBB.getParent();
636   // Get the frame info.
637   MachineFrameInfo &MFI = MF.getFrameInfo();
638   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
639   // Get the instruction info.
640   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
641   // Determine whether 64-bit pointers are used.
642   bool LP64 = TM.isPPC64();
643   DebugLoc dl = MI.getDebugLoc();
644   // Get the total frame size.
645   unsigned FrameSize = MFI.getStackSize();
646 
647   // Get stack alignments.
648   const PPCFrameLowering *TFI = getFrameLowering(MF);
649   Align TargetAlign = TFI->getStackAlign();
650   Align MaxAlign = MFI.getMaxAlign();
651 
652   // Determine the previous frame's address.  If FrameSize can't be
653   // represented as 16 bits or we need special alignment, then we load the
654   // previous frame's address from 0(SP).  Why not do an addis of the hi?
655   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
656   // Constructing the constant and adding would take 3 instructions.
657   // Fortunately, a frame greater than 32K is rare.
658   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
659   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
660 
661   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
662     if (LP64)
663       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
664           .addReg(PPC::X31)
665           .addImm(FrameSize);
666     else
667       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
668           .addReg(PPC::R31)
669           .addImm(FrameSize);
670   } else if (LP64) {
671     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
672         .addImm(0)
673         .addReg(PPC::X1);
674   } else {
675     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
676         .addImm(0)
677         .addReg(PPC::R1);
678   }
679   // Determine the actual NegSizeReg according to alignment info.
680   if (LP64) {
681     if (MaxAlign > TargetAlign) {
682       unsigned UnalNegSizeReg = NegSizeReg;
683       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
684 
685       // Unfortunately, there is no andi, only andi., and we can't insert that
686       // here because we might clobber cr0 while it is live.
687       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
688           .addImm(~(MaxAlign.value() - 1));
689 
690       unsigned NegSizeReg1 = NegSizeReg;
691       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
692       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
693           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
694           .addReg(NegSizeReg1, RegState::Kill);
695       KillNegSizeReg = true;
696     }
697   } else {
698     if (MaxAlign > TargetAlign) {
699       unsigned UnalNegSizeReg = NegSizeReg;
700       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
701 
702       // Unfortunately, there is no andi, only andi., and we can't insert that
703       // here because we might clobber cr0 while it is live.
704       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
705           .addImm(~(MaxAlign.value() - 1));
706 
707       unsigned NegSizeReg1 = NegSizeReg;
708       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
709       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
710           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
711           .addReg(NegSizeReg1, RegState::Kill);
712       KillNegSizeReg = true;
713     }
714   }
715 }
716 
717 void PPCRegisterInfo::lowerPrepareProbedAlloca(
718     MachineBasicBlock::iterator II) const {
719   MachineInstr &MI = *II;
720   // Get the instruction's basic block.
721   MachineBasicBlock &MBB = *MI.getParent();
722   // Get the basic block's function.
723   MachineFunction &MF = *MBB.getParent();
724   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
725   // Get the instruction info.
726   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
727   // Determine whether 64-bit pointers are used.
728   bool LP64 = TM.isPPC64();
729   DebugLoc dl = MI.getDebugLoc();
730   Register FramePointer = MI.getOperand(0).getReg();
731   const Register ActualNegSizeReg = MI.getOperand(1).getReg();
732   bool KillNegSizeReg = MI.getOperand(2).isKill();
733   Register NegSizeReg = MI.getOperand(2).getReg();
734   const MCInstrDesc &CopyInst = TII.get(LP64 ? PPC::OR8 : PPC::OR);
735   // RegAllocator might allocate FramePointer and NegSizeReg in the same phyreg.
736   if (FramePointer == NegSizeReg) {
737     assert(KillNegSizeReg && "FramePointer is a def and NegSizeReg is an use, "
738                              "NegSizeReg should be killed");
739     // FramePointer is clobbered earlier than the use of NegSizeReg in
740     // prepareDynamicAlloca, save NegSizeReg in ActualNegSizeReg to avoid
741     // misuse.
742     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
743         .addReg(NegSizeReg)
744         .addReg(NegSizeReg);
745     NegSizeReg = ActualNegSizeReg;
746     KillNegSizeReg = false;
747   }
748   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, FramePointer);
749   // NegSizeReg might be updated in prepareDynamicAlloca if MaxAlign >
750   // TargetAlign.
751   if (NegSizeReg != ActualNegSizeReg)
752     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
753         .addReg(NegSizeReg)
754         .addReg(NegSizeReg);
755   MBB.erase(II);
756 }
757 
758 void PPCRegisterInfo::lowerDynamicAreaOffset(
759     MachineBasicBlock::iterator II) const {
760   // Get the instruction.
761   MachineInstr &MI = *II;
762   // Get the instruction's basic block.
763   MachineBasicBlock &MBB = *MI.getParent();
764   // Get the basic block's function.
765   MachineFunction &MF = *MBB.getParent();
766   // Get the frame info.
767   MachineFrameInfo &MFI = MF.getFrameInfo();
768   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
769   // Get the instruction info.
770   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
771 
772   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
773   bool is64Bit = TM.isPPC64();
774   DebugLoc dl = MI.getDebugLoc();
775   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
776           MI.getOperand(0).getReg())
777       .addImm(maxCallFrameSize);
778   MBB.erase(II);
779 }
780 
781 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
782 /// reserving a whole register (R0), we scrounge for one here. This generates
783 /// code like this:
784 ///
785 ///   mfcr rA                  ; Move the conditional register into GPR rA.
786 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
787 ///   stw rA, FI               ; Store rA to the frame.
788 ///
789 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
790                                       unsigned FrameIndex) const {
791   // Get the instruction.
792   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
793   // Get the instruction's basic block.
794   MachineBasicBlock &MBB = *MI.getParent();
795   MachineFunction &MF = *MBB.getParent();
796   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
797   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
798   DebugLoc dl = MI.getDebugLoc();
799 
800   bool LP64 = TM.isPPC64();
801   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
802   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
803 
804   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
805   Register SrcReg = MI.getOperand(0).getReg();
806 
807   // We need to store the CR in the low 4-bits of the saved value. First, issue
808   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
809   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
810       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
811 
812   // If the saved register wasn't CR0, shift the bits left so that they are in
813   // CR0's slot.
814   if (SrcReg != PPC::CR0) {
815     Register Reg1 = Reg;
816     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
817 
818     // rlwinm rA, rA, ShiftBits, 0, 31.
819     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
820       .addReg(Reg1, RegState::Kill)
821       .addImm(getEncodingValue(SrcReg) * 4)
822       .addImm(0)
823       .addImm(31);
824   }
825 
826   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
827                     .addReg(Reg, RegState::Kill),
828                     FrameIndex);
829 
830   // Discard the pseudo instruction.
831   MBB.erase(II);
832 }
833 
834 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
835                                       unsigned FrameIndex) const {
836   // Get the instruction.
837   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
838   // Get the instruction's basic block.
839   MachineBasicBlock &MBB = *MI.getParent();
840   MachineFunction &MF = *MBB.getParent();
841   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
842   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
843   DebugLoc dl = MI.getDebugLoc();
844 
845   bool LP64 = TM.isPPC64();
846   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
847   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
848 
849   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
850   Register DestReg = MI.getOperand(0).getReg();
851   assert(MI.definesRegister(DestReg) &&
852     "RESTORE_CR does not define its destination");
853 
854   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
855                               Reg), FrameIndex);
856 
857   // If the reloaded register isn't CR0, shift the bits right so that they are
858   // in the right CR's slot.
859   if (DestReg != PPC::CR0) {
860     Register Reg1 = Reg;
861     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
862 
863     unsigned ShiftBits = getEncodingValue(DestReg)*4;
864     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
865     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
866              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
867              .addImm(31);
868   }
869 
870   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
871              .addReg(Reg, RegState::Kill);
872 
873   // Discard the pseudo instruction.
874   MBB.erase(II);
875 }
876 
877 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
878                                          unsigned FrameIndex) const {
879   // Get the instruction.
880   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
881   // Get the instruction's basic block.
882   MachineBasicBlock &MBB = *MI.getParent();
883   MachineFunction &MF = *MBB.getParent();
884   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
885   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
886   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
887   DebugLoc dl = MI.getDebugLoc();
888 
889   bool LP64 = TM.isPPC64();
890   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
891   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
892 
893   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
894   Register SrcReg = MI.getOperand(0).getReg();
895 
896   // Search up the BB to find the definition of the CR bit.
897   MachineBasicBlock::reverse_iterator Ins = MI;
898   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
899   ++Ins;
900   unsigned CRBitSpillDistance = 0;
901   bool SeenUse = false;
902   for (; Ins != Rend; ++Ins) {
903     // Definition found.
904     if (Ins->modifiesRegister(SrcReg, TRI))
905       break;
906     // Use found.
907     if (Ins->readsRegister(SrcReg, TRI))
908       SeenUse = true;
909     // Unable to find CR bit definition within maximum search distance.
910     if (CRBitSpillDistance == MaxCRBitSpillDist) {
911       Ins = MI;
912       break;
913     }
914     // Skip debug instructions when counting CR bit spill distance.
915     if (!Ins->isDebugInstr())
916       CRBitSpillDistance++;
917   }
918 
919   // Unable to find the definition of the CR bit in the MBB.
920   if (Ins == MBB.rend())
921     Ins = MI;
922 
923   bool SpillsKnownBit = false;
924   // There is no need to extract the CR bit if its value is already known.
925   switch (Ins->getOpcode()) {
926   case PPC::CRUNSET:
927     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
928       .addImm(0);
929     SpillsKnownBit = true;
930     break;
931   case PPC::CRSET:
932     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
933       .addImm(-32768);
934     SpillsKnownBit = true;
935     break;
936   default:
937     // On Power10, we can use SETNBC to spill all CR bits. SETNBC will set all
938     // bits (specifically, it produces a -1 if the CR bit is set). Ultimately,
939     // the bit that is of importance to us is bit 32 (bit 0 of a 32-bit
940     // register), and SETNBC will set this.
941     if (Subtarget.isISA3_1()) {
942       BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETNBC8 : PPC::SETNBC), Reg)
943           .addReg(SrcReg, RegState::Undef);
944       break;
945     }
946 
947     // On Power9, we can use SETB to extract the LT bit. This only works for
948     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
949     // of the bit we care about (32-bit sign bit) will be set to the value of
950     // the LT bit (regardless of the other bits in the CR field).
951     if (Subtarget.isISA3_0()) {
952       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
953           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
954           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
955           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
956         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
957           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
958         break;
959       }
960     }
961 
962     // We need to move the CR field that contains the CR bit we are spilling.
963     // The super register may not be explicitly defined (i.e. it can be defined
964     // by a CR-logical that only defines the subreg) so we state that the CR
965     // field is undef. Also, in order to preserve the kill flag on the CR bit,
966     // we add it as an implicit use.
967     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
968       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
969       .addReg(SrcReg,
970               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
971 
972     // If the saved register wasn't CR0LT, shift the bits left so that the bit
973     // to store is the first one. Mask all but that bit.
974     Register Reg1 = Reg;
975     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
976 
977     // rlwinm rA, rA, ShiftBits, 0, 0.
978     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
979       .addReg(Reg1, RegState::Kill)
980       .addImm(getEncodingValue(SrcReg))
981       .addImm(0).addImm(0);
982   }
983   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
984                     .addReg(Reg, RegState::Kill),
985                     FrameIndex);
986 
987   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
988   // Discard the pseudo instruction.
989   MBB.erase(II);
990   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
991     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
992     Ins->RemoveOperand(0);
993   }
994 }
995 
996 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
997                                       unsigned FrameIndex) const {
998   // Get the instruction.
999   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
1000   // Get the instruction's basic block.
1001   MachineBasicBlock &MBB = *MI.getParent();
1002   MachineFunction &MF = *MBB.getParent();
1003   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1004   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1005   DebugLoc dl = MI.getDebugLoc();
1006 
1007   bool LP64 = TM.isPPC64();
1008   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1009   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1010 
1011   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1012   Register DestReg = MI.getOperand(0).getReg();
1013   assert(MI.definesRegister(DestReg) &&
1014     "RESTORE_CRBIT does not define its destination");
1015 
1016   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
1017                               Reg), FrameIndex);
1018 
1019   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
1020 
1021   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1022   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
1023           .addReg(getCRFromCRBit(DestReg));
1024 
1025   unsigned ShiftBits = getEncodingValue(DestReg);
1026   // rlwimi r11, r10, 32-ShiftBits, ..., ...
1027   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
1028       .addReg(RegO, RegState::Kill)
1029       .addReg(Reg, RegState::Kill)
1030       .addImm(ShiftBits ? 32 - ShiftBits : 0)
1031       .addImm(ShiftBits)
1032       .addImm(ShiftBits);
1033 
1034   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
1035           getCRFromCRBit(DestReg))
1036       .addReg(RegO, RegState::Kill)
1037       // Make sure we have a use dependency all the way through this
1038       // sequence of instructions. We can't have the other bits in the CR
1039       // modified in between the mfocrf and the mtocrf.
1040       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
1041 
1042   // Discard the pseudo instruction.
1043   MBB.erase(II);
1044 }
1045 
1046 void PPCRegisterInfo::emitAccCopyInfo(MachineBasicBlock &MBB,
1047                                       MCRegister DestReg, MCRegister SrcReg) {
1048 #ifdef NDEBUG
1049   return;
1050 #else
1051   if (ReportAccMoves) {
1052     std::string Dest = PPC::ACCRCRegClass.contains(DestReg) ? "acc" : "uacc";
1053     std::string Src = PPC::ACCRCRegClass.contains(SrcReg) ? "acc" : "uacc";
1054     dbgs() << "Emitting copy from " << Src << " to " << Dest << ":\n";
1055     MBB.dump();
1056   }
1057 #endif
1058 }
1059 
1060 static void emitAccSpillRestoreInfo(MachineBasicBlock &MBB, bool IsPrimed,
1061                                     bool IsRestore) {
1062 #ifdef NDEBUG
1063   return;
1064 #else
1065   if (ReportAccMoves) {
1066     dbgs() << "Emitting " << (IsPrimed ? "acc" : "uacc") << " register "
1067            << (IsRestore ? "restore" : "spill") << ":\n";
1068     MBB.dump();
1069   }
1070 #endif
1071 }
1072 
1073 /// lowerACCSpilling - Generate the code for spilling the accumulator register.
1074 /// Similarly to other spills/reloads that use pseudo-ops, we do not actually
1075 /// eliminate the FrameIndex here nor compute the stack offset. We simply
1076 /// create a real instruction with an FI and rely on eliminateFrameIndex to
1077 /// handle the FI elimination.
1078 void PPCRegisterInfo::lowerACCSpilling(MachineBasicBlock::iterator II,
1079                                        unsigned FrameIndex) const {
1080   MachineInstr &MI = *II; // SPILL_ACC <SrcReg>, <offset>
1081   MachineBasicBlock &MBB = *MI.getParent();
1082   MachineFunction &MF = *MBB.getParent();
1083   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1084   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1085   DebugLoc DL = MI.getDebugLoc();
1086   Register SrcReg = MI.getOperand(0).getReg();
1087   bool IsKilled = MI.getOperand(0).isKill();
1088 
1089   bool IsPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1090   Register Reg =
1091       PPC::VSRp0 + (SrcReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1092   bool IsLittleEndian = Subtarget.isLittleEndian();
1093 
1094   emitAccSpillRestoreInfo(MBB, IsPrimed, false);
1095 
1096   // De-prime the register being spilled, create two stores for the pair
1097   // subregisters accounting for endianness and then re-prime the register if
1098   // it isn't killed.  This uses the Offset parameter to addFrameReference() to
1099   // adjust the offset of the store that is within the 64-byte stack slot.
1100   if (IsPrimed)
1101     BuildMI(MBB, II, DL, TII.get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1102   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1103                         .addReg(Reg, getKillRegState(IsKilled)),
1104                     FrameIndex, IsLittleEndian ? 32 : 0);
1105   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1106                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1107                     FrameIndex, IsLittleEndian ? 0 : 32);
1108   if (IsPrimed && !IsKilled)
1109     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1110 
1111   // Discard the pseudo instruction.
1112   MBB.erase(II);
1113 }
1114 
1115 /// lowerACCRestore - Generate the code to restore the accumulator register.
1116 void PPCRegisterInfo::lowerACCRestore(MachineBasicBlock::iterator II,
1117                                       unsigned FrameIndex) const {
1118   MachineInstr &MI = *II; // <DestReg> = RESTORE_ACC <offset>
1119   MachineBasicBlock &MBB = *MI.getParent();
1120   MachineFunction &MF = *MBB.getParent();
1121   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1122   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1123   DebugLoc DL = MI.getDebugLoc();
1124 
1125   Register DestReg = MI.getOperand(0).getReg();
1126   assert(MI.definesRegister(DestReg) &&
1127          "RESTORE_ACC does not define its destination");
1128 
1129   bool IsPrimed = PPC::ACCRCRegClass.contains(DestReg);
1130   Register Reg =
1131       PPC::VSRp0 + (DestReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1132   bool IsLittleEndian = Subtarget.isLittleEndian();
1133 
1134   emitAccSpillRestoreInfo(MBB, IsPrimed, true);
1135 
1136   // Create two loads for the pair subregisters accounting for endianness and
1137   // then prime the accumulator register being restored.
1138   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg),
1139                     FrameIndex, IsLittleEndian ? 32 : 0);
1140   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg + 1),
1141                     FrameIndex, IsLittleEndian ? 0 : 32);
1142   if (IsPrimed)
1143     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), DestReg).addReg(DestReg);
1144 
1145   // Discard the pseudo instruction.
1146   MBB.erase(II);
1147 }
1148 
1149 /// lowerQuadwordSpilling - Generate code to spill paired general register.
1150 void PPCRegisterInfo::lowerQuadwordSpilling(MachineBasicBlock::iterator II,
1151                                             unsigned FrameIndex) const {
1152   MachineInstr &MI = *II;
1153   MachineBasicBlock &MBB = *MI.getParent();
1154   MachineFunction &MF = *MBB.getParent();
1155   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1156   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1157   DebugLoc DL = MI.getDebugLoc();
1158 
1159   Register SrcReg = MI.getOperand(0).getReg();
1160   bool IsKilled = MI.getOperand(0).isKill();
1161 
1162   Register Reg = PPC::X0 + (SrcReg - PPC::G8p0) * 2;
1163   bool IsLittleEndian = Subtarget.isLittleEndian();
1164 
1165   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1166                         .addReg(Reg, getKillRegState(IsKilled)),
1167                     FrameIndex, IsLittleEndian ? 8 : 0);
1168   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1169                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1170                     FrameIndex, IsLittleEndian ? 0 : 8);
1171 
1172   // Discard the pseudo instruction.
1173   MBB.erase(II);
1174 }
1175 
1176 /// lowerQuadwordRestore - Generate code to restore paired general register.
1177 void PPCRegisterInfo::lowerQuadwordRestore(MachineBasicBlock::iterator II,
1178                                            unsigned FrameIndex) const {
1179   MachineInstr &MI = *II;
1180   MachineBasicBlock &MBB = *MI.getParent();
1181   MachineFunction &MF = *MBB.getParent();
1182   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1183   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1184   DebugLoc DL = MI.getDebugLoc();
1185 
1186   Register DestReg = MI.getOperand(0).getReg();
1187   assert(MI.definesRegister(DestReg) &&
1188          "RESTORE_QUADWORD does not define its destination");
1189 
1190   Register Reg = PPC::X0 + (DestReg - PPC::G8p0) * 2;
1191   bool IsLittleEndian = Subtarget.isLittleEndian();
1192 
1193   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg), FrameIndex,
1194                     IsLittleEndian ? 8 : 0);
1195   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg + 1), FrameIndex,
1196                     IsLittleEndian ? 0 : 8);
1197 
1198   // Discard the pseudo instruction.
1199   MBB.erase(II);
1200 }
1201 
1202 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
1203                                            Register Reg, int &FrameIdx) const {
1204   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
1205   // prevent allocating an additional frame slot.
1206   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
1207   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
1208   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
1209   // valid.
1210   // For 32-bit ELF, we have previously created the stack slot if needed, so
1211   // return its FrameIdx.
1212   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
1213     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
1214     return true;
1215   }
1216   return false;
1217 }
1218 
1219 // If the offset must be a multiple of some value, return what that value is.
1220 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
1221   switch (OpC) {
1222   default:
1223     return 1;
1224   case PPC::LWA:
1225   case PPC::LWA_32:
1226   case PPC::LD:
1227   case PPC::LDU:
1228   case PPC::STD:
1229   case PPC::STDU:
1230   case PPC::DFLOADf32:
1231   case PPC::DFLOADf64:
1232   case PPC::DFSTOREf32:
1233   case PPC::DFSTOREf64:
1234   case PPC::LXSD:
1235   case PPC::LXSSP:
1236   case PPC::STXSD:
1237   case PPC::STXSSP:
1238   case PPC::STQ:
1239     return 4;
1240   case PPC::EVLDD:
1241   case PPC::EVSTDD:
1242     return 8;
1243   case PPC::LXV:
1244   case PPC::STXV:
1245   case PPC::LQ:
1246     return 16;
1247   }
1248 }
1249 
1250 // If the offset must be a multiple of some value, return what that value is.
1251 static unsigned offsetMinAlign(const MachineInstr &MI) {
1252   unsigned OpC = MI.getOpcode();
1253   return offsetMinAlignForOpcode(OpC);
1254 }
1255 
1256 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
1257 static unsigned getOffsetONFromFION(const MachineInstr &MI,
1258                                     unsigned FIOperandNum) {
1259   // Take into account whether it's an add or mem instruction
1260   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1261   if (MI.isInlineAsm())
1262     OffsetOperandNo = FIOperandNum - 1;
1263   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1264            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1265     OffsetOperandNo = FIOperandNum + 1;
1266 
1267   return OffsetOperandNo;
1268 }
1269 
1270 void
1271 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1272                                      int SPAdj, unsigned FIOperandNum,
1273                                      RegScavenger *RS) const {
1274   assert(SPAdj == 0 && "Unexpected");
1275 
1276   // Get the instruction.
1277   MachineInstr &MI = *II;
1278   // Get the instruction's basic block.
1279   MachineBasicBlock &MBB = *MI.getParent();
1280   // Get the basic block's function.
1281   MachineFunction &MF = *MBB.getParent();
1282   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1283   // Get the instruction info.
1284   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1285   // Get the frame info.
1286   MachineFrameInfo &MFI = MF.getFrameInfo();
1287   DebugLoc dl = MI.getDebugLoc();
1288 
1289   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1290 
1291   // Get the frame index.
1292   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1293 
1294   // Get the frame pointer save index.  Users of this index are primarily
1295   // DYNALLOC instructions.
1296   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1297   int FPSI = FI->getFramePointerSaveIndex();
1298   // Get the instruction opcode.
1299   unsigned OpC = MI.getOpcode();
1300 
1301   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1302     lowerDynamicAreaOffset(II);
1303     return;
1304   }
1305 
1306   // Special case for dynamic alloca.
1307   if (FPSI && FrameIndex == FPSI &&
1308       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1309     lowerDynamicAlloc(II);
1310     return;
1311   }
1312 
1313   if (FPSI && FrameIndex == FPSI &&
1314       (OpC == PPC::PREPARE_PROBED_ALLOCA_64 ||
1315        OpC == PPC::PREPARE_PROBED_ALLOCA_32 ||
1316        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 ||
1317        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32)) {
1318     lowerPrepareProbedAlloca(II);
1319     return;
1320   }
1321 
1322   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1323   if (OpC == PPC::SPILL_CR) {
1324     lowerCRSpilling(II, FrameIndex);
1325     return;
1326   } else if (OpC == PPC::RESTORE_CR) {
1327     lowerCRRestore(II, FrameIndex);
1328     return;
1329   } else if (OpC == PPC::SPILL_CRBIT) {
1330     lowerCRBitSpilling(II, FrameIndex);
1331     return;
1332   } else if (OpC == PPC::RESTORE_CRBIT) {
1333     lowerCRBitRestore(II, FrameIndex);
1334     return;
1335   } else if (OpC == PPC::SPILL_ACC || OpC == PPC::SPILL_UACC) {
1336     lowerACCSpilling(II, FrameIndex);
1337     return;
1338   } else if (OpC == PPC::RESTORE_ACC || OpC == PPC::RESTORE_UACC) {
1339     lowerACCRestore(II, FrameIndex);
1340     return;
1341   } else if (OpC == PPC::SPILL_QUADWORD) {
1342     lowerQuadwordSpilling(II, FrameIndex);
1343     return;
1344   } else if (OpC == PPC::RESTORE_QUADWORD) {
1345     lowerQuadwordRestore(II, FrameIndex);
1346     return;
1347   }
1348 
1349   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1350   MI.getOperand(FIOperandNum).ChangeToRegister(
1351     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1352 
1353   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1354   // form (and must be r+r).
1355   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1356                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1357 
1358   // Now add the frame object offset to the offset from r1.
1359   int Offset = MFI.getObjectOffset(FrameIndex);
1360   Offset += MI.getOperand(OffsetOperandNo).getImm();
1361 
1362   // If we're not using a Frame Pointer that has been set to the value of the
1363   // SP before having the stack size subtracted from it, then add the stack size
1364   // to Offset to get the correct offset.
1365   // Naked functions have stack size 0, although getStackSize may not reflect
1366   // that because we didn't call all the pieces that compute it for naked
1367   // functions.
1368   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1369     if (!(hasBasePointer(MF) && FrameIndex < 0))
1370       Offset += MFI.getStackSize();
1371   }
1372 
1373   // If we can, encode the offset directly into the instruction.  If this is a
1374   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1375   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1376   // clear can be encoded.  This is extremely uncommon, because normally you
1377   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1378   // happen in invalid code.
1379   assert(OpC != PPC::DBG_VALUE &&
1380          "This should be handled in a target-independent way");
1381   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1382                             isUInt<8>(Offset) :
1383                             isInt<16>(Offset);
1384   if (!noImmForm && ((OffsetFitsMnemonic &&
1385                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1386                      OpC == TargetOpcode::STACKMAP ||
1387                      OpC == TargetOpcode::PATCHPOINT)) {
1388     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1389     return;
1390   }
1391 
1392   // The offset doesn't fit into a single register, scavenge one to build the
1393   // offset in.
1394 
1395   bool is64Bit = TM.isPPC64();
1396   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1397   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1398   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1399   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1400            SReg = MF.getRegInfo().createVirtualRegister(RC);
1401 
1402   // Insert a set of rA with the full offset value before the ld, st, or add
1403   if (isInt<16>(Offset))
1404     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1405       .addImm(Offset);
1406   else {
1407     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1408       .addImm(Offset >> 16);
1409     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1410       .addReg(SRegHi, RegState::Kill)
1411       .addImm(Offset);
1412   }
1413 
1414   // Convert into indexed form of the instruction:
1415   //
1416   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1417   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1418   unsigned OperandBase;
1419 
1420   if (noImmForm)
1421     OperandBase = 1;
1422   else if (OpC != TargetOpcode::INLINEASM &&
1423            OpC != TargetOpcode::INLINEASM_BR) {
1424     assert(ImmToIdxMap.count(OpC) &&
1425            "No indexed form of load or store available!");
1426     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1427     MI.setDesc(TII.get(NewOpcode));
1428     OperandBase = 1;
1429   } else {
1430     OperandBase = OffsetOperandNo;
1431   }
1432 
1433   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1434   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1435   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1436 }
1437 
1438 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1439   const PPCFrameLowering *TFI = getFrameLowering(MF);
1440 
1441   if (!TM.isPPC64())
1442     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1443   else
1444     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1445 }
1446 
1447 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1448   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1449   if (!hasBasePointer(MF))
1450     return getFrameRegister(MF);
1451 
1452   if (TM.isPPC64())
1453     return PPC::X30;
1454 
1455   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1456     return PPC::R29;
1457 
1458   return PPC::R30;
1459 }
1460 
1461 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1462   if (!EnableBasePointer)
1463     return false;
1464   if (AlwaysBasePointer)
1465     return true;
1466 
1467   // If we need to realign the stack, then the stack pointer can no longer
1468   // serve as an offset into the caller's stack space. As a result, we need a
1469   // base pointer.
1470   return hasStackRealignment(MF);
1471 }
1472 
1473 /// Returns true if the instruction's frame index
1474 /// reference would be better served by a base register other than FP
1475 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1476 /// references it should create new base registers for.
1477 bool PPCRegisterInfo::
1478 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1479   assert(Offset < 0 && "Local offset must be negative");
1480 
1481   // It's the load/store FI references that cause issues, as it can be difficult
1482   // to materialize the offset if it won't fit in the literal field. Estimate
1483   // based on the size of the local frame and some conservative assumptions
1484   // about the rest of the stack frame (note, this is pre-regalloc, so
1485   // we don't know everything for certain yet) whether this offset is likely
1486   // to be out of range of the immediate. Return true if so.
1487 
1488   // We only generate virtual base registers for loads and stores that have
1489   // an r+i form. Return false for everything else.
1490   unsigned OpC = MI->getOpcode();
1491   if (!ImmToIdxMap.count(OpC))
1492     return false;
1493 
1494   // Don't generate a new virtual base register just to add zero to it.
1495   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1496       MI->getOperand(2).getImm() == 0)
1497     return false;
1498 
1499   MachineBasicBlock &MBB = *MI->getParent();
1500   MachineFunction &MF = *MBB.getParent();
1501   const PPCFrameLowering *TFI = getFrameLowering(MF);
1502   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1503 
1504   // If we likely don't need a stack frame, then we probably don't need a
1505   // virtual base register either.
1506   if (!StackEst)
1507     return false;
1508 
1509   // Estimate an offset from the stack pointer.
1510   // The incoming offset is relating to the SP at the start of the function,
1511   // but when we access the local it'll be relative to the SP after local
1512   // allocation, so adjust our SP-relative offset by that allocation size.
1513   Offset += StackEst;
1514 
1515   // The frame pointer will point to the end of the stack, so estimate the
1516   // offset as the difference between the object offset and the FP location.
1517   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1518 }
1519 
1520 /// Insert defining instruction(s) for BaseReg to
1521 /// be a pointer to FrameIdx at the beginning of the basic block.
1522 Register PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1523                                                        int FrameIdx,
1524                                                        int64_t Offset) const {
1525   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1526 
1527   MachineBasicBlock::iterator Ins = MBB->begin();
1528   DebugLoc DL;                  // Defaults to "unknown"
1529   if (Ins != MBB->end())
1530     DL = Ins->getDebugLoc();
1531 
1532   const MachineFunction &MF = *MBB->getParent();
1533   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1534   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1535   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1536   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1537   const TargetRegisterClass *RC = getPointerRegClass(MF);
1538   Register BaseReg = MRI.createVirtualRegister(RC);
1539   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1540 
1541   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1542     .addFrameIndex(FrameIdx).addImm(Offset);
1543 
1544   return BaseReg;
1545 }
1546 
1547 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1548                                         int64_t Offset) const {
1549   unsigned FIOperandNum = 0;
1550   while (!MI.getOperand(FIOperandNum).isFI()) {
1551     ++FIOperandNum;
1552     assert(FIOperandNum < MI.getNumOperands() &&
1553            "Instr doesn't have FrameIndex operand!");
1554   }
1555 
1556   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1557   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1558   Offset += MI.getOperand(OffsetOperandNo).getImm();
1559   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1560 
1561   MachineBasicBlock &MBB = *MI.getParent();
1562   MachineFunction &MF = *MBB.getParent();
1563   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1564   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1565   const MCInstrDesc &MCID = MI.getDesc();
1566   MachineRegisterInfo &MRI = MF.getRegInfo();
1567   MRI.constrainRegClass(BaseReg,
1568                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1569 }
1570 
1571 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1572                                          Register BaseReg,
1573                                          int64_t Offset) const {
1574   unsigned FIOperandNum = 0;
1575   while (!MI->getOperand(FIOperandNum).isFI()) {
1576     ++FIOperandNum;
1577     assert(FIOperandNum < MI->getNumOperands() &&
1578            "Instr doesn't have FrameIndex operand!");
1579   }
1580 
1581   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1582   Offset += MI->getOperand(OffsetOperandNo).getImm();
1583 
1584   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1585          MI->getOpcode() == TargetOpcode::STACKMAP ||
1586          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1587          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1588 }
1589