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