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