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