xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision d98e5e02adb5c37f892c51a6f1264179c5d32531)
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   // If the callee saved info is invalid we have to default to true for safety.
377   if (!MFI.isCalleeSavedInfoValid())
378     return true;
379 
380   // We will require the use of X-Forms because the frame is larger than what
381   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
382   // If we need an X-Form then we need a register to store the address offset.
383   unsigned FrameSize = MFI.getStackSize();
384   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
385   if (FrameSize & ~0x7FFF)
386     return true;
387 
388   // The callee saved info is valid so it can be traversed.
389   // Checking for registers that need saving that do not have load or store
390   // forms where the address offset is an immediate.
391   for (unsigned i = 0; i < Info.size(); i++) {
392     int FrIdx = Info[i].getFrameIdx();
393     unsigned Reg = Info[i].getReg();
394 
395     const TargetRegisterClass *RC = getMinimalPhysRegClass(Reg);
396     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(RC);
397     if (!MFI.isFixedObjectIndex(FrIdx)) {
398       // This is not a fixed object. If it requires alignment then we may still
399       // need to use the XForm.
400       if (offsetMinAlignForOpcode(Opcode) > 1)
401         return true;
402     }
403 
404     // This is eiher:
405     // 1) A fixed frame index object which we know are aligned so
406     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
407     // need to consider the alignment here.
408     // 2) A not fixed object but in that case we now know that the min required
409     // alignment is no more than 1 based on the previous check.
410     if (InstrInfo->isXFormMemOp(Opcode))
411       return true;
412   }
413   return false;
414 }
415 
416 bool PPCRegisterInfo::isCallerPreservedPhysReg(MCRegister PhysReg,
417                                                const MachineFunction &MF) const {
418   assert(Register::isPhysicalRegister(PhysReg));
419   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
420   const MachineFrameInfo &MFI = MF.getFrameInfo();
421 
422   if (!Subtarget.is64BitELFABI() && !Subtarget.isAIXABI())
423     return false;
424   if (PhysReg == Subtarget.getTOCPointerRegister())
425     // X2/R2 is guaranteed to be preserved within a function if it is reserved.
426     // The reason it's reserved is that it's the TOC pointer (and the function
427     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
428     // with no TOC access), we can't claim that it is preserved.
429     return (getReservedRegs(MF).test(PhysReg));
430   if (StackPtrConst && PhysReg == Subtarget.getStackPointerRegister() &&
431       !MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
432     // The value of the stack pointer does not change within a function after
433     // the prologue and before the epilogue if there are no dynamic allocations
434     // and no inline asm which clobbers X1/R1.
435     return true;
436   return false;
437 }
438 
439 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
440                                               MachineFunction &MF) const {
441   const PPCFrameLowering *TFI = getFrameLowering(MF);
442   const unsigned DefaultSafety = 1;
443 
444   switch (RC->getID()) {
445   default:
446     return 0;
447   case PPC::G8RC_NOX0RegClassID:
448   case PPC::GPRC_NOR0RegClassID:
449   case PPC::SPERCRegClassID:
450   case PPC::G8RCRegClassID:
451   case PPC::GPRCRegClassID: {
452     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
453     return 32 - FP - DefaultSafety;
454   }
455   case PPC::F4RCRegClassID:
456   case PPC::F8RCRegClassID:
457   case PPC::VSLRCRegClassID:
458     return 32 - DefaultSafety;
459   case PPC::VFRCRegClassID:
460   case PPC::VRRCRegClassID: {
461     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
462     // Vector registers VR20-VR31 are reserved and cannot be used in the default
463     // Altivec ABI on AIX.
464     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
465       return 20 - DefaultSafety;
466   }
467     return 32 - DefaultSafety;
468   case PPC::VSFRCRegClassID:
469   case PPC::VSSRCRegClassID:
470   case PPC::VSRCRegClassID: {
471     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
472     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
473       // Vector registers VR20-VR31 are reserved and cannot be used in the
474       // default Altivec ABI on AIX.
475       return 52 - DefaultSafety;
476   }
477     return 64 - DefaultSafety;
478   case PPC::CRRCRegClassID:
479     return 8 - DefaultSafety;
480   }
481 }
482 
483 const TargetRegisterClass *
484 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
485                                            const MachineFunction &MF) const {
486   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
487   if (Subtarget.hasVSX()) {
488     // With VSX, we can inflate various sub-register classes to the full VSX
489     // register set.
490 
491     // For Power9 we allow the user to enable GPR to vector spills.
492     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
493     // support to spill GPRC.
494     if (TM.isELFv2ABI() || Subtarget.isAIXABI()) {
495       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
496           RC == &PPC::G8RCRegClass) {
497         InflateGP8RC++;
498         return &PPC::SPILLTOVSRRCRegClass;
499       }
500       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
501         InflateGPRC++;
502     }
503     if (RC == &PPC::F8RCRegClass)
504       return &PPC::VSFRCRegClass;
505     else if (RC == &PPC::VRRCRegClass)
506       return &PPC::VSRCRegClass;
507     else if (RC == &PPC::F4RCRegClass && Subtarget.hasP8Vector())
508       return &PPC::VSSRCRegClass;
509   }
510 
511   return TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
512 }
513 
514 //===----------------------------------------------------------------------===//
515 // Stack Frame Processing methods
516 //===----------------------------------------------------------------------===//
517 
518 /// lowerDynamicAlloc - Generate the code for allocating an object in the
519 /// current frame.  The sequence of code will be in the general form
520 ///
521 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
522 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
523 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
524 ///
525 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
526   // Get the instruction.
527   MachineInstr &MI = *II;
528   // Get the instruction's basic block.
529   MachineBasicBlock &MBB = *MI.getParent();
530   // Get the basic block's function.
531   MachineFunction &MF = *MBB.getParent();
532   // Get the frame info.
533   MachineFrameInfo &MFI = MF.getFrameInfo();
534   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
535   // Get the instruction info.
536   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
537   // Determine whether 64-bit pointers are used.
538   bool LP64 = TM.isPPC64();
539   DebugLoc dl = MI.getDebugLoc();
540 
541   // Get the maximum call stack size.
542   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
543   Align MaxAlign = MFI.getMaxAlign();
544   assert(isAligned(MaxAlign, maxCallFrameSize) &&
545          "Maximum call-frame size not sufficiently aligned");
546   (void)MaxAlign;
547 
548   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
549   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
550   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
551   bool KillNegSizeReg = MI.getOperand(1).isKill();
552   Register NegSizeReg = MI.getOperand(1).getReg();
553 
554   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
555   // Grow the stack and update the stack pointer link, then determine the
556   // address of new allocated space.
557   if (LP64) {
558     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
559         .addReg(Reg, RegState::Kill)
560         .addReg(PPC::X1)
561         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
562     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
563         .addReg(PPC::X1)
564         .addImm(maxCallFrameSize);
565   } else {
566     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
567         .addReg(Reg, RegState::Kill)
568         .addReg(PPC::R1)
569         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
570     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
571         .addReg(PPC::R1)
572         .addImm(maxCallFrameSize);
573   }
574 
575   // Discard the DYNALLOC instruction.
576   MBB.erase(II);
577 }
578 
579 /// To accomplish dynamic stack allocation, we have to calculate exact size
580 /// subtracted from the stack pointer according alignment information and get
581 /// previous frame pointer.
582 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
583                                            Register &NegSizeReg,
584                                            bool &KillNegSizeReg,
585                                            Register &FramePointer) const {
586   // Get the instruction.
587   MachineInstr &MI = *II;
588   // Get the instruction's basic block.
589   MachineBasicBlock &MBB = *MI.getParent();
590   // Get the basic block's function.
591   MachineFunction &MF = *MBB.getParent();
592   // Get the frame info.
593   MachineFrameInfo &MFI = MF.getFrameInfo();
594   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
595   // Get the instruction info.
596   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
597   // Determine whether 64-bit pointers are used.
598   bool LP64 = TM.isPPC64();
599   DebugLoc dl = MI.getDebugLoc();
600   // Get the total frame size.
601   unsigned FrameSize = MFI.getStackSize();
602 
603   // Get stack alignments.
604   const PPCFrameLowering *TFI = getFrameLowering(MF);
605   Align TargetAlign = TFI->getStackAlign();
606   Align MaxAlign = MFI.getMaxAlign();
607 
608   // Determine the previous frame's address.  If FrameSize can't be
609   // represented as 16 bits or we need special alignment, then we load the
610   // previous frame's address from 0(SP).  Why not do an addis of the hi?
611   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
612   // Constructing the constant and adding would take 3 instructions.
613   // Fortunately, a frame greater than 32K is rare.
614   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
615   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
616 
617   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
618     if (LP64)
619       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
620           .addReg(PPC::X31)
621           .addImm(FrameSize);
622     else
623       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
624           .addReg(PPC::R31)
625           .addImm(FrameSize);
626   } else if (LP64) {
627     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
628         .addImm(0)
629         .addReg(PPC::X1);
630   } else {
631     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
632         .addImm(0)
633         .addReg(PPC::R1);
634   }
635   // Determine the actual NegSizeReg according to alignment info.
636   if (LP64) {
637     if (MaxAlign > TargetAlign) {
638       unsigned UnalNegSizeReg = NegSizeReg;
639       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
640 
641       // Unfortunately, there is no andi, only andi., and we can't insert that
642       // here because we might clobber cr0 while it is live.
643       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
644           .addImm(~(MaxAlign.value() - 1));
645 
646       unsigned NegSizeReg1 = NegSizeReg;
647       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
648       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
649           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
650           .addReg(NegSizeReg1, RegState::Kill);
651       KillNegSizeReg = true;
652     }
653   } else {
654     if (MaxAlign > TargetAlign) {
655       unsigned UnalNegSizeReg = NegSizeReg;
656       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
657 
658       // Unfortunately, there is no andi, only andi., and we can't insert that
659       // here because we might clobber cr0 while it is live.
660       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
661           .addImm(~(MaxAlign.value() - 1));
662 
663       unsigned NegSizeReg1 = NegSizeReg;
664       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
665       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
666           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
667           .addReg(NegSizeReg1, RegState::Kill);
668       KillNegSizeReg = true;
669     }
670   }
671 }
672 
673 void PPCRegisterInfo::lowerPrepareProbedAlloca(
674     MachineBasicBlock::iterator II) const {
675   MachineInstr &MI = *II;
676   // Get the instruction's basic block.
677   MachineBasicBlock &MBB = *MI.getParent();
678   // Get the basic block's function.
679   MachineFunction &MF = *MBB.getParent();
680   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
681   // Get the instruction info.
682   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
683   // Determine whether 64-bit pointers are used.
684   bool LP64 = TM.isPPC64();
685   DebugLoc dl = MI.getDebugLoc();
686   Register FramePointer = MI.getOperand(0).getReg();
687   const Register ActualNegSizeReg = MI.getOperand(1).getReg();
688   bool KillNegSizeReg = MI.getOperand(2).isKill();
689   Register NegSizeReg = MI.getOperand(2).getReg();
690   const MCInstrDesc &CopyInst = TII.get(LP64 ? PPC::OR8 : PPC::OR);
691   // RegAllocator might allocate FramePointer and NegSizeReg in the same phyreg.
692   if (FramePointer == NegSizeReg) {
693     assert(KillNegSizeReg && "FramePointer is a def and NegSizeReg is an use, "
694                              "NegSizeReg should be killed");
695     // FramePointer is clobbered earlier than the use of NegSizeReg in
696     // prepareDynamicAlloca, save NegSizeReg in ActualNegSizeReg to avoid
697     // misuse.
698     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
699         .addReg(NegSizeReg)
700         .addReg(NegSizeReg);
701     NegSizeReg = ActualNegSizeReg;
702     KillNegSizeReg = false;
703   }
704   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, FramePointer);
705   // NegSizeReg might be updated in prepareDynamicAlloca if MaxAlign >
706   // TargetAlign.
707   if (NegSizeReg != ActualNegSizeReg)
708     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
709         .addReg(NegSizeReg)
710         .addReg(NegSizeReg);
711   MBB.erase(II);
712 }
713 
714 void PPCRegisterInfo::lowerDynamicAreaOffset(
715     MachineBasicBlock::iterator II) const {
716   // Get the instruction.
717   MachineInstr &MI = *II;
718   // Get the instruction's basic block.
719   MachineBasicBlock &MBB = *MI.getParent();
720   // Get the basic block's function.
721   MachineFunction &MF = *MBB.getParent();
722   // Get the frame info.
723   MachineFrameInfo &MFI = MF.getFrameInfo();
724   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
725   // Get the instruction info.
726   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
727 
728   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
729   bool is64Bit = TM.isPPC64();
730   DebugLoc dl = MI.getDebugLoc();
731   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
732           MI.getOperand(0).getReg())
733       .addImm(maxCallFrameSize);
734   MBB.erase(II);
735 }
736 
737 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
738 /// reserving a whole register (R0), we scrounge for one here. This generates
739 /// code like this:
740 ///
741 ///   mfcr rA                  ; Move the conditional register into GPR rA.
742 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
743 ///   stw rA, FI               ; Store rA to the frame.
744 ///
745 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
746                                       unsigned FrameIndex) const {
747   // Get the instruction.
748   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
749   // Get the instruction's basic block.
750   MachineBasicBlock &MBB = *MI.getParent();
751   MachineFunction &MF = *MBB.getParent();
752   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
753   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
754   DebugLoc dl = MI.getDebugLoc();
755 
756   bool LP64 = TM.isPPC64();
757   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
758   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
759 
760   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
761   Register SrcReg = MI.getOperand(0).getReg();
762 
763   // We need to store the CR in the low 4-bits of the saved value. First, issue
764   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
765   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
766       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
767 
768   // If the saved register wasn't CR0, shift the bits left so that they are in
769   // CR0's slot.
770   if (SrcReg != PPC::CR0) {
771     Register Reg1 = Reg;
772     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
773 
774     // rlwinm rA, rA, ShiftBits, 0, 31.
775     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
776       .addReg(Reg1, RegState::Kill)
777       .addImm(getEncodingValue(SrcReg) * 4)
778       .addImm(0)
779       .addImm(31);
780   }
781 
782   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
783                     .addReg(Reg, RegState::Kill),
784                     FrameIndex);
785 
786   // Discard the pseudo instruction.
787   MBB.erase(II);
788 }
789 
790 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
791                                       unsigned FrameIndex) const {
792   // Get the instruction.
793   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
794   // Get the instruction's basic block.
795   MachineBasicBlock &MBB = *MI.getParent();
796   MachineFunction &MF = *MBB.getParent();
797   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
798   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
799   DebugLoc dl = MI.getDebugLoc();
800 
801   bool LP64 = TM.isPPC64();
802   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
803   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
804 
805   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
806   Register DestReg = MI.getOperand(0).getReg();
807   assert(MI.definesRegister(DestReg) &&
808     "RESTORE_CR does not define its destination");
809 
810   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
811                               Reg), FrameIndex);
812 
813   // If the reloaded register isn't CR0, shift the bits right so that they are
814   // in the right CR's slot.
815   if (DestReg != PPC::CR0) {
816     Register Reg1 = Reg;
817     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
818 
819     unsigned ShiftBits = getEncodingValue(DestReg)*4;
820     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
821     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
822              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
823              .addImm(31);
824   }
825 
826   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
827              .addReg(Reg, RegState::Kill);
828 
829   // Discard the pseudo instruction.
830   MBB.erase(II);
831 }
832 
833 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
834                                          unsigned FrameIndex) const {
835   // Get the instruction.
836   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
837   // Get the instruction's basic block.
838   MachineBasicBlock &MBB = *MI.getParent();
839   MachineFunction &MF = *MBB.getParent();
840   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
841   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
842   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
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 SrcReg = MI.getOperand(0).getReg();
851 
852   // Search up the BB to find the definition of the CR bit.
853   MachineBasicBlock::reverse_iterator Ins = MI;
854   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
855   ++Ins;
856   unsigned CRBitSpillDistance = 0;
857   bool SeenUse = false;
858   for (; Ins != Rend; ++Ins) {
859     // Definition found.
860     if (Ins->modifiesRegister(SrcReg, TRI))
861       break;
862     // Use found.
863     if (Ins->readsRegister(SrcReg, TRI))
864       SeenUse = true;
865     // Unable to find CR bit definition within maximum search distance.
866     if (CRBitSpillDistance == MaxCRBitSpillDist) {
867       Ins = MI;
868       break;
869     }
870     // Skip debug instructions when counting CR bit spill distance.
871     if (!Ins->isDebugInstr())
872       CRBitSpillDistance++;
873   }
874 
875   // Unable to find the definition of the CR bit in the MBB.
876   if (Ins == MBB.rend())
877     Ins = MI;
878 
879   bool SpillsKnownBit = false;
880   // There is no need to extract the CR bit if its value is already known.
881   switch (Ins->getOpcode()) {
882   case PPC::CRUNSET:
883     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
884       .addImm(0);
885     SpillsKnownBit = true;
886     break;
887   case PPC::CRSET:
888     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
889       .addImm(-32768);
890     SpillsKnownBit = true;
891     break;
892   default:
893     // On Power10, we can use SETNBC to spill all CR bits. SETNBC will set all
894     // bits (specifically, it produces a -1 if the CR bit is set). Ultimately,
895     // the bit that is of importance to us is bit 32 (bit 0 of a 32-bit
896     // register), and SETNBC will set this.
897     if (Subtarget.isISA3_1()) {
898       BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETNBC8 : PPC::SETNBC), Reg)
899           .addReg(SrcReg, RegState::Undef);
900       break;
901     }
902 
903     // On Power9, we can use SETB to extract the LT bit. This only works for
904     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
905     // of the bit we care about (32-bit sign bit) will be set to the value of
906     // the LT bit (regardless of the other bits in the CR field).
907     if (Subtarget.isISA3_0()) {
908       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
909           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
910           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
911           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
912         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
913           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
914         break;
915       }
916     }
917 
918     // We need to move the CR field that contains the CR bit we are spilling.
919     // The super register may not be explicitly defined (i.e. it can be defined
920     // by a CR-logical that only defines the subreg) so we state that the CR
921     // field is undef. Also, in order to preserve the kill flag on the CR bit,
922     // we add it as an implicit use.
923     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
924       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
925       .addReg(SrcReg,
926               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
927 
928     // If the saved register wasn't CR0LT, shift the bits left so that the bit
929     // to store is the first one. Mask all but that bit.
930     Register Reg1 = Reg;
931     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
932 
933     // rlwinm rA, rA, ShiftBits, 0, 0.
934     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
935       .addReg(Reg1, RegState::Kill)
936       .addImm(getEncodingValue(SrcReg))
937       .addImm(0).addImm(0);
938   }
939   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
940                     .addReg(Reg, RegState::Kill),
941                     FrameIndex);
942 
943   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
944   // Discard the pseudo instruction.
945   MBB.erase(II);
946   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
947     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
948     Ins->RemoveOperand(0);
949   }
950 }
951 
952 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
953                                       unsigned FrameIndex) const {
954   // Get the instruction.
955   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
956   // Get the instruction's basic block.
957   MachineBasicBlock &MBB = *MI.getParent();
958   MachineFunction &MF = *MBB.getParent();
959   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
960   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
961   DebugLoc dl = MI.getDebugLoc();
962 
963   bool LP64 = TM.isPPC64();
964   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
965   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
966 
967   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
968   Register DestReg = MI.getOperand(0).getReg();
969   assert(MI.definesRegister(DestReg) &&
970     "RESTORE_CRBIT does not define its destination");
971 
972   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
973                               Reg), FrameIndex);
974 
975   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
976 
977   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
978   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
979           .addReg(getCRFromCRBit(DestReg));
980 
981   unsigned ShiftBits = getEncodingValue(DestReg);
982   // rlwimi r11, r10, 32-ShiftBits, ..., ...
983   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
984       .addReg(RegO, RegState::Kill)
985       .addReg(Reg, RegState::Kill)
986       .addImm(ShiftBits ? 32 - ShiftBits : 0)
987       .addImm(ShiftBits)
988       .addImm(ShiftBits);
989 
990   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
991           getCRFromCRBit(DestReg))
992       .addReg(RegO, RegState::Kill)
993       // Make sure we have a use dependency all the way through this
994       // sequence of instructions. We can't have the other bits in the CR
995       // modified in between the mfocrf and the mtocrf.
996       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
997 
998   // Discard the pseudo instruction.
999   MBB.erase(II);
1000 }
1001 
1002 void PPCRegisterInfo::emitAccCopyInfo(MachineBasicBlock &MBB,
1003                                       MCRegister DestReg, MCRegister SrcReg) {
1004 #ifdef NDEBUG
1005   return;
1006 #else
1007   if (ReportAccMoves) {
1008     std::string Dest = PPC::ACCRCRegClass.contains(DestReg) ? "acc" : "uacc";
1009     std::string Src = PPC::ACCRCRegClass.contains(SrcReg) ? "acc" : "uacc";
1010     dbgs() << "Emitting copy from " << Src << " to " << Dest << ":\n";
1011     MBB.dump();
1012   }
1013 #endif
1014 }
1015 
1016 static void emitAccSpillRestoreInfo(MachineBasicBlock &MBB, bool IsPrimed,
1017                                     bool IsRestore) {
1018 #ifdef NDEBUG
1019   return;
1020 #else
1021   if (ReportAccMoves) {
1022     dbgs() << "Emitting " << (IsPrimed ? "acc" : "uacc") << " register "
1023            << (IsRestore ? "restore" : "spill") << ":\n";
1024     MBB.dump();
1025   }
1026 #endif
1027 }
1028 
1029 /// lowerACCSpilling - Generate the code for spilling the accumulator register.
1030 /// Similarly to other spills/reloads that use pseudo-ops, we do not actually
1031 /// eliminate the FrameIndex here nor compute the stack offset. We simply
1032 /// create a real instruction with an FI and rely on eliminateFrameIndex to
1033 /// handle the FI elimination.
1034 void PPCRegisterInfo::lowerACCSpilling(MachineBasicBlock::iterator II,
1035                                        unsigned FrameIndex) const {
1036   MachineInstr &MI = *II; // SPILL_ACC <SrcReg>, <offset>
1037   MachineBasicBlock &MBB = *MI.getParent();
1038   MachineFunction &MF = *MBB.getParent();
1039   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1040   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1041   DebugLoc DL = MI.getDebugLoc();
1042   Register SrcReg = MI.getOperand(0).getReg();
1043   bool IsKilled = MI.getOperand(0).isKill();
1044 
1045   bool IsPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1046   Register Reg =
1047       PPC::VSRp0 + (SrcReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1048   bool IsLittleEndian = Subtarget.isLittleEndian();
1049 
1050   emitAccSpillRestoreInfo(MBB, IsPrimed, false);
1051 
1052   // De-prime the register being spilled, create two stores for the pair
1053   // subregisters accounting for endianness and then re-prime the register if
1054   // it isn't killed.  This uses the Offset parameter to addFrameReference() to
1055   // adjust the offset of the store that is within the 64-byte stack slot.
1056   if (IsPrimed)
1057     BuildMI(MBB, II, DL, TII.get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1058   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1059                         .addReg(Reg, getKillRegState(IsKilled)),
1060                     FrameIndex, IsLittleEndian ? 32 : 0);
1061   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1062                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1063                     FrameIndex, IsLittleEndian ? 0 : 32);
1064   if (IsPrimed && !IsKilled)
1065     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1066 
1067   // Discard the pseudo instruction.
1068   MBB.erase(II);
1069 }
1070 
1071 /// lowerACCRestore - Generate the code to restore the accumulator register.
1072 void PPCRegisterInfo::lowerACCRestore(MachineBasicBlock::iterator II,
1073                                       unsigned FrameIndex) const {
1074   MachineInstr &MI = *II; // <DestReg> = RESTORE_ACC <offset>
1075   MachineBasicBlock &MBB = *MI.getParent();
1076   MachineFunction &MF = *MBB.getParent();
1077   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1078   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1079   DebugLoc DL = MI.getDebugLoc();
1080 
1081   Register DestReg = MI.getOperand(0).getReg();
1082   assert(MI.definesRegister(DestReg) &&
1083          "RESTORE_ACC does not define its destination");
1084 
1085   bool IsPrimed = PPC::ACCRCRegClass.contains(DestReg);
1086   Register Reg =
1087       PPC::VSRp0 + (DestReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1088   bool IsLittleEndian = Subtarget.isLittleEndian();
1089 
1090   emitAccSpillRestoreInfo(MBB, IsPrimed, true);
1091 
1092   // Create two loads for the pair subregisters accounting for endianness and
1093   // then prime the accumulator register being restored.
1094   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg),
1095                     FrameIndex, IsLittleEndian ? 32 : 0);
1096   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg + 1),
1097                     FrameIndex, IsLittleEndian ? 0 : 32);
1098   if (IsPrimed)
1099     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), DestReg).addReg(DestReg);
1100 
1101   // Discard the pseudo instruction.
1102   MBB.erase(II);
1103 }
1104 
1105 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
1106                                            Register Reg, int &FrameIdx) const {
1107   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
1108   // prevent allocating an additional frame slot.
1109   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
1110   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
1111   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
1112   // valid.
1113   // For 32-bit ELF, we have previously created the stack slot if needed, so
1114   // return its FrameIdx.
1115   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
1116     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
1117     return true;
1118   }
1119   return false;
1120 }
1121 
1122 // If the offset must be a multiple of some value, return what that value is.
1123 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
1124   switch (OpC) {
1125   default:
1126     return 1;
1127   case PPC::LWA:
1128   case PPC::LWA_32:
1129   case PPC::LD:
1130   case PPC::LDU:
1131   case PPC::STD:
1132   case PPC::STDU:
1133   case PPC::DFLOADf32:
1134   case PPC::DFLOADf64:
1135   case PPC::DFSTOREf32:
1136   case PPC::DFSTOREf64:
1137   case PPC::LXSD:
1138   case PPC::LXSSP:
1139   case PPC::STXSD:
1140   case PPC::STXSSP:
1141     return 4;
1142   case PPC::EVLDD:
1143   case PPC::EVSTDD:
1144     return 8;
1145   case PPC::LXV:
1146   case PPC::STXV:
1147     return 16;
1148   }
1149 }
1150 
1151 // If the offset must be a multiple of some value, return what that value is.
1152 static unsigned offsetMinAlign(const MachineInstr &MI) {
1153   unsigned OpC = MI.getOpcode();
1154   return offsetMinAlignForOpcode(OpC);
1155 }
1156 
1157 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
1158 static unsigned getOffsetONFromFION(const MachineInstr &MI,
1159                                     unsigned FIOperandNum) {
1160   // Take into account whether it's an add or mem instruction
1161   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1162   if (MI.isInlineAsm())
1163     OffsetOperandNo = FIOperandNum - 1;
1164   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1165            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1166     OffsetOperandNo = FIOperandNum + 1;
1167 
1168   return OffsetOperandNo;
1169 }
1170 
1171 void
1172 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1173                                      int SPAdj, unsigned FIOperandNum,
1174                                      RegScavenger *RS) const {
1175   assert(SPAdj == 0 && "Unexpected");
1176 
1177   // Get the instruction.
1178   MachineInstr &MI = *II;
1179   // Get the instruction's basic block.
1180   MachineBasicBlock &MBB = *MI.getParent();
1181   // Get the basic block's function.
1182   MachineFunction &MF = *MBB.getParent();
1183   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1184   // Get the instruction info.
1185   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1186   // Get the frame info.
1187   MachineFrameInfo &MFI = MF.getFrameInfo();
1188   DebugLoc dl = MI.getDebugLoc();
1189 
1190   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1191 
1192   // Get the frame index.
1193   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1194 
1195   // Get the frame pointer save index.  Users of this index are primarily
1196   // DYNALLOC instructions.
1197   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1198   int FPSI = FI->getFramePointerSaveIndex();
1199   // Get the instruction opcode.
1200   unsigned OpC = MI.getOpcode();
1201 
1202   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1203     lowerDynamicAreaOffset(II);
1204     return;
1205   }
1206 
1207   // Special case for dynamic alloca.
1208   if (FPSI && FrameIndex == FPSI &&
1209       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1210     lowerDynamicAlloc(II);
1211     return;
1212   }
1213 
1214   if (FPSI && FrameIndex == FPSI &&
1215       (OpC == PPC::PREPARE_PROBED_ALLOCA_64 ||
1216        OpC == PPC::PREPARE_PROBED_ALLOCA_32 ||
1217        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 ||
1218        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32)) {
1219     lowerPrepareProbedAlloca(II);
1220     return;
1221   }
1222 
1223   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1224   if (OpC == PPC::SPILL_CR) {
1225     lowerCRSpilling(II, FrameIndex);
1226     return;
1227   } else if (OpC == PPC::RESTORE_CR) {
1228     lowerCRRestore(II, FrameIndex);
1229     return;
1230   } else if (OpC == PPC::SPILL_CRBIT) {
1231     lowerCRBitSpilling(II, FrameIndex);
1232     return;
1233   } else if (OpC == PPC::RESTORE_CRBIT) {
1234     lowerCRBitRestore(II, FrameIndex);
1235     return;
1236   } else if (OpC == PPC::SPILL_ACC || OpC == PPC::SPILL_UACC) {
1237     lowerACCSpilling(II, FrameIndex);
1238     return;
1239   } else if (OpC == PPC::RESTORE_ACC || OpC == PPC::RESTORE_UACC) {
1240     lowerACCRestore(II, FrameIndex);
1241     return;
1242   }
1243 
1244   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1245   MI.getOperand(FIOperandNum).ChangeToRegister(
1246     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1247 
1248   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1249   // form (and must be r+r).
1250   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1251                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1252 
1253   // Now add the frame object offset to the offset from r1.
1254   int Offset = MFI.getObjectOffset(FrameIndex);
1255   Offset += MI.getOperand(OffsetOperandNo).getImm();
1256 
1257   // If we're not using a Frame Pointer that has been set to the value of the
1258   // SP before having the stack size subtracted from it, then add the stack size
1259   // to Offset to get the correct offset.
1260   // Naked functions have stack size 0, although getStackSize may not reflect
1261   // that because we didn't call all the pieces that compute it for naked
1262   // functions.
1263   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1264     if (!(hasBasePointer(MF) && FrameIndex < 0))
1265       Offset += MFI.getStackSize();
1266   }
1267 
1268   // If we can, encode the offset directly into the instruction.  If this is a
1269   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1270   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1271   // clear can be encoded.  This is extremely uncommon, because normally you
1272   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1273   // happen in invalid code.
1274   assert(OpC != PPC::DBG_VALUE &&
1275          "This should be handled in a target-independent way");
1276   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1277                             isUInt<8>(Offset) :
1278                             isInt<16>(Offset);
1279   if (!noImmForm && ((OffsetFitsMnemonic &&
1280                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1281                      OpC == TargetOpcode::STACKMAP ||
1282                      OpC == TargetOpcode::PATCHPOINT)) {
1283     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1284     return;
1285   }
1286 
1287   // The offset doesn't fit into a single register, scavenge one to build the
1288   // offset in.
1289 
1290   bool is64Bit = TM.isPPC64();
1291   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1292   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1293   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1294   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1295            SReg = MF.getRegInfo().createVirtualRegister(RC);
1296 
1297   // Insert a set of rA with the full offset value before the ld, st, or add
1298   if (isInt<16>(Offset))
1299     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1300       .addImm(Offset);
1301   else {
1302     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1303       .addImm(Offset >> 16);
1304     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1305       .addReg(SRegHi, RegState::Kill)
1306       .addImm(Offset);
1307   }
1308 
1309   // Convert into indexed form of the instruction:
1310   //
1311   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1312   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1313   unsigned OperandBase;
1314 
1315   if (noImmForm)
1316     OperandBase = 1;
1317   else if (OpC != TargetOpcode::INLINEASM &&
1318            OpC != TargetOpcode::INLINEASM_BR) {
1319     assert(ImmToIdxMap.count(OpC) &&
1320            "No indexed form of load or store available!");
1321     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1322     MI.setDesc(TII.get(NewOpcode));
1323     OperandBase = 1;
1324   } else {
1325     OperandBase = OffsetOperandNo;
1326   }
1327 
1328   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1329   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1330   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1331 }
1332 
1333 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1334   const PPCFrameLowering *TFI = getFrameLowering(MF);
1335 
1336   if (!TM.isPPC64())
1337     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1338   else
1339     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1340 }
1341 
1342 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1343   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1344   if (!hasBasePointer(MF))
1345     return getFrameRegister(MF);
1346 
1347   if (TM.isPPC64())
1348     return PPC::X30;
1349 
1350   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1351     return PPC::R29;
1352 
1353   return PPC::R30;
1354 }
1355 
1356 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1357   if (!EnableBasePointer)
1358     return false;
1359   if (AlwaysBasePointer)
1360     return true;
1361 
1362   // If we need to realign the stack, then the stack pointer can no longer
1363   // serve as an offset into the caller's stack space. As a result, we need a
1364   // base pointer.
1365   return hasStackRealignment(MF);
1366 }
1367 
1368 /// Returns true if the instruction's frame index
1369 /// reference would be better served by a base register other than FP
1370 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1371 /// references it should create new base registers for.
1372 bool PPCRegisterInfo::
1373 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1374   assert(Offset < 0 && "Local offset must be negative");
1375 
1376   // It's the load/store FI references that cause issues, as it can be difficult
1377   // to materialize the offset if it won't fit in the literal field. Estimate
1378   // based on the size of the local frame and some conservative assumptions
1379   // about the rest of the stack frame (note, this is pre-regalloc, so
1380   // we don't know everything for certain yet) whether this offset is likely
1381   // to be out of range of the immediate. Return true if so.
1382 
1383   // We only generate virtual base registers for loads and stores that have
1384   // an r+i form. Return false for everything else.
1385   unsigned OpC = MI->getOpcode();
1386   if (!ImmToIdxMap.count(OpC))
1387     return false;
1388 
1389   // Don't generate a new virtual base register just to add zero to it.
1390   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1391       MI->getOperand(2).getImm() == 0)
1392     return false;
1393 
1394   MachineBasicBlock &MBB = *MI->getParent();
1395   MachineFunction &MF = *MBB.getParent();
1396   const PPCFrameLowering *TFI = getFrameLowering(MF);
1397   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1398 
1399   // If we likely don't need a stack frame, then we probably don't need a
1400   // virtual base register either.
1401   if (!StackEst)
1402     return false;
1403 
1404   // Estimate an offset from the stack pointer.
1405   // The incoming offset is relating to the SP at the start of the function,
1406   // but when we access the local it'll be relative to the SP after local
1407   // allocation, so adjust our SP-relative offset by that allocation size.
1408   Offset += StackEst;
1409 
1410   // The frame pointer will point to the end of the stack, so estimate the
1411   // offset as the difference between the object offset and the FP location.
1412   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1413 }
1414 
1415 /// Insert defining instruction(s) for BaseReg to
1416 /// be a pointer to FrameIdx at the beginning of the basic block.
1417 Register PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1418                                                        int FrameIdx,
1419                                                        int64_t Offset) const {
1420   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1421 
1422   MachineBasicBlock::iterator Ins = MBB->begin();
1423   DebugLoc DL;                  // Defaults to "unknown"
1424   if (Ins != MBB->end())
1425     DL = Ins->getDebugLoc();
1426 
1427   const MachineFunction &MF = *MBB->getParent();
1428   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1429   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1430   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1431   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1432   const TargetRegisterClass *RC = getPointerRegClass(MF);
1433   Register BaseReg = MRI.createVirtualRegister(RC);
1434   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1435 
1436   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1437     .addFrameIndex(FrameIdx).addImm(Offset);
1438 
1439   return BaseReg;
1440 }
1441 
1442 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1443                                         int64_t Offset) const {
1444   unsigned FIOperandNum = 0;
1445   while (!MI.getOperand(FIOperandNum).isFI()) {
1446     ++FIOperandNum;
1447     assert(FIOperandNum < MI.getNumOperands() &&
1448            "Instr doesn't have FrameIndex operand!");
1449   }
1450 
1451   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1452   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1453   Offset += MI.getOperand(OffsetOperandNo).getImm();
1454   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1455 
1456   MachineBasicBlock &MBB = *MI.getParent();
1457   MachineFunction &MF = *MBB.getParent();
1458   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1459   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1460   const MCInstrDesc &MCID = MI.getDesc();
1461   MachineRegisterInfo &MRI = MF.getRegInfo();
1462   MRI.constrainRegClass(BaseReg,
1463                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1464 }
1465 
1466 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1467                                          Register BaseReg,
1468                                          int64_t Offset) const {
1469   unsigned FIOperandNum = 0;
1470   while (!MI->getOperand(FIOperandNum).isFI()) {
1471     ++FIOperandNum;
1472     assert(FIOperandNum < MI->getNumOperands() &&
1473            "Instr doesn't have FrameIndex operand!");
1474   }
1475 
1476   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1477   Offset += MI->getOperand(OffsetOperandNo).getImm();
1478 
1479   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1480          MI->getOpcode() == TargetOpcode::STACKMAP ||
1481          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1482          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1483 }
1484