1 //===-- PPCInstrInfo.cpp - PowerPC Instruction 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 TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCInstrInfo.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCHazardRecognizers.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/LiveIntervals.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/ScheduleDAG.h"
31 #include "llvm/CodeGen/SlotIndexes.h"
32 #include "llvm/CodeGen/StackMaps.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "ppc-instr-info"
44 
45 #define GET_INSTRMAP_INFO
46 #define GET_INSTRINFO_CTOR_DTOR
47 #include "PPCGenInstrInfo.inc"
48 
49 STATISTIC(NumStoreSPILLVSRRCAsVec,
50           "Number of spillvsrrc spilled to stack as vec");
51 STATISTIC(NumStoreSPILLVSRRCAsGpr,
52           "Number of spillvsrrc spilled to stack as gpr");
53 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
54 STATISTIC(CmpIselsConverted,
55           "Number of ISELs that depend on comparison of constants converted");
56 STATISTIC(MissedConvertibleImmediateInstrs,
57           "Number of compare-immediate instructions fed by constants");
58 STATISTIC(NumRcRotatesConvertedToRcAnd,
59           "Number of record-form rotates converted to record-form andi");
60 
61 static cl::
62 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
63             cl::desc("Disable analysis for CTR loops"));
64 
65 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
66 cl::desc("Disable compare instruction optimization"), cl::Hidden);
67 
68 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
69 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
70 cl::Hidden);
71 
72 static cl::opt<bool>
73 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
74   cl::desc("Use the old (incorrect) instruction latency calculation"));
75 
76 // Pin the vtable to this file.
77 void PPCInstrInfo::anchor() {}
78 
79 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
80     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
81                       /* CatchRetOpcode */ -1,
82                       STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
83       Subtarget(STI), RI(STI.getTargetMachine()) {}
84 
85 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
86 /// this target when scheduling the DAG.
87 ScheduleHazardRecognizer *
88 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
89                                            const ScheduleDAG *DAG) const {
90   unsigned Directive =
91       static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
92   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
93       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
94     const InstrItineraryData *II =
95         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
96     return new ScoreboardHazardRecognizer(II, DAG);
97   }
98 
99   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
100 }
101 
102 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
103 /// to use for this target when scheduling the DAG.
104 ScheduleHazardRecognizer *
105 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
106                                                  const ScheduleDAG *DAG) const {
107   unsigned Directive =
108       DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
109 
110   // FIXME: Leaving this as-is until we have POWER9 scheduling info
111   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
112     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
113 
114   // Most subtargets use a PPC970 recognizer.
115   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
116       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
117     assert(DAG->TII && "No InstrInfo?");
118 
119     return new PPCHazardRecognizer970(*DAG);
120   }
121 
122   return new ScoreboardHazardRecognizer(II, DAG);
123 }
124 
125 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
126                                        const MachineInstr &MI,
127                                        unsigned *PredCost) const {
128   if (!ItinData || UseOldLatencyCalc)
129     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
130 
131   // The default implementation of getInstrLatency calls getStageLatency, but
132   // getStageLatency does not do the right thing for us. While we have
133   // itinerary, most cores are fully pipelined, and so the itineraries only
134   // express the first part of the pipeline, not every stage. Instead, we need
135   // to use the listed output operand cycle number (using operand 0 here, which
136   // is an output).
137 
138   unsigned Latency = 1;
139   unsigned DefClass = MI.getDesc().getSchedClass();
140   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
141     const MachineOperand &MO = MI.getOperand(i);
142     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
143       continue;
144 
145     int Cycle = ItinData->getOperandCycle(DefClass, i);
146     if (Cycle < 0)
147       continue;
148 
149     Latency = std::max(Latency, (unsigned) Cycle);
150   }
151 
152   return Latency;
153 }
154 
155 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
156                                     const MachineInstr &DefMI, unsigned DefIdx,
157                                     const MachineInstr &UseMI,
158                                     unsigned UseIdx) const {
159   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
160                                                    UseMI, UseIdx);
161 
162   if (!DefMI.getParent())
163     return Latency;
164 
165   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
166   Register Reg = DefMO.getReg();
167 
168   bool IsRegCR;
169   if (Register::isVirtualRegister(Reg)) {
170     const MachineRegisterInfo *MRI =
171         &DefMI.getParent()->getParent()->getRegInfo();
172     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
173               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
174   } else {
175     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
176               PPC::CRBITRCRegClass.contains(Reg);
177   }
178 
179   if (UseMI.isBranch() && IsRegCR) {
180     if (Latency < 0)
181       Latency = getInstrLatency(ItinData, DefMI);
182 
183     // On some cores, there is an additional delay between writing to a condition
184     // register, and using it from a branch.
185     unsigned Directive = Subtarget.getCPUDirective();
186     switch (Directive) {
187     default: break;
188     case PPC::DIR_7400:
189     case PPC::DIR_750:
190     case PPC::DIR_970:
191     case PPC::DIR_E5500:
192     case PPC::DIR_PWR4:
193     case PPC::DIR_PWR5:
194     case PPC::DIR_PWR5X:
195     case PPC::DIR_PWR6:
196     case PPC::DIR_PWR6X:
197     case PPC::DIR_PWR7:
198     case PPC::DIR_PWR8:
199     // FIXME: Is this needed for POWER9?
200       Latency += 2;
201       break;
202     }
203   }
204 
205   return Latency;
206 }
207 
208 /// This is an architecture-specific helper function of reassociateOps.
209 /// Set special operand attributes for new instructions after reassociation.
210 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1,
211                                          MachineInstr &OldMI2,
212                                          MachineInstr &NewMI1,
213                                          MachineInstr &NewMI2) const {
214   // Propagate FP flags from the original instructions.
215   // But clear poison-generating flags because those may not be valid now.
216   uint16_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags();
217   NewMI1.setFlags(IntersectedFlags);
218   NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap);
219   NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap);
220   NewMI1.clearFlag(MachineInstr::MIFlag::IsExact);
221 
222   NewMI2.setFlags(IntersectedFlags);
223   NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap);
224   NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap);
225   NewMI2.clearFlag(MachineInstr::MIFlag::IsExact);
226 }
227 
228 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &MI,
229                                          uint16_t Flags) const {
230   MI.setFlags(Flags);
231   MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
232   MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
233   MI.clearFlag(MachineInstr::MIFlag::IsExact);
234 }
235 
236 // This function does not list all associative and commutative operations, but
237 // only those worth feeding through the machine combiner in an attempt to
238 // reduce the critical path. Mostly, this means floating-point operations,
239 // because they have high latencies(>=5) (compared to other operations, such as
240 // and/or, which are also associative and commutative, but have low latencies).
241 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
242   switch (Inst.getOpcode()) {
243   // Floating point:
244   // FP Add:
245   case PPC::FADD:
246   case PPC::FADDS:
247   // FP Multiply:
248   case PPC::FMUL:
249   case PPC::FMULS:
250   // Altivec Add:
251   case PPC::VADDFP:
252   // VSX Add:
253   case PPC::XSADDDP:
254   case PPC::XVADDDP:
255   case PPC::XVADDSP:
256   case PPC::XSADDSP:
257   // VSX Multiply:
258   case PPC::XSMULDP:
259   case PPC::XVMULDP:
260   case PPC::XVMULSP:
261   case PPC::XSMULSP:
262     return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) &&
263            Inst.getFlag(MachineInstr::MIFlag::FmNsz);
264   // Fixed point:
265   // Multiply:
266   case PPC::MULHD:
267   case PPC::MULLD:
268   case PPC::MULHW:
269   case PPC::MULLW:
270     return true;
271   default:
272     return false;
273   }
274 }
275 
276 #define InfoArrayIdxFMAInst 0
277 #define InfoArrayIdxFAddInst 1
278 #define InfoArrayIdxFMULInst 2
279 #define InfoArrayIdxAddOpIdx 3
280 #define InfoArrayIdxMULOpIdx 4
281 // Array keeps info for FMA instructions:
282 // Index 0(InfoArrayIdxFMAInst): FMA instruction;
283 // Index 1(InfoArrayIdxFAddInst): ADD instruction assoaicted with FMA;
284 // Index 2(InfoArrayIdxFMULInst): MUL instruction assoaicted with FMA;
285 // Index 3(InfoArrayIdxAddOpIdx): ADD operand index in FMA operands;
286 // Index 4(InfoArrayIdxMULOpIdx): first MUL operand index in FMA operands;
287 //                                second MUL operand index is plus 1.
288 static const uint16_t FMAOpIdxInfo[][5] = {
289     // FIXME: Add more FMA instructions like XSNMADDADP and so on.
290     {PPC::XSMADDADP, PPC::XSADDDP, PPC::XSMULDP, 1, 2},
291     {PPC::XSMADDASP, PPC::XSADDSP, PPC::XSMULSP, 1, 2},
292     {PPC::XVMADDADP, PPC::XVADDDP, PPC::XVMULDP, 1, 2},
293     {PPC::XVMADDASP, PPC::XVADDSP, PPC::XVMULSP, 1, 2},
294     {PPC::FMADD, PPC::FADD, PPC::FMUL, 3, 1},
295     {PPC::FMADDS, PPC::FADDS, PPC::FMULS, 3, 1}};
296 
297 // Check if an opcode is a FMA instruction. If it is, return the index in array
298 // FMAOpIdxInfo. Otherwise, return -1.
299 int16_t PPCInstrInfo::getFMAOpIdxInfo(unsigned Opcode) const {
300   for (unsigned I = 0; I < array_lengthof(FMAOpIdxInfo); I++)
301     if (FMAOpIdxInfo[I][InfoArrayIdxFMAInst] == Opcode)
302       return I;
303   return -1;
304 }
305 
306 // Try to reassociate FMA chains like below:
307 //
308 // Pattern 1:
309 //   A =  FADD X,  Y          (Leaf)
310 //   B =  FMA  A,  M21,  M22  (Prev)
311 //   C =  FMA  B,  M31,  M32  (Root)
312 // -->
313 //   A =  FMA  X,  M21,  M22
314 //   B =  FMA  Y,  M31,  M32
315 //   C =  FADD A,  B
316 //
317 // Pattern 2:
318 //   A =  FMA  X,  M11,  M12  (Leaf)
319 //   B =  FMA  A,  M21,  M22  (Prev)
320 //   C =  FMA  B,  M31,  M32  (Root)
321 // -->
322 //   A =  FMUL M11,  M12
323 //   B =  FMA  X,  M21,  M22
324 //   D =  FMA  A,  M31,  M32
325 //   C =  FADD B,  D
326 //
327 // breaking the dependency between A and B, allowing FMA to be executed in
328 // parallel (or back-to-back in a pipeline) instead of depending on each other.
329 bool PPCInstrInfo::getFMAPatterns(
330     MachineInstr &Root,
331     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
332   MachineBasicBlock *MBB = Root.getParent();
333   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
334 
335   auto IsAllOpsVirtualReg = [](const MachineInstr &Instr) {
336     for (const auto &MO : Instr.explicit_operands())
337       if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg())))
338         return false;
339     return true;
340   };
341 
342   auto IsReassociable = [&](const MachineInstr &Instr, int16_t &AddOpIdx,
343                             bool IsLeaf, bool IsAdd) {
344     int16_t Idx = -1;
345     if (!IsAdd) {
346       Idx = getFMAOpIdxInfo(Instr.getOpcode());
347       if (Idx < 0)
348         return false;
349     } else if (Instr.getOpcode() !=
350                FMAOpIdxInfo[getFMAOpIdxInfo(Root.getOpcode())]
351                            [InfoArrayIdxFAddInst])
352       return false;
353 
354     // Instruction can be reassociated.
355     // fast math flags may prohibit reassociation.
356     if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) &&
357           Instr.getFlag(MachineInstr::MIFlag::FmNsz)))
358       return false;
359 
360     // Instruction operands are virtual registers for reassociation.
361     if (!IsAllOpsVirtualReg(Instr))
362       return false;
363 
364     if (IsAdd && IsLeaf)
365       return true;
366 
367     AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
368 
369     const MachineOperand &OpAdd = Instr.getOperand(AddOpIdx);
370     MachineInstr *MIAdd = MRI.getUniqueVRegDef(OpAdd.getReg());
371     // If 'add' operand's def is not in current block, don't do ILP related opt.
372     if (!MIAdd || MIAdd->getParent() != MBB)
373       return false;
374 
375     // If this is not Leaf FMA Instr, its 'add' operand should only have one use
376     // as this fma will be changed later.
377     return IsLeaf ? true : MRI.hasOneNonDBGUse(OpAdd.getReg());
378   };
379 
380   int16_t AddOpIdx = -1;
381   // Root must be a valid FMA like instruction.
382   if (!IsReassociable(Root, AddOpIdx, false, false))
383     return false;
384 
385   assert((AddOpIdx >= 0) && "add operand index not right!");
386 
387   Register RegB = Root.getOperand(AddOpIdx).getReg();
388   MachineInstr *Prev = MRI.getUniqueVRegDef(RegB);
389 
390   // Prev must be a valid FMA like instruction.
391   AddOpIdx = -1;
392   if (!IsReassociable(*Prev, AddOpIdx, false, false))
393     return false;
394 
395   assert((AddOpIdx >= 0) && "add operand index not right!");
396 
397   Register RegA = Prev->getOperand(AddOpIdx).getReg();
398   MachineInstr *Leaf = MRI.getUniqueVRegDef(RegA);
399   AddOpIdx = -1;
400   if (IsReassociable(*Leaf, AddOpIdx, true, false)) {
401     Patterns.push_back(MachineCombinerPattern::REASSOC_XMM_AMM_BMM);
402     return true;
403   }
404   if (IsReassociable(*Leaf, AddOpIdx, true, true)) {
405     Patterns.push_back(MachineCombinerPattern::REASSOC_XY_AMM_BMM);
406     return true;
407   }
408   return false;
409 }
410 
411 bool PPCInstrInfo::getMachineCombinerPatterns(
412     MachineInstr &Root,
413     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
414   // Using the machine combiner in this way is potentially expensive, so
415   // restrict to when aggressive optimizations are desired.
416   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
417     return false;
418 
419   if (getFMAPatterns(Root, Patterns))
420     return true;
421 
422   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
423 }
424 
425 void PPCInstrInfo::genAlternativeCodeSequence(
426     MachineInstr &Root, MachineCombinerPattern Pattern,
427     SmallVectorImpl<MachineInstr *> &InsInstrs,
428     SmallVectorImpl<MachineInstr *> &DelInstrs,
429     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
430   switch (Pattern) {
431   case MachineCombinerPattern::REASSOC_XY_AMM_BMM:
432   case MachineCombinerPattern::REASSOC_XMM_AMM_BMM:
433     reassociateFMA(Root, Pattern, InsInstrs, DelInstrs, InstrIdxForVirtReg);
434     break;
435   default:
436     // Reassociate default patterns.
437     TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
438                                                 DelInstrs, InstrIdxForVirtReg);
439     break;
440   }
441 }
442 
443 // Currently, only handle two patterns REASSOC_XY_AMM_BMM and
444 // REASSOC_XMM_AMM_BMM. See comments for getFMAPatterns.
445 void PPCInstrInfo::reassociateFMA(
446     MachineInstr &Root, MachineCombinerPattern Pattern,
447     SmallVectorImpl<MachineInstr *> &InsInstrs,
448     SmallVectorImpl<MachineInstr *> &DelInstrs,
449     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
450   MachineFunction *MF = Root.getMF();
451   MachineRegisterInfo &MRI = MF->getRegInfo();
452   MachineOperand &OpC = Root.getOperand(0);
453   Register RegC = OpC.getReg();
454   const TargetRegisterClass *RC = MRI.getRegClass(RegC);
455   MRI.constrainRegClass(RegC, RC);
456 
457   unsigned FmaOp = Root.getOpcode();
458   int16_t Idx = getFMAOpIdxInfo(FmaOp);
459   assert(Idx >= 0 && "Root must be a FMA instruction");
460 
461   uint16_t AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
462   uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
463   MachineInstr *Prev = MRI.getUniqueVRegDef(Root.getOperand(AddOpIdx).getReg());
464   MachineInstr *Leaf =
465       MRI.getUniqueVRegDef(Prev->getOperand(AddOpIdx).getReg());
466   uint16_t IntersectedFlags =
467       Root.getFlags() & Prev->getFlags() & Leaf->getFlags();
468 
469   auto GetOperandInfo = [&](const MachineOperand &Operand, Register &Reg,
470                             bool &KillFlag) {
471     Reg = Operand.getReg();
472     MRI.constrainRegClass(Reg, RC);
473     KillFlag = Operand.isKill();
474   };
475 
476   auto GetFMAInstrInfo = [&](const MachineInstr &Instr, Register &MulOp1,
477                              Register &MulOp2, bool &MulOp1KillFlag,
478                              bool &MulOp2KillFlag) {
479     GetOperandInfo(Instr.getOperand(FirstMulOpIdx), MulOp1, MulOp1KillFlag);
480     GetOperandInfo(Instr.getOperand(FirstMulOpIdx + 1), MulOp2, MulOp2KillFlag);
481   };
482 
483   Register RegM11, RegM12, RegX, RegY, RegM21, RegM22, RegM31, RegM32;
484   bool KillX = false, KillY = false, KillM11 = false, KillM12 = false,
485        KillM21 = false, KillM22 = false, KillM31 = false, KillM32 = false;
486 
487   GetFMAInstrInfo(Root, RegM31, RegM32, KillM31, KillM32);
488   GetFMAInstrInfo(*Prev, RegM21, RegM22, KillM21, KillM22);
489 
490   if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
491     GetFMAInstrInfo(*Leaf, RegM11, RegM12, KillM11, KillM12);
492     GetOperandInfo(Leaf->getOperand(AddOpIdx), RegX, KillX);
493   } else if (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) {
494     GetOperandInfo(Leaf->getOperand(1), RegX, KillX);
495     GetOperandInfo(Leaf->getOperand(2), RegY, KillY);
496   }
497 
498   // Create new virtual registers for the new results instead of
499   // recycling legacy ones because the MachineCombiner's computation of the
500   // critical path requires a new register definition rather than an existing
501   // one.
502   Register NewVRA = MRI.createVirtualRegister(RC);
503   InstrIdxForVirtReg.insert(std::make_pair(NewVRA, 0));
504 
505   Register NewVRB = MRI.createVirtualRegister(RC);
506   InstrIdxForVirtReg.insert(std::make_pair(NewVRB, 1));
507 
508   Register NewVRD = 0;
509   if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
510     NewVRD = MRI.createVirtualRegister(RC);
511     InstrIdxForVirtReg.insert(std::make_pair(NewVRD, 2));
512   }
513 
514   auto AdjustOperandOrder = [&](MachineInstr *MI, Register RegAdd, bool KillAdd,
515                                 Register RegMul1, bool KillRegMul1,
516                                 Register RegMul2, bool KillRegMul2) {
517     MI->getOperand(AddOpIdx).setReg(RegAdd);
518     MI->getOperand(AddOpIdx).setIsKill(KillAdd);
519     MI->getOperand(FirstMulOpIdx).setReg(RegMul1);
520     MI->getOperand(FirstMulOpIdx).setIsKill(KillRegMul1);
521     MI->getOperand(FirstMulOpIdx + 1).setReg(RegMul2);
522     MI->getOperand(FirstMulOpIdx + 1).setIsKill(KillRegMul2);
523   };
524 
525   if (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) {
526     // Create new instructions for insertion.
527     MachineInstrBuilder MINewB =
528         BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
529             .addReg(RegX, getKillRegState(KillX))
530             .addReg(RegM21, getKillRegState(KillM21))
531             .addReg(RegM22, getKillRegState(KillM22));
532     MachineInstrBuilder MINewA =
533         BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA)
534             .addReg(RegY, getKillRegState(KillY))
535             .addReg(RegM31, getKillRegState(KillM31))
536             .addReg(RegM32, getKillRegState(KillM32));
537     // If AddOpIdx is not 1, adjust the order.
538     if (AddOpIdx != 1) {
539       AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
540       AdjustOperandOrder(MINewA, RegY, KillY, RegM31, KillM31, RegM32, KillM32);
541     }
542 
543     MachineInstrBuilder MINewC =
544         BuildMI(*MF, Root.getDebugLoc(),
545                 get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC)
546             .addReg(NewVRB, getKillRegState(true))
547             .addReg(NewVRA, getKillRegState(true));
548 
549     // Update flags for newly created instructions.
550     setSpecialOperandAttr(*MINewA, IntersectedFlags);
551     setSpecialOperandAttr(*MINewB, IntersectedFlags);
552     setSpecialOperandAttr(*MINewC, IntersectedFlags);
553 
554     // Record new instructions for insertion.
555     InsInstrs.push_back(MINewA);
556     InsInstrs.push_back(MINewB);
557     InsInstrs.push_back(MINewC);
558   } else if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
559     assert(NewVRD && "new FMA register not created!");
560     // Create new instructions for insertion.
561     MachineInstrBuilder MINewA =
562         BuildMI(*MF, Leaf->getDebugLoc(),
563                 get(FMAOpIdxInfo[Idx][InfoArrayIdxFMULInst]), NewVRA)
564             .addReg(RegM11, getKillRegState(KillM11))
565             .addReg(RegM12, getKillRegState(KillM12));
566     MachineInstrBuilder MINewB =
567         BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
568             .addReg(RegX, getKillRegState(KillX))
569             .addReg(RegM21, getKillRegState(KillM21))
570             .addReg(RegM22, getKillRegState(KillM22));
571     MachineInstrBuilder MINewD =
572         BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRD)
573             .addReg(NewVRA, getKillRegState(true))
574             .addReg(RegM31, getKillRegState(KillM31))
575             .addReg(RegM32, getKillRegState(KillM32));
576     // If AddOpIdx is not 1, adjust the order.
577     if (AddOpIdx != 1) {
578       AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
579       AdjustOperandOrder(MINewD, NewVRA, true, RegM31, KillM31, RegM32,
580                          KillM32);
581     }
582 
583     MachineInstrBuilder MINewC =
584         BuildMI(*MF, Root.getDebugLoc(),
585                 get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC)
586             .addReg(NewVRB, getKillRegState(true))
587             .addReg(NewVRD, getKillRegState(true));
588 
589     // Update flags for newly created instructions.
590     setSpecialOperandAttr(*MINewA, IntersectedFlags);
591     setSpecialOperandAttr(*MINewB, IntersectedFlags);
592     setSpecialOperandAttr(*MINewD, IntersectedFlags);
593     setSpecialOperandAttr(*MINewC, IntersectedFlags);
594 
595     // Record new instructions for insertion.
596     InsInstrs.push_back(MINewA);
597     InsInstrs.push_back(MINewB);
598     InsInstrs.push_back(MINewD);
599     InsInstrs.push_back(MINewC);
600   }
601 
602   assert(!InsInstrs.empty() &&
603          "Insertion instructions set should not be empty!");
604 
605   // Record old instructions for deletion.
606   DelInstrs.push_back(Leaf);
607   DelInstrs.push_back(Prev);
608   DelInstrs.push_back(&Root);
609 }
610 
611 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
612 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
613                                          Register &SrcReg, Register &DstReg,
614                                          unsigned &SubIdx) const {
615   switch (MI.getOpcode()) {
616   default: return false;
617   case PPC::EXTSW:
618   case PPC::EXTSW_32:
619   case PPC::EXTSW_32_64:
620     SrcReg = MI.getOperand(1).getReg();
621     DstReg = MI.getOperand(0).getReg();
622     SubIdx = PPC::sub_32;
623     return true;
624   }
625 }
626 
627 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
628                                            int &FrameIndex) const {
629   unsigned Opcode = MI.getOpcode();
630   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
631   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
632 
633   if (End != std::find(OpcodesForSpill, End, Opcode)) {
634     // Check for the operands added by addFrameReference (the immediate is the
635     // offset which defaults to 0).
636     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
637         MI.getOperand(2).isFI()) {
638       FrameIndex = MI.getOperand(2).getIndex();
639       return MI.getOperand(0).getReg();
640     }
641   }
642   return 0;
643 }
644 
645 // For opcodes with the ReMaterializable flag set, this function is called to
646 // verify the instruction is really rematable.
647 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
648                                                      AliasAnalysis *AA) const {
649   switch (MI.getOpcode()) {
650   default:
651     // This function should only be called for opcodes with the ReMaterializable
652     // flag set.
653     llvm_unreachable("Unknown rematerializable operation!");
654     break;
655   case PPC::LI:
656   case PPC::LI8:
657   case PPC::LIS:
658   case PPC::LIS8:
659   case PPC::ADDIStocHA:
660   case PPC::ADDIStocHA8:
661   case PPC::ADDItocL:
662   case PPC::LOAD_STACK_GUARD:
663   case PPC::XXLXORz:
664   case PPC::XXLXORspz:
665   case PPC::XXLXORdpz:
666   case PPC::XXLEQVOnes:
667   case PPC::V_SET0B:
668   case PPC::V_SET0H:
669   case PPC::V_SET0:
670   case PPC::V_SETALLONESB:
671   case PPC::V_SETALLONESH:
672   case PPC::V_SETALLONES:
673   case PPC::CRSET:
674   case PPC::CRUNSET:
675   case PPC::XXSETACCZ:
676     return true;
677   }
678   return false;
679 }
680 
681 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
682                                           int &FrameIndex) const {
683   unsigned Opcode = MI.getOpcode();
684   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
685   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
686 
687   if (End != std::find(OpcodesForSpill, End, Opcode)) {
688     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
689         MI.getOperand(2).isFI()) {
690       FrameIndex = MI.getOperand(2).getIndex();
691       return MI.getOperand(0).getReg();
692     }
693   }
694   return 0;
695 }
696 
697 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
698                                                    unsigned OpIdx1,
699                                                    unsigned OpIdx2) const {
700   MachineFunction &MF = *MI.getParent()->getParent();
701 
702   // Normal instructions can be commuted the obvious way.
703   if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
704     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
705   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
706   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
707   // changing the relative order of the mask operands might change what happens
708   // to the high-bits of the mask (and, thus, the result).
709 
710   // Cannot commute if it has a non-zero rotate count.
711   if (MI.getOperand(3).getImm() != 0)
712     return nullptr;
713 
714   // If we have a zero rotate count, we have:
715   //   M = mask(MB,ME)
716   //   Op0 = (Op1 & ~M) | (Op2 & M)
717   // Change this to:
718   //   M = mask((ME+1)&31, (MB-1)&31)
719   //   Op0 = (Op2 & ~M) | (Op1 & M)
720 
721   // Swap op1/op2
722   assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
723          "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
724   Register Reg0 = MI.getOperand(0).getReg();
725   Register Reg1 = MI.getOperand(1).getReg();
726   Register Reg2 = MI.getOperand(2).getReg();
727   unsigned SubReg1 = MI.getOperand(1).getSubReg();
728   unsigned SubReg2 = MI.getOperand(2).getSubReg();
729   bool Reg1IsKill = MI.getOperand(1).isKill();
730   bool Reg2IsKill = MI.getOperand(2).isKill();
731   bool ChangeReg0 = false;
732   // If machine instrs are no longer in two-address forms, update
733   // destination register as well.
734   if (Reg0 == Reg1) {
735     // Must be two address instruction!
736     assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
737            "Expecting a two-address instruction!");
738     assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
739     Reg2IsKill = false;
740     ChangeReg0 = true;
741   }
742 
743   // Masks.
744   unsigned MB = MI.getOperand(4).getImm();
745   unsigned ME = MI.getOperand(5).getImm();
746 
747   // We can't commute a trivial mask (there is no way to represent an all-zero
748   // mask).
749   if (MB == 0 && ME == 31)
750     return nullptr;
751 
752   if (NewMI) {
753     // Create a new instruction.
754     Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
755     bool Reg0IsDead = MI.getOperand(0).isDead();
756     return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
757         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
758         .addReg(Reg2, getKillRegState(Reg2IsKill))
759         .addReg(Reg1, getKillRegState(Reg1IsKill))
760         .addImm((ME + 1) & 31)
761         .addImm((MB - 1) & 31);
762   }
763 
764   if (ChangeReg0) {
765     MI.getOperand(0).setReg(Reg2);
766     MI.getOperand(0).setSubReg(SubReg2);
767   }
768   MI.getOperand(2).setReg(Reg1);
769   MI.getOperand(1).setReg(Reg2);
770   MI.getOperand(2).setSubReg(SubReg1);
771   MI.getOperand(1).setSubReg(SubReg2);
772   MI.getOperand(2).setIsKill(Reg1IsKill);
773   MI.getOperand(1).setIsKill(Reg2IsKill);
774 
775   // Swap the mask around.
776   MI.getOperand(4).setImm((ME + 1) & 31);
777   MI.getOperand(5).setImm((MB - 1) & 31);
778   return &MI;
779 }
780 
781 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
782                                          unsigned &SrcOpIdx1,
783                                          unsigned &SrcOpIdx2) const {
784   // For VSX A-Type FMA instructions, it is the first two operands that can be
785   // commuted, however, because the non-encoded tied input operand is listed
786   // first, the operands to swap are actually the second and third.
787 
788   int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
789   if (AltOpc == -1)
790     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
791 
792   // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
793   // and SrcOpIdx2.
794   return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
795 }
796 
797 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
798                               MachineBasicBlock::iterator MI) const {
799   // This function is used for scheduling, and the nop wanted here is the type
800   // that terminates dispatch groups on the POWER cores.
801   unsigned Directive = Subtarget.getCPUDirective();
802   unsigned Opcode;
803   switch (Directive) {
804   default:            Opcode = PPC::NOP; break;
805   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
806   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
807   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
808   // FIXME: Update when POWER9 scheduling model is ready.
809   case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
810   }
811 
812   DebugLoc DL;
813   BuildMI(MBB, MI, DL, get(Opcode));
814 }
815 
816 /// Return the noop instruction to use for a noop.
817 void PPCInstrInfo::getNoop(MCInst &NopInst) const {
818   NopInst.setOpcode(PPC::NOP);
819 }
820 
821 // Branch analysis.
822 // Note: If the condition register is set to CTR or CTR8 then this is a
823 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
824 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
825                                  MachineBasicBlock *&TBB,
826                                  MachineBasicBlock *&FBB,
827                                  SmallVectorImpl<MachineOperand> &Cond,
828                                  bool AllowModify) const {
829   bool isPPC64 = Subtarget.isPPC64();
830 
831   // If the block has no terminators, it just falls into the block after it.
832   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
833   if (I == MBB.end())
834     return false;
835 
836   if (!isUnpredicatedTerminator(*I))
837     return false;
838 
839   if (AllowModify) {
840     // If the BB ends with an unconditional branch to the fallthrough BB,
841     // we eliminate the branch instruction.
842     if (I->getOpcode() == PPC::B &&
843         MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
844       I->eraseFromParent();
845 
846       // We update iterator after deleting the last branch.
847       I = MBB.getLastNonDebugInstr();
848       if (I == MBB.end() || !isUnpredicatedTerminator(*I))
849         return false;
850     }
851   }
852 
853   // Get the last instruction in the block.
854   MachineInstr &LastInst = *I;
855 
856   // If there is only one terminator instruction, process it.
857   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
858     if (LastInst.getOpcode() == PPC::B) {
859       if (!LastInst.getOperand(0).isMBB())
860         return true;
861       TBB = LastInst.getOperand(0).getMBB();
862       return false;
863     } else if (LastInst.getOpcode() == PPC::BCC) {
864       if (!LastInst.getOperand(2).isMBB())
865         return true;
866       // Block ends with fall-through condbranch.
867       TBB = LastInst.getOperand(2).getMBB();
868       Cond.push_back(LastInst.getOperand(0));
869       Cond.push_back(LastInst.getOperand(1));
870       return false;
871     } else if (LastInst.getOpcode() == PPC::BC) {
872       if (!LastInst.getOperand(1).isMBB())
873         return true;
874       // Block ends with fall-through condbranch.
875       TBB = LastInst.getOperand(1).getMBB();
876       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
877       Cond.push_back(LastInst.getOperand(0));
878       return false;
879     } else if (LastInst.getOpcode() == PPC::BCn) {
880       if (!LastInst.getOperand(1).isMBB())
881         return true;
882       // Block ends with fall-through condbranch.
883       TBB = LastInst.getOperand(1).getMBB();
884       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
885       Cond.push_back(LastInst.getOperand(0));
886       return false;
887     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
888                LastInst.getOpcode() == PPC::BDNZ) {
889       if (!LastInst.getOperand(0).isMBB())
890         return true;
891       if (DisableCTRLoopAnal)
892         return true;
893       TBB = LastInst.getOperand(0).getMBB();
894       Cond.push_back(MachineOperand::CreateImm(1));
895       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
896                                                true));
897       return false;
898     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
899                LastInst.getOpcode() == PPC::BDZ) {
900       if (!LastInst.getOperand(0).isMBB())
901         return true;
902       if (DisableCTRLoopAnal)
903         return true;
904       TBB = LastInst.getOperand(0).getMBB();
905       Cond.push_back(MachineOperand::CreateImm(0));
906       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
907                                                true));
908       return false;
909     }
910 
911     // Otherwise, don't know what this is.
912     return true;
913   }
914 
915   // Get the instruction before it if it's a terminator.
916   MachineInstr &SecondLastInst = *I;
917 
918   // If there are three terminators, we don't know what sort of block this is.
919   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
920     return true;
921 
922   // If the block ends with PPC::B and PPC:BCC, handle it.
923   if (SecondLastInst.getOpcode() == PPC::BCC &&
924       LastInst.getOpcode() == PPC::B) {
925     if (!SecondLastInst.getOperand(2).isMBB() ||
926         !LastInst.getOperand(0).isMBB())
927       return true;
928     TBB = SecondLastInst.getOperand(2).getMBB();
929     Cond.push_back(SecondLastInst.getOperand(0));
930     Cond.push_back(SecondLastInst.getOperand(1));
931     FBB = LastInst.getOperand(0).getMBB();
932     return false;
933   } else if (SecondLastInst.getOpcode() == PPC::BC &&
934              LastInst.getOpcode() == PPC::B) {
935     if (!SecondLastInst.getOperand(1).isMBB() ||
936         !LastInst.getOperand(0).isMBB())
937       return true;
938     TBB = SecondLastInst.getOperand(1).getMBB();
939     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
940     Cond.push_back(SecondLastInst.getOperand(0));
941     FBB = LastInst.getOperand(0).getMBB();
942     return false;
943   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
944              LastInst.getOpcode() == PPC::B) {
945     if (!SecondLastInst.getOperand(1).isMBB() ||
946         !LastInst.getOperand(0).isMBB())
947       return true;
948     TBB = SecondLastInst.getOperand(1).getMBB();
949     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
950     Cond.push_back(SecondLastInst.getOperand(0));
951     FBB = LastInst.getOperand(0).getMBB();
952     return false;
953   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
954               SecondLastInst.getOpcode() == PPC::BDNZ) &&
955              LastInst.getOpcode() == PPC::B) {
956     if (!SecondLastInst.getOperand(0).isMBB() ||
957         !LastInst.getOperand(0).isMBB())
958       return true;
959     if (DisableCTRLoopAnal)
960       return true;
961     TBB = SecondLastInst.getOperand(0).getMBB();
962     Cond.push_back(MachineOperand::CreateImm(1));
963     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
964                                              true));
965     FBB = LastInst.getOperand(0).getMBB();
966     return false;
967   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
968               SecondLastInst.getOpcode() == PPC::BDZ) &&
969              LastInst.getOpcode() == PPC::B) {
970     if (!SecondLastInst.getOperand(0).isMBB() ||
971         !LastInst.getOperand(0).isMBB())
972       return true;
973     if (DisableCTRLoopAnal)
974       return true;
975     TBB = SecondLastInst.getOperand(0).getMBB();
976     Cond.push_back(MachineOperand::CreateImm(0));
977     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
978                                              true));
979     FBB = LastInst.getOperand(0).getMBB();
980     return false;
981   }
982 
983   // If the block ends with two PPC:Bs, handle it.  The second one is not
984   // executed, so remove it.
985   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
986     if (!SecondLastInst.getOperand(0).isMBB())
987       return true;
988     TBB = SecondLastInst.getOperand(0).getMBB();
989     I = LastInst;
990     if (AllowModify)
991       I->eraseFromParent();
992     return false;
993   }
994 
995   // Otherwise, can't handle this.
996   return true;
997 }
998 
999 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
1000                                     int *BytesRemoved) const {
1001   assert(!BytesRemoved && "code size not handled");
1002 
1003   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1004   if (I == MBB.end())
1005     return 0;
1006 
1007   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
1008       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1009       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1010       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
1011     return 0;
1012 
1013   // Remove the branch.
1014   I->eraseFromParent();
1015 
1016   I = MBB.end();
1017 
1018   if (I == MBB.begin()) return 1;
1019   --I;
1020   if (I->getOpcode() != PPC::BCC &&
1021       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1022       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1023       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
1024     return 1;
1025 
1026   // Remove the branch.
1027   I->eraseFromParent();
1028   return 2;
1029 }
1030 
1031 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
1032                                     MachineBasicBlock *TBB,
1033                                     MachineBasicBlock *FBB,
1034                                     ArrayRef<MachineOperand> Cond,
1035                                     const DebugLoc &DL,
1036                                     int *BytesAdded) const {
1037   // Shouldn't be a fall through.
1038   assert(TBB && "insertBranch must not be told to insert a fallthrough");
1039   assert((Cond.size() == 2 || Cond.size() == 0) &&
1040          "PPC branch conditions have two components!");
1041   assert(!BytesAdded && "code size not handled");
1042 
1043   bool isPPC64 = Subtarget.isPPC64();
1044 
1045   // One-way branch.
1046   if (!FBB) {
1047     if (Cond.empty())   // Unconditional branch
1048       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
1049     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1050       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1051                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1052                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
1053     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1054       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1055     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1056       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1057     else                // Conditional branch
1058       BuildMI(&MBB, DL, get(PPC::BCC))
1059           .addImm(Cond[0].getImm())
1060           .add(Cond[1])
1061           .addMBB(TBB);
1062     return 1;
1063   }
1064 
1065   // Two-way Conditional Branch.
1066   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1067     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1068                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1069                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
1070   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1071     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1072   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1073     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1074   else
1075     BuildMI(&MBB, DL, get(PPC::BCC))
1076         .addImm(Cond[0].getImm())
1077         .add(Cond[1])
1078         .addMBB(TBB);
1079   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
1080   return 2;
1081 }
1082 
1083 // Select analysis.
1084 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1085                                    ArrayRef<MachineOperand> Cond,
1086                                    Register DstReg, Register TrueReg,
1087                                    Register FalseReg, int &CondCycles,
1088                                    int &TrueCycles, int &FalseCycles) const {
1089   if (Cond.size() != 2)
1090     return false;
1091 
1092   // If this is really a bdnz-like condition, then it cannot be turned into a
1093   // select.
1094   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1095     return false;
1096 
1097   // Check register classes.
1098   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1099   const TargetRegisterClass *RC =
1100     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1101   if (!RC)
1102     return false;
1103 
1104   // isel is for regular integer GPRs only.
1105   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
1106       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
1107       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
1108       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
1109     return false;
1110 
1111   // FIXME: These numbers are for the A2, how well they work for other cores is
1112   // an open question. On the A2, the isel instruction has a 2-cycle latency
1113   // but single-cycle throughput. These numbers are used in combination with
1114   // the MispredictPenalty setting from the active SchedMachineModel.
1115   CondCycles = 1;
1116   TrueCycles = 1;
1117   FalseCycles = 1;
1118 
1119   return true;
1120 }
1121 
1122 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
1123                                 MachineBasicBlock::iterator MI,
1124                                 const DebugLoc &dl, Register DestReg,
1125                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
1126                                 Register FalseReg) const {
1127   assert(Cond.size() == 2 &&
1128          "PPC branch conditions have two components!");
1129 
1130   // Get the register classes.
1131   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1132   const TargetRegisterClass *RC =
1133     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1134   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
1135 
1136   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
1137                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
1138   assert((Is64Bit ||
1139           PPC::GPRCRegClass.hasSubClassEq(RC) ||
1140           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
1141          "isel is for regular integer GPRs only");
1142 
1143   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
1144   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
1145 
1146   unsigned SubIdx = 0;
1147   bool SwapOps = false;
1148   switch (SelectPred) {
1149   case PPC::PRED_EQ:
1150   case PPC::PRED_EQ_MINUS:
1151   case PPC::PRED_EQ_PLUS:
1152       SubIdx = PPC::sub_eq; SwapOps = false; break;
1153   case PPC::PRED_NE:
1154   case PPC::PRED_NE_MINUS:
1155   case PPC::PRED_NE_PLUS:
1156       SubIdx = PPC::sub_eq; SwapOps = true; break;
1157   case PPC::PRED_LT:
1158   case PPC::PRED_LT_MINUS:
1159   case PPC::PRED_LT_PLUS:
1160       SubIdx = PPC::sub_lt; SwapOps = false; break;
1161   case PPC::PRED_GE:
1162   case PPC::PRED_GE_MINUS:
1163   case PPC::PRED_GE_PLUS:
1164       SubIdx = PPC::sub_lt; SwapOps = true; break;
1165   case PPC::PRED_GT:
1166   case PPC::PRED_GT_MINUS:
1167   case PPC::PRED_GT_PLUS:
1168       SubIdx = PPC::sub_gt; SwapOps = false; break;
1169   case PPC::PRED_LE:
1170   case PPC::PRED_LE_MINUS:
1171   case PPC::PRED_LE_PLUS:
1172       SubIdx = PPC::sub_gt; SwapOps = true; break;
1173   case PPC::PRED_UN:
1174   case PPC::PRED_UN_MINUS:
1175   case PPC::PRED_UN_PLUS:
1176       SubIdx = PPC::sub_un; SwapOps = false; break;
1177   case PPC::PRED_NU:
1178   case PPC::PRED_NU_MINUS:
1179   case PPC::PRED_NU_PLUS:
1180       SubIdx = PPC::sub_un; SwapOps = true; break;
1181   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
1182   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
1183   }
1184 
1185   Register FirstReg =  SwapOps ? FalseReg : TrueReg,
1186            SecondReg = SwapOps ? TrueReg  : FalseReg;
1187 
1188   // The first input register of isel cannot be r0. If it is a member
1189   // of a register class that can be r0, then copy it first (the
1190   // register allocator should eliminate the copy).
1191   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
1192       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
1193     const TargetRegisterClass *FirstRC =
1194       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
1195         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
1196     Register OldFirstReg = FirstReg;
1197     FirstReg = MRI.createVirtualRegister(FirstRC);
1198     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
1199       .addReg(OldFirstReg);
1200   }
1201 
1202   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
1203     .addReg(FirstReg).addReg(SecondReg)
1204     .addReg(Cond[1].getReg(), 0, SubIdx);
1205 }
1206 
1207 static unsigned getCRBitValue(unsigned CRBit) {
1208   unsigned Ret = 4;
1209   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
1210       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
1211       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
1212       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
1213     Ret = 3;
1214   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
1215       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
1216       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
1217       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
1218     Ret = 2;
1219   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
1220       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
1221       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
1222       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
1223     Ret = 1;
1224   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
1225       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
1226       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
1227       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
1228     Ret = 0;
1229 
1230   assert(Ret != 4 && "Invalid CR bit register");
1231   return Ret;
1232 }
1233 
1234 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
1235                                MachineBasicBlock::iterator I,
1236                                const DebugLoc &DL, MCRegister DestReg,
1237                                MCRegister SrcReg, bool KillSrc) const {
1238   // We can end up with self copies and similar things as a result of VSX copy
1239   // legalization. Promote them here.
1240   const TargetRegisterInfo *TRI = &getRegisterInfo();
1241   if (PPC::F8RCRegClass.contains(DestReg) &&
1242       PPC::VSRCRegClass.contains(SrcReg)) {
1243     MCRegister SuperReg =
1244         TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
1245 
1246     if (VSXSelfCopyCrash && SrcReg == SuperReg)
1247       llvm_unreachable("nop VSX copy");
1248 
1249     DestReg = SuperReg;
1250   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
1251              PPC::VSRCRegClass.contains(DestReg)) {
1252     MCRegister SuperReg =
1253         TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
1254 
1255     if (VSXSelfCopyCrash && DestReg == SuperReg)
1256       llvm_unreachable("nop VSX copy");
1257 
1258     SrcReg = SuperReg;
1259   }
1260 
1261   // Different class register copy
1262   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
1263       PPC::GPRCRegClass.contains(DestReg)) {
1264     MCRegister CRReg = getCRFromCRBit(SrcReg);
1265     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
1266     getKillRegState(KillSrc);
1267     // Rotate the CR bit in the CR fields to be the least significant bit and
1268     // then mask with 0x1 (MB = ME = 31).
1269     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
1270        .addReg(DestReg, RegState::Kill)
1271        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
1272        .addImm(31)
1273        .addImm(31);
1274     return;
1275   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
1276              (PPC::G8RCRegClass.contains(DestReg) ||
1277               PPC::GPRCRegClass.contains(DestReg))) {
1278     bool Is64Bit = PPC::G8RCRegClass.contains(DestReg);
1279     unsigned MvCode = Is64Bit ? PPC::MFOCRF8 : PPC::MFOCRF;
1280     unsigned ShCode = Is64Bit ? PPC::RLWINM8 : PPC::RLWINM;
1281     unsigned CRNum = TRI->getEncodingValue(SrcReg);
1282     BuildMI(MBB, I, DL, get(MvCode), DestReg).addReg(SrcReg);
1283     getKillRegState(KillSrc);
1284     if (CRNum == 7)
1285       return;
1286     // Shift the CR bits to make the CR field in the lowest 4 bits of GRC.
1287     BuildMI(MBB, I, DL, get(ShCode), DestReg)
1288         .addReg(DestReg, RegState::Kill)
1289         .addImm(CRNum * 4 + 4)
1290         .addImm(28)
1291         .addImm(31);
1292     return;
1293   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
1294              PPC::VSFRCRegClass.contains(DestReg)) {
1295     assert(Subtarget.hasDirectMove() &&
1296            "Subtarget doesn't support directmove, don't know how to copy.");
1297     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
1298     NumGPRtoVSRSpill++;
1299     getKillRegState(KillSrc);
1300     return;
1301   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
1302              PPC::G8RCRegClass.contains(DestReg)) {
1303     assert(Subtarget.hasDirectMove() &&
1304            "Subtarget doesn't support directmove, don't know how to copy.");
1305     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
1306     getKillRegState(KillSrc);
1307     return;
1308   } else if (PPC::SPERCRegClass.contains(SrcReg) &&
1309              PPC::GPRCRegClass.contains(DestReg)) {
1310     BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
1311     getKillRegState(KillSrc);
1312     return;
1313   } else if (PPC::GPRCRegClass.contains(SrcReg) &&
1314              PPC::SPERCRegClass.contains(DestReg)) {
1315     BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
1316     getKillRegState(KillSrc);
1317     return;
1318   }
1319 
1320   unsigned Opc;
1321   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
1322     Opc = PPC::OR;
1323   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
1324     Opc = PPC::OR8;
1325   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
1326     Opc = PPC::FMR;
1327   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
1328     Opc = PPC::MCRF;
1329   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
1330     Opc = PPC::VOR;
1331   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
1332     // There are two different ways this can be done:
1333     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1334     //      issue in VSU pipeline 0.
1335     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1336     //      can go to either pipeline.
1337     // We'll always use xxlor here, because in practically all cases where
1338     // copies are generated, they are close enough to some use that the
1339     // lower-latency form is preferable.
1340     Opc = PPC::XXLOR;
1341   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1342            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1343     Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1344   else if (Subtarget.pairedVectorMemops() &&
1345            PPC::VSRpRCRegClass.contains(DestReg, SrcReg)) {
1346     if (SrcReg > PPC::VSRp15)
1347       SrcReg = PPC::V0 + (SrcReg - PPC::VSRp16) * 2;
1348     else
1349       SrcReg = PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1350     if (DestReg > PPC::VSRp15)
1351       DestReg = PPC::V0 + (DestReg - PPC::VSRp16) * 2;
1352     else
1353       DestReg = PPC::VSL0 + (DestReg - PPC::VSRp0) * 2;
1354     BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg).
1355       addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1356     BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg + 1).
1357       addReg(SrcReg + 1).addReg(SrcReg + 1, getKillRegState(KillSrc));
1358     return;
1359   }
1360   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1361     Opc = PPC::CROR;
1362   else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1363     Opc = PPC::EVOR;
1364   else if ((PPC::ACCRCRegClass.contains(DestReg) ||
1365             PPC::UACCRCRegClass.contains(DestReg)) &&
1366            (PPC::ACCRCRegClass.contains(SrcReg) ||
1367             PPC::UACCRCRegClass.contains(SrcReg))) {
1368     // If primed, de-prime the source register, copy the individual registers
1369     // and prime the destination if needed. The vector subregisters are
1370     // vs[(u)acc * 4] - vs[(u)acc * 4 + 3]. If the copy is not a kill and the
1371     // source is primed, we need to re-prime it after the copy as well.
1372     PPCRegisterInfo::emitAccCopyInfo(MBB, DestReg, SrcReg);
1373     bool DestPrimed = PPC::ACCRCRegClass.contains(DestReg);
1374     bool SrcPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1375     MCRegister VSLSrcReg =
1376         PPC::VSL0 + (SrcReg - (SrcPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1377     MCRegister VSLDestReg =
1378         PPC::VSL0 + (DestReg - (DestPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1379     if (SrcPrimed)
1380       BuildMI(MBB, I, DL, get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1381     for (unsigned Idx = 0; Idx < 4; Idx++)
1382       BuildMI(MBB, I, DL, get(PPC::XXLOR), VSLDestReg + Idx)
1383           .addReg(VSLSrcReg + Idx)
1384           .addReg(VSLSrcReg + Idx, getKillRegState(KillSrc));
1385     if (DestPrimed)
1386       BuildMI(MBB, I, DL, get(PPC::XXMTACC), DestReg).addReg(DestReg);
1387     if (SrcPrimed && !KillSrc)
1388       BuildMI(MBB, I, DL, get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1389     return;
1390   } else
1391     llvm_unreachable("Impossible reg-to-reg copy");
1392 
1393   const MCInstrDesc &MCID = get(Opc);
1394   if (MCID.getNumOperands() == 3)
1395     BuildMI(MBB, I, DL, MCID, DestReg)
1396       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1397   else
1398     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1399 }
1400 
1401 unsigned PPCInstrInfo::getSpillIndex(const TargetRegisterClass *RC) const {
1402   int OpcodeIndex = 0;
1403 
1404   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1405       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1406     OpcodeIndex = SOK_Int4Spill;
1407   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1408              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1409     OpcodeIndex = SOK_Int8Spill;
1410   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1411     OpcodeIndex = SOK_Float8Spill;
1412   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1413     OpcodeIndex = SOK_Float4Spill;
1414   } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1415     OpcodeIndex = SOK_SPESpill;
1416   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1417     OpcodeIndex = SOK_CRSpill;
1418   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1419     OpcodeIndex = SOK_CRBitSpill;
1420   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1421     OpcodeIndex = SOK_VRVectorSpill;
1422   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1423     OpcodeIndex = SOK_VSXVectorSpill;
1424   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1425     OpcodeIndex = SOK_VectorFloat8Spill;
1426   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1427     OpcodeIndex = SOK_VectorFloat4Spill;
1428   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1429     OpcodeIndex = SOK_SpillToVSR;
1430   } else if (PPC::ACCRCRegClass.hasSubClassEq(RC)) {
1431     assert(Subtarget.pairedVectorMemops() &&
1432            "Register unexpected when paired memops are disabled.");
1433     OpcodeIndex = SOK_AccumulatorSpill;
1434   } else if (PPC::UACCRCRegClass.hasSubClassEq(RC)) {
1435     assert(Subtarget.pairedVectorMemops() &&
1436            "Register unexpected when paired memops are disabled.");
1437     OpcodeIndex = SOK_UAccumulatorSpill;
1438   } else if (PPC::VSRpRCRegClass.hasSubClassEq(RC)) {
1439     assert(Subtarget.pairedVectorMemops() &&
1440            "Register unexpected when paired memops are disabled.");
1441     OpcodeIndex = SOK_PairedVecSpill;
1442   } else {
1443     llvm_unreachable("Unknown regclass!");
1444   }
1445   return OpcodeIndex;
1446 }
1447 
1448 unsigned
1449 PPCInstrInfo::getStoreOpcodeForSpill(const TargetRegisterClass *RC) const {
1450   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1451   return OpcodesForSpill[getSpillIndex(RC)];
1452 }
1453 
1454 unsigned
1455 PPCInstrInfo::getLoadOpcodeForSpill(const TargetRegisterClass *RC) const {
1456   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1457   return OpcodesForSpill[getSpillIndex(RC)];
1458 }
1459 
1460 void PPCInstrInfo::StoreRegToStackSlot(
1461     MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1462     const TargetRegisterClass *RC,
1463     SmallVectorImpl<MachineInstr *> &NewMIs) const {
1464   unsigned Opcode = getStoreOpcodeForSpill(RC);
1465   DebugLoc DL;
1466 
1467   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1468   FuncInfo->setHasSpills();
1469 
1470   NewMIs.push_back(addFrameReference(
1471       BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1472       FrameIdx));
1473 
1474   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1475       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1476     FuncInfo->setSpillsCR();
1477 
1478   if (isXFormMemOp(Opcode))
1479     FuncInfo->setHasNonRISpills();
1480 }
1481 
1482 void PPCInstrInfo::storeRegToStackSlotNoUpd(
1483     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
1484     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
1485     const TargetRegisterInfo *TRI) const {
1486   MachineFunction &MF = *MBB.getParent();
1487   SmallVector<MachineInstr *, 4> NewMIs;
1488 
1489   StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1490 
1491   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1492     MBB.insert(MI, NewMIs[i]);
1493 
1494   const MachineFrameInfo &MFI = MF.getFrameInfo();
1495   MachineMemOperand *MMO = MF.getMachineMemOperand(
1496       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1497       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1498       MFI.getObjectAlign(FrameIdx));
1499   NewMIs.back()->addMemOperand(MF, MMO);
1500 }
1501 
1502 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1503                                        MachineBasicBlock::iterator MI,
1504                                        Register SrcReg, bool isKill,
1505                                        int FrameIdx,
1506                                        const TargetRegisterClass *RC,
1507                                        const TargetRegisterInfo *TRI) const {
1508   // We need to avoid a situation in which the value from a VRRC register is
1509   // spilled using an Altivec instruction and reloaded into a VSRC register
1510   // using a VSX instruction. The issue with this is that the VSX
1511   // load/store instructions swap the doublewords in the vector and the Altivec
1512   // ones don't. The register classes on the spill/reload may be different if
1513   // the register is defined using an Altivec instruction and is then used by a
1514   // VSX instruction.
1515   RC = updatedRC(RC);
1516   storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI);
1517 }
1518 
1519 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1520                                         unsigned DestReg, int FrameIdx,
1521                                         const TargetRegisterClass *RC,
1522                                         SmallVectorImpl<MachineInstr *> &NewMIs)
1523                                         const {
1524   unsigned Opcode = getLoadOpcodeForSpill(RC);
1525   NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1526                                      FrameIdx));
1527   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1528 
1529   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1530       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1531     FuncInfo->setSpillsCR();
1532 
1533   if (isXFormMemOp(Opcode))
1534     FuncInfo->setHasNonRISpills();
1535 }
1536 
1537 void PPCInstrInfo::loadRegFromStackSlotNoUpd(
1538     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
1539     int FrameIdx, const TargetRegisterClass *RC,
1540     const TargetRegisterInfo *TRI) const {
1541   MachineFunction &MF = *MBB.getParent();
1542   SmallVector<MachineInstr*, 4> NewMIs;
1543   DebugLoc DL;
1544   if (MI != MBB.end()) DL = MI->getDebugLoc();
1545 
1546   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1547   FuncInfo->setHasSpills();
1548 
1549   LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1550 
1551   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1552     MBB.insert(MI, NewMIs[i]);
1553 
1554   const MachineFrameInfo &MFI = MF.getFrameInfo();
1555   MachineMemOperand *MMO = MF.getMachineMemOperand(
1556       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1557       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1558       MFI.getObjectAlign(FrameIdx));
1559   NewMIs.back()->addMemOperand(MF, MMO);
1560 }
1561 
1562 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1563                                         MachineBasicBlock::iterator MI,
1564                                         Register DestReg, int FrameIdx,
1565                                         const TargetRegisterClass *RC,
1566                                         const TargetRegisterInfo *TRI) const {
1567   // We need to avoid a situation in which the value from a VRRC register is
1568   // spilled using an Altivec instruction and reloaded into a VSRC register
1569   // using a VSX instruction. The issue with this is that the VSX
1570   // load/store instructions swap the doublewords in the vector and the Altivec
1571   // ones don't. The register classes on the spill/reload may be different if
1572   // the register is defined using an Altivec instruction and is then used by a
1573   // VSX instruction.
1574   RC = updatedRC(RC);
1575 
1576   loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI);
1577 }
1578 
1579 bool PPCInstrInfo::
1580 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1581   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1582   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1583     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1584   else
1585     // Leave the CR# the same, but invert the condition.
1586     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1587   return false;
1588 }
1589 
1590 // For some instructions, it is legal to fold ZERO into the RA register field.
1591 // This function performs that fold by replacing the operand with PPC::ZERO,
1592 // it does not consider whether the load immediate zero is no longer in use.
1593 bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1594                                      Register Reg) const {
1595   // A zero immediate should always be loaded with a single li.
1596   unsigned DefOpc = DefMI.getOpcode();
1597   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1598     return false;
1599   if (!DefMI.getOperand(1).isImm())
1600     return false;
1601   if (DefMI.getOperand(1).getImm() != 0)
1602     return false;
1603 
1604   // Note that we cannot here invert the arguments of an isel in order to fold
1605   // a ZERO into what is presented as the second argument. All we have here
1606   // is the condition bit, and that might come from a CR-logical bit operation.
1607 
1608   const MCInstrDesc &UseMCID = UseMI.getDesc();
1609 
1610   // Only fold into real machine instructions.
1611   if (UseMCID.isPseudo())
1612     return false;
1613 
1614   // We need to find which of the User's operands is to be folded, that will be
1615   // the operand that matches the given register ID.
1616   unsigned UseIdx;
1617   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1618     if (UseMI.getOperand(UseIdx).isReg() &&
1619         UseMI.getOperand(UseIdx).getReg() == Reg)
1620       break;
1621 
1622   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1623   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1624 
1625   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1626 
1627   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1628   // register (which might also be specified as a pointer class kind).
1629   if (UseInfo->isLookupPtrRegClass()) {
1630     if (UseInfo->RegClass /* Kind */ != 1)
1631       return false;
1632   } else {
1633     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1634         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1635       return false;
1636   }
1637 
1638   // Make sure this is not tied to an output register (or otherwise
1639   // constrained). This is true for ST?UX registers, for example, which
1640   // are tied to their output registers.
1641   if (UseInfo->Constraints != 0)
1642     return false;
1643 
1644   MCRegister ZeroReg;
1645   if (UseInfo->isLookupPtrRegClass()) {
1646     bool isPPC64 = Subtarget.isPPC64();
1647     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1648   } else {
1649     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1650               PPC::ZERO8 : PPC::ZERO;
1651   }
1652 
1653   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1654   return true;
1655 }
1656 
1657 // Folds zero into instructions which have a load immediate zero as an operand
1658 // but also recognize zero as immediate zero. If the definition of the load
1659 // has no more users it is deleted.
1660 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1661                                  Register Reg, MachineRegisterInfo *MRI) const {
1662   bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
1663   if (MRI->use_nodbg_empty(Reg))
1664     DefMI.eraseFromParent();
1665   return Changed;
1666 }
1667 
1668 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1669   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1670        I != IE; ++I)
1671     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1672       return true;
1673   return false;
1674 }
1675 
1676 // We should make sure that, if we're going to predicate both sides of a
1677 // condition (a diamond), that both sides don't define the counter register. We
1678 // can predicate counter-decrement-based branches, but while that predicates
1679 // the branching, it does not predicate the counter decrement. If we tried to
1680 // merge the triangle into one predicated block, we'd decrement the counter
1681 // twice.
1682 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1683                      unsigned NumT, unsigned ExtraT,
1684                      MachineBasicBlock &FMBB,
1685                      unsigned NumF, unsigned ExtraF,
1686                      BranchProbability Probability) const {
1687   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1688 }
1689 
1690 
1691 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1692   // The predicated branches are identified by their type, not really by the
1693   // explicit presence of a predicate. Furthermore, some of them can be
1694   // predicated more than once. Because if conversion won't try to predicate
1695   // any instruction which already claims to be predicated (by returning true
1696   // here), always return false. In doing so, we let isPredicable() be the
1697   // final word on whether not the instruction can be (further) predicated.
1698 
1699   return false;
1700 }
1701 
1702 bool PPCInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1703                                         const MachineBasicBlock *MBB,
1704                                         const MachineFunction &MF) const {
1705   // Set MFFS and MTFSF as scheduling boundary to avoid unexpected code motion
1706   // across them, since some FP operations may change content of FPSCR.
1707   // TODO: Model FPSCR in PPC instruction definitions and remove the workaround
1708   if (MI.getOpcode() == PPC::MFFS || MI.getOpcode() == PPC::MTFSF)
1709     return true;
1710   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF);
1711 }
1712 
1713 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1714                                         ArrayRef<MachineOperand> Pred) const {
1715   unsigned OpC = MI.getOpcode();
1716   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1717     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1718       bool isPPC64 = Subtarget.isPPC64();
1719       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1720                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1721       // Need add Def and Use for CTR implicit operand.
1722       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1723           .addReg(Pred[1].getReg(), RegState::Implicit)
1724           .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
1725     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1726       MI.setDesc(get(PPC::BCLR));
1727       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1728     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1729       MI.setDesc(get(PPC::BCLRn));
1730       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1731     } else {
1732       MI.setDesc(get(PPC::BCCLR));
1733       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1734           .addImm(Pred[0].getImm())
1735           .add(Pred[1]);
1736     }
1737 
1738     return true;
1739   } else if (OpC == PPC::B) {
1740     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1741       bool isPPC64 = Subtarget.isPPC64();
1742       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1743                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1744       // Need add Def and Use for CTR implicit operand.
1745       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1746           .addReg(Pred[1].getReg(), RegState::Implicit)
1747           .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
1748     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1749       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1750       MI.RemoveOperand(0);
1751 
1752       MI.setDesc(get(PPC::BC));
1753       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1754           .add(Pred[1])
1755           .addMBB(MBB);
1756     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1757       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1758       MI.RemoveOperand(0);
1759 
1760       MI.setDesc(get(PPC::BCn));
1761       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1762           .add(Pred[1])
1763           .addMBB(MBB);
1764     } else {
1765       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1766       MI.RemoveOperand(0);
1767 
1768       MI.setDesc(get(PPC::BCC));
1769       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1770           .addImm(Pred[0].getImm())
1771           .add(Pred[1])
1772           .addMBB(MBB);
1773     }
1774 
1775     return true;
1776   } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
1777              OpC == PPC::BCTRL8) {
1778     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1779       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1780 
1781     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1782     bool isPPC64 = Subtarget.isPPC64();
1783 
1784     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1785       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1786                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1787       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1788     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1789       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1790                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1791       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1792     } else {
1793       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1794                              : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1795       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1796           .addImm(Pred[0].getImm())
1797           .add(Pred[1]);
1798     }
1799 
1800     // Need add Def and Use for LR implicit operand.
1801     if (setLR)
1802       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1803           .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::Implicit)
1804           .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::ImplicitDefine);
1805 
1806     return true;
1807   }
1808 
1809   return false;
1810 }
1811 
1812 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1813                                      ArrayRef<MachineOperand> Pred2) const {
1814   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1815   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1816 
1817   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1818     return false;
1819   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1820     return false;
1821 
1822   // P1 can only subsume P2 if they test the same condition register.
1823   if (Pred1[1].getReg() != Pred2[1].getReg())
1824     return false;
1825 
1826   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1827   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1828 
1829   if (P1 == P2)
1830     return true;
1831 
1832   // Does P1 subsume P2, e.g. GE subsumes GT.
1833   if (P1 == PPC::PRED_LE &&
1834       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1835     return true;
1836   if (P1 == PPC::PRED_GE &&
1837       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1838     return true;
1839 
1840   return false;
1841 }
1842 
1843 bool PPCInstrInfo::ClobbersPredicate(MachineInstr &MI,
1844                                      std::vector<MachineOperand> &Pred,
1845                                      bool SkipDead) const {
1846   // Note: At the present time, the contents of Pred from this function is
1847   // unused by IfConversion. This implementation follows ARM by pushing the
1848   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1849   // predicate, instructions defining CTR or CTR8 are also included as
1850   // predicate-defining instructions.
1851 
1852   const TargetRegisterClass *RCs[] =
1853     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1854       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1855 
1856   bool Found = false;
1857   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1858     const MachineOperand &MO = MI.getOperand(i);
1859     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1860       const TargetRegisterClass *RC = RCs[c];
1861       if (MO.isReg()) {
1862         if (MO.isDef() && RC->contains(MO.getReg())) {
1863           Pred.push_back(MO);
1864           Found = true;
1865         }
1866       } else if (MO.isRegMask()) {
1867         for (TargetRegisterClass::iterator I = RC->begin(),
1868              IE = RC->end(); I != IE; ++I)
1869           if (MO.clobbersPhysReg(*I)) {
1870             Pred.push_back(MO);
1871             Found = true;
1872           }
1873       }
1874     }
1875   }
1876 
1877   return Found;
1878 }
1879 
1880 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1881                                   Register &SrcReg2, int &Mask,
1882                                   int &Value) const {
1883   unsigned Opc = MI.getOpcode();
1884 
1885   switch (Opc) {
1886   default: return false;
1887   case PPC::CMPWI:
1888   case PPC::CMPLWI:
1889   case PPC::CMPDI:
1890   case PPC::CMPLDI:
1891     SrcReg = MI.getOperand(1).getReg();
1892     SrcReg2 = 0;
1893     Value = MI.getOperand(2).getImm();
1894     Mask = 0xFFFF;
1895     return true;
1896   case PPC::CMPW:
1897   case PPC::CMPLW:
1898   case PPC::CMPD:
1899   case PPC::CMPLD:
1900   case PPC::FCMPUS:
1901   case PPC::FCMPUD:
1902     SrcReg = MI.getOperand(1).getReg();
1903     SrcReg2 = MI.getOperand(2).getReg();
1904     Value = 0;
1905     Mask = 0;
1906     return true;
1907   }
1908 }
1909 
1910 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1911                                         Register SrcReg2, int Mask, int Value,
1912                                         const MachineRegisterInfo *MRI) const {
1913   if (DisableCmpOpt)
1914     return false;
1915 
1916   int OpC = CmpInstr.getOpcode();
1917   Register CRReg = CmpInstr.getOperand(0).getReg();
1918 
1919   // FP record forms set CR1 based on the exception status bits, not a
1920   // comparison with zero.
1921   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1922     return false;
1923 
1924   const TargetRegisterInfo *TRI = &getRegisterInfo();
1925   // The record forms set the condition register based on a signed comparison
1926   // with zero (so says the ISA manual). This is not as straightforward as it
1927   // seems, however, because this is always a 64-bit comparison on PPC64, even
1928   // for instructions that are 32-bit in nature (like slw for example).
1929   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1930   // for equality checks (as those don't depend on the sign). On PPC64,
1931   // we are restricted to equality for unsigned 64-bit comparisons and for
1932   // signed 32-bit comparisons the applicability is more restricted.
1933   bool isPPC64 = Subtarget.isPPC64();
1934   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1935   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1936   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1937 
1938   // Look through copies unless that gets us to a physical register.
1939   Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
1940   if (ActualSrc.isVirtual())
1941     SrcReg = ActualSrc;
1942 
1943   // Get the unique definition of SrcReg.
1944   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1945   if (!MI) return false;
1946 
1947   bool equalityOnly = false;
1948   bool noSub = false;
1949   if (isPPC64) {
1950     if (is32BitSignedCompare) {
1951       // We can perform this optimization only if MI is sign-extending.
1952       if (isSignExtended(*MI))
1953         noSub = true;
1954       else
1955         return false;
1956     } else if (is32BitUnsignedCompare) {
1957       // We can perform this optimization, equality only, if MI is
1958       // zero-extending.
1959       if (isZeroExtended(*MI)) {
1960         noSub = true;
1961         equalityOnly = true;
1962       } else
1963         return false;
1964     } else
1965       equalityOnly = is64BitUnsignedCompare;
1966   } else
1967     equalityOnly = is32BitUnsignedCompare;
1968 
1969   if (equalityOnly) {
1970     // We need to check the uses of the condition register in order to reject
1971     // non-equality comparisons.
1972     for (MachineRegisterInfo::use_instr_iterator
1973          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1974          I != IE; ++I) {
1975       MachineInstr *UseMI = &*I;
1976       if (UseMI->getOpcode() == PPC::BCC) {
1977         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1978         unsigned PredCond = PPC::getPredicateCondition(Pred);
1979         // We ignore hint bits when checking for non-equality comparisons.
1980         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1981           return false;
1982       } else if (UseMI->getOpcode() == PPC::ISEL ||
1983                  UseMI->getOpcode() == PPC::ISEL8) {
1984         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1985         if (SubIdx != PPC::sub_eq)
1986           return false;
1987       } else
1988         return false;
1989     }
1990   }
1991 
1992   MachineBasicBlock::iterator I = CmpInstr;
1993 
1994   // Scan forward to find the first use of the compare.
1995   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1996        ++I) {
1997     bool FoundUse = false;
1998     for (MachineRegisterInfo::use_instr_iterator
1999          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
2000          J != JE; ++J)
2001       if (&*J == &*I) {
2002         FoundUse = true;
2003         break;
2004       }
2005 
2006     if (FoundUse)
2007       break;
2008   }
2009 
2010   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
2011   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
2012 
2013   // There are two possible candidates which can be changed to set CR[01].
2014   // One is MI, the other is a SUB instruction.
2015   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2016   MachineInstr *Sub = nullptr;
2017   if (SrcReg2 != 0)
2018     // MI is not a candidate for CMPrr.
2019     MI = nullptr;
2020   // FIXME: Conservatively refuse to convert an instruction which isn't in the
2021   // same BB as the comparison. This is to allow the check below to avoid calls
2022   // (and other explicit clobbers); instead we should really check for these
2023   // more explicitly (in at least a few predecessors).
2024   else if (MI->getParent() != CmpInstr.getParent())
2025     return false;
2026   else if (Value != 0) {
2027     // The record-form instructions set CR bit based on signed comparison
2028     // against 0. We try to convert a compare against 1 or -1 into a compare
2029     // against 0 to exploit record-form instructions. For example, we change
2030     // the condition "greater than -1" into "greater than or equal to 0"
2031     // and "less than 1" into "less than or equal to 0".
2032 
2033     // Since we optimize comparison based on a specific branch condition,
2034     // we don't optimize if condition code is used by more than once.
2035     if (equalityOnly || !MRI->hasOneUse(CRReg))
2036       return false;
2037 
2038     MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
2039     if (UseMI->getOpcode() != PPC::BCC)
2040       return false;
2041 
2042     PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
2043     unsigned PredCond = PPC::getPredicateCondition(Pred);
2044     unsigned PredHint = PPC::getPredicateHint(Pred);
2045     int16_t Immed = (int16_t)Value;
2046 
2047     // When modifying the condition in the predicate, we propagate hint bits
2048     // from the original predicate to the new one.
2049     if (Immed == -1 && PredCond == PPC::PRED_GT)
2050       // We convert "greater than -1" into "greater than or equal to 0",
2051       // since we are assuming signed comparison by !equalityOnly
2052       Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
2053     else if (Immed == -1 && PredCond == PPC::PRED_LE)
2054       // We convert "less than or equal to -1" into "less than 0".
2055       Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
2056     else if (Immed == 1 && PredCond == PPC::PRED_LT)
2057       // We convert "less than 1" into "less than or equal to 0".
2058       Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
2059     else if (Immed == 1 && PredCond == PPC::PRED_GE)
2060       // We convert "greater than or equal to 1" into "greater than 0".
2061       Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
2062     else
2063       return false;
2064 
2065     PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
2066   }
2067 
2068   // Search for Sub.
2069   --I;
2070 
2071   // Get ready to iterate backward from CmpInstr.
2072   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
2073 
2074   for (; I != E && !noSub; --I) {
2075     const MachineInstr &Instr = *I;
2076     unsigned IOpC = Instr.getOpcode();
2077 
2078     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
2079                              Instr.readsRegister(PPC::CR0, TRI)))
2080       // This instruction modifies or uses the record condition register after
2081       // the one we want to change. While we could do this transformation, it
2082       // would likely not be profitable. This transformation removes one
2083       // instruction, and so even forcing RA to generate one move probably
2084       // makes it unprofitable.
2085       return false;
2086 
2087     // Check whether CmpInstr can be made redundant by the current instruction.
2088     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
2089          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
2090         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
2091         ((Instr.getOperand(1).getReg() == SrcReg &&
2092           Instr.getOperand(2).getReg() == SrcReg2) ||
2093         (Instr.getOperand(1).getReg() == SrcReg2 &&
2094          Instr.getOperand(2).getReg() == SrcReg))) {
2095       Sub = &*I;
2096       break;
2097     }
2098 
2099     if (I == B)
2100       // The 'and' is below the comparison instruction.
2101       return false;
2102   }
2103 
2104   // Return false if no candidates exist.
2105   if (!MI && !Sub)
2106     return false;
2107 
2108   // The single candidate is called MI.
2109   if (!MI) MI = Sub;
2110 
2111   int NewOpC = -1;
2112   int MIOpC = MI->getOpcode();
2113   if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
2114       MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
2115     NewOpC = MIOpC;
2116   else {
2117     NewOpC = PPC::getRecordFormOpcode(MIOpC);
2118     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
2119       NewOpC = MIOpC;
2120   }
2121 
2122   // FIXME: On the non-embedded POWER architectures, only some of the record
2123   // forms are fast, and we should use only the fast ones.
2124 
2125   // The defining instruction has a record form (or is already a record
2126   // form). It is possible, however, that we'll need to reverse the condition
2127   // code of the users.
2128   if (NewOpC == -1)
2129     return false;
2130 
2131   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
2132   // needs to be updated to be based on SUB.  Push the condition code
2133   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
2134   // condition code of these operands will be modified.
2135   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
2136   // comparison against 0, which may modify predicate.
2137   bool ShouldSwap = false;
2138   if (Sub && Value == 0) {
2139     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2140       Sub->getOperand(2).getReg() == SrcReg;
2141 
2142     // The operands to subf are the opposite of sub, so only in the fixed-point
2143     // case, invert the order.
2144     ShouldSwap = !ShouldSwap;
2145   }
2146 
2147   if (ShouldSwap)
2148     for (MachineRegisterInfo::use_instr_iterator
2149          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2150          I != IE; ++I) {
2151       MachineInstr *UseMI = &*I;
2152       if (UseMI->getOpcode() == PPC::BCC) {
2153         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
2154         unsigned PredCond = PPC::getPredicateCondition(Pred);
2155         assert((!equalityOnly ||
2156                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
2157                "Invalid predicate for equality-only optimization");
2158         (void)PredCond; // To suppress warning in release build.
2159         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
2160                                 PPC::getSwappedPredicate(Pred)));
2161       } else if (UseMI->getOpcode() == PPC::ISEL ||
2162                  UseMI->getOpcode() == PPC::ISEL8) {
2163         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
2164         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
2165                "Invalid CR bit for equality-only optimization");
2166 
2167         if (NewSubReg == PPC::sub_lt)
2168           NewSubReg = PPC::sub_gt;
2169         else if (NewSubReg == PPC::sub_gt)
2170           NewSubReg = PPC::sub_lt;
2171 
2172         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
2173                                                  NewSubReg));
2174       } else // We need to abort on a user we don't understand.
2175         return false;
2176     }
2177   assert(!(Value != 0 && ShouldSwap) &&
2178          "Non-zero immediate support and ShouldSwap"
2179          "may conflict in updating predicate");
2180 
2181   // Create a new virtual register to hold the value of the CR set by the
2182   // record-form instruction. If the instruction was not previously in
2183   // record form, then set the kill flag on the CR.
2184   CmpInstr.eraseFromParent();
2185 
2186   MachineBasicBlock::iterator MII = MI;
2187   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
2188           get(TargetOpcode::COPY), CRReg)
2189     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
2190 
2191   // Even if CR0 register were dead before, it is alive now since the
2192   // instruction we just built uses it.
2193   MI->clearRegisterDeads(PPC::CR0);
2194 
2195   if (MIOpC != NewOpC) {
2196     // We need to be careful here: we're replacing one instruction with
2197     // another, and we need to make sure that we get all of the right
2198     // implicit uses and defs. On the other hand, the caller may be holding
2199     // an iterator to this instruction, and so we can't delete it (this is
2200     // specifically the case if this is the instruction directly after the
2201     // compare).
2202 
2203     // Rotates are expensive instructions. If we're emitting a record-form
2204     // rotate that can just be an andi/andis, we should just emit that.
2205     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
2206       Register GPRRes = MI->getOperand(0).getReg();
2207       int64_t SH = MI->getOperand(2).getImm();
2208       int64_t MB = MI->getOperand(3).getImm();
2209       int64_t ME = MI->getOperand(4).getImm();
2210       // We can only do this if both the start and end of the mask are in the
2211       // same halfword.
2212       bool MBInLoHWord = MB >= 16;
2213       bool MEInLoHWord = ME >= 16;
2214       uint64_t Mask = ~0LLU;
2215 
2216       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
2217         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2218         // The mask value needs to shift right 16 if we're emitting andis.
2219         Mask >>= MBInLoHWord ? 0 : 16;
2220         NewOpC = MIOpC == PPC::RLWINM
2221                      ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
2222                      : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
2223       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
2224                  (ME - MB + 1 == SH) && (MB >= 16)) {
2225         // If we are rotating by the exact number of bits as are in the mask
2226         // and the mask is in the least significant bits of the register,
2227         // that's just an andis. (as long as the GPR result has no uses).
2228         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
2229         Mask >>= 16;
2230         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
2231       }
2232       // If we've set the mask, we can transform.
2233       if (Mask != ~0LLU) {
2234         MI->RemoveOperand(4);
2235         MI->RemoveOperand(3);
2236         MI->getOperand(2).setImm(Mask);
2237         NumRcRotatesConvertedToRcAnd++;
2238       }
2239     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
2240       int64_t MB = MI->getOperand(3).getImm();
2241       if (MB >= 48) {
2242         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2243         NewOpC = PPC::ANDI8_rec;
2244         MI->RemoveOperand(3);
2245         MI->getOperand(2).setImm(Mask);
2246         NumRcRotatesConvertedToRcAnd++;
2247       }
2248     }
2249 
2250     const MCInstrDesc &NewDesc = get(NewOpC);
2251     MI->setDesc(NewDesc);
2252 
2253     if (NewDesc.ImplicitDefs)
2254       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
2255            *ImpDefs; ++ImpDefs)
2256         if (!MI->definesRegister(*ImpDefs))
2257           MI->addOperand(*MI->getParent()->getParent(),
2258                          MachineOperand::CreateReg(*ImpDefs, true, true));
2259     if (NewDesc.ImplicitUses)
2260       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
2261            *ImpUses; ++ImpUses)
2262         if (!MI->readsRegister(*ImpUses))
2263           MI->addOperand(*MI->getParent()->getParent(),
2264                          MachineOperand::CreateReg(*ImpUses, false, true));
2265   }
2266   assert(MI->definesRegister(PPC::CR0) &&
2267          "Record-form instruction does not define cr0?");
2268 
2269   // Modify the condition code of operands in OperandsToUpdate.
2270   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2271   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2272   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2273     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2274 
2275   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2276     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2277 
2278   return true;
2279 }
2280 
2281 bool PPCInstrInfo::getMemOperandsWithOffsetWidth(
2282     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2283     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
2284     const TargetRegisterInfo *TRI) const {
2285   const MachineOperand *BaseOp;
2286   OffsetIsScalable = false;
2287   if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))
2288     return false;
2289   BaseOps.push_back(BaseOp);
2290   return true;
2291 }
2292 
2293 static bool isLdStSafeToCluster(const MachineInstr &LdSt,
2294                                 const TargetRegisterInfo *TRI) {
2295   // If this is a volatile load/store, don't mess with it.
2296   if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
2297     return false;
2298 
2299   if (LdSt.getOperand(2).isFI())
2300     return true;
2301 
2302   assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
2303   // Can't cluster if the instruction modifies the base register
2304   // or it is update form. e.g. ld r2,3(r2)
2305   if (LdSt.modifiesRegister(LdSt.getOperand(2).getReg(), TRI))
2306     return false;
2307 
2308   return true;
2309 }
2310 
2311 // Only cluster instruction pair that have the same opcode, and they are
2312 // clusterable according to PowerPC specification.
2313 static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
2314                                      const PPCSubtarget &Subtarget) {
2315   switch (FirstOpc) {
2316   default:
2317     return false;
2318   case PPC::STD:
2319   case PPC::STFD:
2320   case PPC::STXSD:
2321   case PPC::DFSTOREf64:
2322     return FirstOpc == SecondOpc;
2323   // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
2324   // 32bit and 64bit instruction selection. They are clusterable pair though
2325   // they are different opcode.
2326   case PPC::STW:
2327   case PPC::STW8:
2328     return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
2329   }
2330 }
2331 
2332 bool PPCInstrInfo::shouldClusterMemOps(
2333     ArrayRef<const MachineOperand *> BaseOps1,
2334     ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
2335     unsigned NumBytes) const {
2336 
2337   assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
2338   const MachineOperand &BaseOp1 = *BaseOps1.front();
2339   const MachineOperand &BaseOp2 = *BaseOps2.front();
2340   assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
2341          "Only base registers and frame indices are supported.");
2342 
2343   // The NumLoads means the number of loads that has been clustered.
2344   // Don't cluster memory op if there are already two ops clustered at least.
2345   if (NumLoads > 2)
2346     return false;
2347 
2348   // Cluster the load/store only when they have the same base
2349   // register or FI.
2350   if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
2351       (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
2352       (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
2353     return false;
2354 
2355   // Check if the load/store are clusterable according to the PowerPC
2356   // specification.
2357   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
2358   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
2359   unsigned FirstOpc = FirstLdSt.getOpcode();
2360   unsigned SecondOpc = SecondLdSt.getOpcode();
2361   const TargetRegisterInfo *TRI = &getRegisterInfo();
2362   // Cluster the load/store only when they have the same opcode, and they are
2363   // clusterable opcode according to PowerPC specification.
2364   if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
2365     return false;
2366 
2367   // Can't cluster load/store that have ordered or volatile memory reference.
2368   if (!isLdStSafeToCluster(FirstLdSt, TRI) ||
2369       !isLdStSafeToCluster(SecondLdSt, TRI))
2370     return false;
2371 
2372   int64_t Offset1 = 0, Offset2 = 0;
2373   unsigned Width1 = 0, Width2 = 0;
2374   const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
2375   if (!getMemOperandWithOffsetWidth(FirstLdSt, Base1, Offset1, Width1, TRI) ||
2376       !getMemOperandWithOffsetWidth(SecondLdSt, Base2, Offset2, Width2, TRI) ||
2377       Width1 != Width2)
2378     return false;
2379 
2380   assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
2381          "getMemOperandWithOffsetWidth return incorrect base op");
2382   // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
2383   assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
2384   return Offset1 + Width1 == Offset2;
2385 }
2386 
2387 /// GetInstSize - Return the number of bytes of code the specified
2388 /// instruction may be.  This returns the maximum number of bytes.
2389 ///
2390 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2391   unsigned Opcode = MI.getOpcode();
2392 
2393   if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2394     const MachineFunction *MF = MI.getParent()->getParent();
2395     const char *AsmStr = MI.getOperand(0).getSymbolName();
2396     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2397   } else if (Opcode == TargetOpcode::STACKMAP) {
2398     StackMapOpers Opers(&MI);
2399     return Opers.getNumPatchBytes();
2400   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2401     PatchPointOpers Opers(&MI);
2402     return Opers.getNumPatchBytes();
2403   } else {
2404     return get(Opcode).getSize();
2405   }
2406 }
2407 
2408 std::pair<unsigned, unsigned>
2409 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2410   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2411   return std::make_pair(TF & Mask, TF & ~Mask);
2412 }
2413 
2414 ArrayRef<std::pair<unsigned, const char *>>
2415 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2416   using namespace PPCII;
2417   static const std::pair<unsigned, const char *> TargetFlags[] = {
2418       {MO_LO, "ppc-lo"},
2419       {MO_HA, "ppc-ha"},
2420       {MO_TPREL_LO, "ppc-tprel-lo"},
2421       {MO_TPREL_HA, "ppc-tprel-ha"},
2422       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2423       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2424       {MO_TOC_LO, "ppc-toc-lo"},
2425       {MO_TLS, "ppc-tls"}};
2426   return makeArrayRef(TargetFlags);
2427 }
2428 
2429 ArrayRef<std::pair<unsigned, const char *>>
2430 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2431   using namespace PPCII;
2432   static const std::pair<unsigned, const char *> TargetFlags[] = {
2433       {MO_PLT, "ppc-plt"},
2434       {MO_PIC_FLAG, "ppc-pic"},
2435       {MO_PCREL_FLAG, "ppc-pcrel"},
2436       {MO_GOT_FLAG, "ppc-got"},
2437       {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
2438       {MO_TLSGD_FLAG, "ppc-tlsgd"},
2439       {MO_TLSLD_FLAG, "ppc-tlsld"},
2440       {MO_TPREL_FLAG, "ppc-tprel"},
2441       {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
2442       {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
2443       {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"}};
2444   return makeArrayRef(TargetFlags);
2445 }
2446 
2447 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2448 // The VSX versions have the advantage of a full 64-register target whereas
2449 // the FP ones have the advantage of lower latency and higher throughput. So
2450 // what we are after is using the faster instructions in low register pressure
2451 // situations and using the larger register file in high register pressure
2452 // situations.
2453 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2454     unsigned UpperOpcode, LowerOpcode;
2455     switch (MI.getOpcode()) {
2456     case PPC::DFLOADf32:
2457       UpperOpcode = PPC::LXSSP;
2458       LowerOpcode = PPC::LFS;
2459       break;
2460     case PPC::DFLOADf64:
2461       UpperOpcode = PPC::LXSD;
2462       LowerOpcode = PPC::LFD;
2463       break;
2464     case PPC::DFSTOREf32:
2465       UpperOpcode = PPC::STXSSP;
2466       LowerOpcode = PPC::STFS;
2467       break;
2468     case PPC::DFSTOREf64:
2469       UpperOpcode = PPC::STXSD;
2470       LowerOpcode = PPC::STFD;
2471       break;
2472     case PPC::XFLOADf32:
2473       UpperOpcode = PPC::LXSSPX;
2474       LowerOpcode = PPC::LFSX;
2475       break;
2476     case PPC::XFLOADf64:
2477       UpperOpcode = PPC::LXSDX;
2478       LowerOpcode = PPC::LFDX;
2479       break;
2480     case PPC::XFSTOREf32:
2481       UpperOpcode = PPC::STXSSPX;
2482       LowerOpcode = PPC::STFSX;
2483       break;
2484     case PPC::XFSTOREf64:
2485       UpperOpcode = PPC::STXSDX;
2486       LowerOpcode = PPC::STFDX;
2487       break;
2488     case PPC::LIWAX:
2489       UpperOpcode = PPC::LXSIWAX;
2490       LowerOpcode = PPC::LFIWAX;
2491       break;
2492     case PPC::LIWZX:
2493       UpperOpcode = PPC::LXSIWZX;
2494       LowerOpcode = PPC::LFIWZX;
2495       break;
2496     case PPC::STIWX:
2497       UpperOpcode = PPC::STXSIWX;
2498       LowerOpcode = PPC::STFIWX;
2499       break;
2500     default:
2501       llvm_unreachable("Unknown Operation!");
2502     }
2503 
2504     Register TargetReg = MI.getOperand(0).getReg();
2505     unsigned Opcode;
2506     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2507         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2508       Opcode = LowerOpcode;
2509     else
2510       Opcode = UpperOpcode;
2511     MI.setDesc(get(Opcode));
2512     return true;
2513 }
2514 
2515 static bool isAnImmediateOperand(const MachineOperand &MO) {
2516   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2517 }
2518 
2519 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2520   auto &MBB = *MI.getParent();
2521   auto DL = MI.getDebugLoc();
2522 
2523   switch (MI.getOpcode()) {
2524   case PPC::BUILD_UACC: {
2525     MCRegister ACC = MI.getOperand(0).getReg();
2526     MCRegister UACC = MI.getOperand(1).getReg();
2527     if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
2528       MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
2529       MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
2530       // FIXME: This can easily be improved to look up to the top of the MBB
2531       // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
2532       // we can just re-target any such XXLOR's to DstVSR + offset.
2533       for (int VecNo = 0; VecNo < 4; VecNo++)
2534         BuildMI(MBB, MI, DL, get(PPC::XXLOR), DstVSR + VecNo)
2535             .addReg(SrcVSR + VecNo)
2536             .addReg(SrcVSR + VecNo);
2537     }
2538     // BUILD_UACC is expanded to 4 copies of the underlying vsx regisers.
2539     // So after building the 4 copies, we can replace the BUILD_UACC instruction
2540     // with a NOP.
2541     LLVM_FALLTHROUGH;
2542   }
2543   case PPC::KILL_PAIR: {
2544     MI.setDesc(get(PPC::UNENCODED_NOP));
2545     MI.RemoveOperand(1);
2546     MI.RemoveOperand(0);
2547     return true;
2548   }
2549   case TargetOpcode::LOAD_STACK_GUARD: {
2550     assert(Subtarget.isTargetLinux() &&
2551            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2552     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2553     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2554     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2555     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2556         .addImm(Offset)
2557         .addReg(Reg);
2558     return true;
2559   }
2560   case PPC::DFLOADf32:
2561   case PPC::DFLOADf64:
2562   case PPC::DFSTOREf32:
2563   case PPC::DFSTOREf64: {
2564     assert(Subtarget.hasP9Vector() &&
2565            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2566     assert(MI.getOperand(2).isReg() &&
2567            isAnImmediateOperand(MI.getOperand(1)) &&
2568            "D-form op must have register and immediate operands");
2569     return expandVSXMemPseudo(MI);
2570   }
2571   case PPC::XFLOADf32:
2572   case PPC::XFSTOREf32:
2573   case PPC::LIWAX:
2574   case PPC::LIWZX:
2575   case PPC::STIWX: {
2576     assert(Subtarget.hasP8Vector() &&
2577            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2578     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2579            "X-form op must have register and register operands");
2580     return expandVSXMemPseudo(MI);
2581   }
2582   case PPC::XFLOADf64:
2583   case PPC::XFSTOREf64: {
2584     assert(Subtarget.hasVSX() &&
2585            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2586     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2587            "X-form op must have register and register operands");
2588     return expandVSXMemPseudo(MI);
2589   }
2590   case PPC::SPILLTOVSR_LD: {
2591     Register TargetReg = MI.getOperand(0).getReg();
2592     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2593       MI.setDesc(get(PPC::DFLOADf64));
2594       return expandPostRAPseudo(MI);
2595     }
2596     else
2597       MI.setDesc(get(PPC::LD));
2598     return true;
2599   }
2600   case PPC::SPILLTOVSR_ST: {
2601     Register SrcReg = MI.getOperand(0).getReg();
2602     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2603       NumStoreSPILLVSRRCAsVec++;
2604       MI.setDesc(get(PPC::DFSTOREf64));
2605       return expandPostRAPseudo(MI);
2606     } else {
2607       NumStoreSPILLVSRRCAsGpr++;
2608       MI.setDesc(get(PPC::STD));
2609     }
2610     return true;
2611   }
2612   case PPC::SPILLTOVSR_LDX: {
2613     Register TargetReg = MI.getOperand(0).getReg();
2614     if (PPC::VSFRCRegClass.contains(TargetReg))
2615       MI.setDesc(get(PPC::LXSDX));
2616     else
2617       MI.setDesc(get(PPC::LDX));
2618     return true;
2619   }
2620   case PPC::SPILLTOVSR_STX: {
2621     Register SrcReg = MI.getOperand(0).getReg();
2622     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2623       NumStoreSPILLVSRRCAsVec++;
2624       MI.setDesc(get(PPC::STXSDX));
2625     } else {
2626       NumStoreSPILLVSRRCAsGpr++;
2627       MI.setDesc(get(PPC::STDX));
2628     }
2629     return true;
2630   }
2631 
2632   case PPC::CFENCE8: {
2633     auto Val = MI.getOperand(0).getReg();
2634     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2635     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2636         .addImm(PPC::PRED_NE_MINUS)
2637         .addReg(PPC::CR7)
2638         .addImm(1);
2639     MI.setDesc(get(PPC::ISYNC));
2640     MI.RemoveOperand(0);
2641     return true;
2642   }
2643   }
2644   return false;
2645 }
2646 
2647 // Essentially a compile-time implementation of a compare->isel sequence.
2648 // It takes two constants to compare, along with the true/false registers
2649 // and the comparison type (as a subreg to a CR field) and returns one
2650 // of the true/false registers, depending on the comparison results.
2651 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2652                           unsigned TrueReg, unsigned FalseReg,
2653                           unsigned CRSubReg) {
2654   // Signed comparisons. The immediates are assumed to be sign-extended.
2655   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2656     switch (CRSubReg) {
2657     default: llvm_unreachable("Unknown integer comparison type.");
2658     case PPC::sub_lt:
2659       return Imm1 < Imm2 ? TrueReg : FalseReg;
2660     case PPC::sub_gt:
2661       return Imm1 > Imm2 ? TrueReg : FalseReg;
2662     case PPC::sub_eq:
2663       return Imm1 == Imm2 ? TrueReg : FalseReg;
2664     }
2665   }
2666   // Unsigned comparisons.
2667   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2668     switch (CRSubReg) {
2669     default: llvm_unreachable("Unknown integer comparison type.");
2670     case PPC::sub_lt:
2671       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2672     case PPC::sub_gt:
2673       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2674     case PPC::sub_eq:
2675       return Imm1 == Imm2 ? TrueReg : FalseReg;
2676     }
2677   }
2678   return PPC::NoRegister;
2679 }
2680 
2681 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2682                                               unsigned OpNo,
2683                                               int64_t Imm) const {
2684   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2685   // Replace the REG with the Immediate.
2686   Register InUseReg = MI.getOperand(OpNo).getReg();
2687   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2688 
2689   if (MI.implicit_operands().empty())
2690     return;
2691 
2692   // We need to make sure that the MI didn't have any implicit use
2693   // of this REG any more.
2694   const TargetRegisterInfo *TRI = &getRegisterInfo();
2695   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2696   if (UseOpIdx >= 0) {
2697     MachineOperand &MO = MI.getOperand(UseOpIdx);
2698     if (MO.isImplicit())
2699       // The operands must always be in the following order:
2700       // - explicit reg defs,
2701       // - other explicit operands (reg uses, immediates, etc.),
2702       // - implicit reg defs
2703       // - implicit reg uses
2704       // Therefore, removing the implicit operand won't change the explicit
2705       // operands layout.
2706       MI.RemoveOperand(UseOpIdx);
2707   }
2708 }
2709 
2710 // Replace an instruction with one that materializes a constant (and sets
2711 // CR0 if the original instruction was a record-form instruction).
2712 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2713                                       const LoadImmediateInfo &LII) const {
2714   // Remove existing operands.
2715   int OperandToKeep = LII.SetCR ? 1 : 0;
2716   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2717     MI.RemoveOperand(i);
2718 
2719   // Replace the instruction.
2720   if (LII.SetCR) {
2721     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
2722     // Set the immediate.
2723     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2724         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2725     return;
2726   }
2727   else
2728     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2729 
2730   // Set the immediate.
2731   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2732       .addImm(LII.Imm);
2733 }
2734 
2735 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2736                                            bool &SeenIntermediateUse) const {
2737   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2738          "Should be called after register allocation.");
2739   const TargetRegisterInfo *TRI = &getRegisterInfo();
2740   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2741   It++;
2742   SeenIntermediateUse = false;
2743   for (; It != E; ++It) {
2744     if (It->modifiesRegister(Reg, TRI))
2745       return &*It;
2746     if (It->readsRegister(Reg, TRI))
2747       SeenIntermediateUse = true;
2748   }
2749   return nullptr;
2750 }
2751 
2752 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2753   MachineInstr &MI,
2754   unsigned &OpNoForForwarding,
2755   bool &SeenIntermediateUse) const {
2756   OpNoForForwarding = ~0U;
2757   MachineInstr *DefMI = nullptr;
2758   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2759   const TargetRegisterInfo *TRI = &getRegisterInfo();
2760   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2761   // within the basic block to see if the register is defined using an
2762   // LI/LI8/ADDI/ADDI8.
2763   if (MRI->isSSA()) {
2764     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2765       if (!MI.getOperand(i).isReg())
2766         continue;
2767       Register Reg = MI.getOperand(i).getReg();
2768       if (!Register::isVirtualRegister(Reg))
2769         continue;
2770       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2771       if (Register::isVirtualRegister(TrueReg)) {
2772         DefMI = MRI->getVRegDef(TrueReg);
2773         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8 ||
2774             DefMI->getOpcode() == PPC::ADDI ||
2775             DefMI->getOpcode() == PPC::ADDI8) {
2776           OpNoForForwarding = i;
2777           // The ADDI and LI operand maybe exist in one instruction at same
2778           // time. we prefer to fold LI operand as LI only has one Imm operand
2779           // and is more possible to be converted. So if current DefMI is
2780           // ADDI/ADDI8, we continue to find possible LI/LI8.
2781           if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
2782             break;
2783         }
2784       }
2785     }
2786   } else {
2787     // Looking back through the definition for each operand could be expensive,
2788     // so exit early if this isn't an instruction that either has an immediate
2789     // form or is already an immediate form that we can handle.
2790     ImmInstrInfo III;
2791     unsigned Opc = MI.getOpcode();
2792     bool ConvertibleImmForm =
2793         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
2794         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2795         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
2796         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
2797         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2798         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
2799         Opc == PPC::RLWINM8_rec;
2800     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2801                        ? isVFRegister(MI.getOperand(0).getReg())
2802                        : false;
2803     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2804       return nullptr;
2805 
2806     // Don't convert or %X, %Y, %Y since that's just a register move.
2807     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2808         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2809       return nullptr;
2810     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2811       MachineOperand &MO = MI.getOperand(i);
2812       SeenIntermediateUse = false;
2813       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2814         Register Reg = MI.getOperand(i).getReg();
2815         // If we see another use of this reg between the def and the MI,
2816         // we want to flat it so the def isn't deleted.
2817         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2818         if (DefMI) {
2819           // Is this register defined by some form of add-immediate (including
2820           // load-immediate) within this basic block?
2821           switch (DefMI->getOpcode()) {
2822           default:
2823             break;
2824           case PPC::LI:
2825           case PPC::LI8:
2826           case PPC::ADDItocL:
2827           case PPC::ADDI:
2828           case PPC::ADDI8:
2829             OpNoForForwarding = i;
2830             return DefMI;
2831           }
2832         }
2833       }
2834     }
2835   }
2836   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2837 }
2838 
2839 unsigned PPCInstrInfo::getSpillTarget() const {
2840   // With P10, we may need to spill paired vector registers or accumulator
2841   // registers. MMA implies paired vectors, so we can just check that.
2842   bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
2843   return IsP10Variant ? 2 : Subtarget.hasP9Vector() ? 1 : 0;
2844 }
2845 
2846 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2847   return StoreSpillOpcodesArray[getSpillTarget()];
2848 }
2849 
2850 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2851   return LoadSpillOpcodesArray[getSpillTarget()];
2852 }
2853 
2854 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr *StartMI, MachineInstr *EndMI,
2855                                      unsigned RegNo) const {
2856   // Conservatively clear kill flag for the register if the instructions are in
2857   // different basic blocks and in SSA form, because the kill flag may no longer
2858   // be right. There is no need to bother with dead flags since defs with no
2859   // uses will be handled by DCE.
2860   MachineRegisterInfo &MRI = StartMI->getParent()->getParent()->getRegInfo();
2861   if (MRI.isSSA() && (StartMI->getParent() != EndMI->getParent())) {
2862     MRI.clearKillFlags(RegNo);
2863     return;
2864   }
2865 
2866   // Instructions between [StartMI, EndMI] should be in same basic block.
2867   assert((StartMI->getParent() == EndMI->getParent()) &&
2868          "Instructions are not in same basic block");
2869 
2870   // If before RA, StartMI may be def through COPY, we need to adjust it to the
2871   // real def. See function getForwardingDefMI.
2872   if (MRI.isSSA()) {
2873     bool Reads, Writes;
2874     std::tie(Reads, Writes) = StartMI->readsWritesVirtualRegister(RegNo);
2875     if (!Reads && !Writes) {
2876       assert(Register::isVirtualRegister(RegNo) &&
2877              "Must be a virtual register");
2878       // Get real def and ignore copies.
2879       StartMI = MRI.getVRegDef(RegNo);
2880     }
2881   }
2882 
2883   bool IsKillSet = false;
2884 
2885   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2886     MachineOperand &MO = MI.getOperand(Index);
2887     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2888         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2889       MO.setIsKill(false);
2890   };
2891 
2892   // Set killed flag for EndMI.
2893   // No need to do anything if EndMI defines RegNo.
2894   int UseIndex =
2895       EndMI->findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2896   if (UseIndex != -1) {
2897     EndMI->getOperand(UseIndex).setIsKill(true);
2898     IsKillSet = true;
2899     // Clear killed flag for other EndMI operands related to RegNo. In some
2900     // upexpected cases, killed may be set multiple times for same register
2901     // operand in same MI.
2902     for (int i = 0, e = EndMI->getNumOperands(); i != e; ++i)
2903       if (i != UseIndex)
2904         clearOperandKillInfo(*EndMI, i);
2905   }
2906 
2907   // Walking the inst in reverse order (EndMI -> StartMI].
2908   MachineBasicBlock::reverse_iterator It = *EndMI;
2909   MachineBasicBlock::reverse_iterator E = EndMI->getParent()->rend();
2910   // EndMI has been handled above, skip it here.
2911   It++;
2912   MachineOperand *MO = nullptr;
2913   for (; It != E; ++It) {
2914     // Skip insturctions which could not be a def/use of RegNo.
2915     if (It->isDebugInstr() || It->isPosition())
2916       continue;
2917 
2918     // Clear killed flag for all It operands related to RegNo. In some
2919     // upexpected cases, killed may be set multiple times for same register
2920     // operand in same MI.
2921     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2922         clearOperandKillInfo(*It, i);
2923 
2924     // If killed is not set, set killed for its last use or set dead for its def
2925     // if no use found.
2926     if (!IsKillSet) {
2927       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2928         // Use found, set it killed.
2929         IsKillSet = true;
2930         MO->setIsKill(true);
2931         continue;
2932       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2933                                                   &getRegisterInfo()))) {
2934         // No use found, set dead for its def.
2935         assert(&*It == StartMI && "No new def between StartMI and EndMI.");
2936         MO->setIsDead(true);
2937         break;
2938       }
2939     }
2940 
2941     if ((&*It) == StartMI)
2942       break;
2943   }
2944   // Ensure RegMo liveness is killed after EndMI.
2945   assert((IsKillSet || (MO && MO->isDead())) &&
2946          "RegNo should be killed or dead");
2947 }
2948 
2949 // This opt tries to convert the following imm form to an index form to save an
2950 // add for stack variables.
2951 // Return false if no such pattern found.
2952 //
2953 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
2954 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
2955 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
2956 //
2957 // can be converted to:
2958 //
2959 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
2960 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
2961 //
2962 // In order to eliminate ADD instr, make sure that:
2963 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
2964 //    new ADDI instr and ADDI can only take int16 Imm.
2965 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
2966 //    between ADDI and ADD instr since its original def in ADDI will be changed
2967 //    in new ADDI instr. And also there should be no new def for it between
2968 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
2969 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
2970 //    between ADD and Imm instr since ADD instr will be eliminated.
2971 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
2972 //    moved to Index instr.
2973 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
2974   MachineFunction *MF = MI.getParent()->getParent();
2975   MachineRegisterInfo *MRI = &MF->getRegInfo();
2976   bool PostRA = !MRI->isSSA();
2977   // Do this opt after PEI which is after RA. The reason is stack slot expansion
2978   // in PEI may expose such opportunities since in PEI, stack slot offsets to
2979   // frame base(OffsetAddi) are determined.
2980   if (!PostRA)
2981     return false;
2982   unsigned ToBeDeletedReg = 0;
2983   int64_t OffsetImm = 0;
2984   unsigned XFormOpcode = 0;
2985   ImmInstrInfo III;
2986 
2987   // Check if Imm instr meets requirement.
2988   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
2989                                     III))
2990     return false;
2991 
2992   bool OtherIntermediateUse = false;
2993   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
2994 
2995   // Exit if there is other use between ADD and Imm instr or no def found.
2996   if (OtherIntermediateUse || !ADDMI)
2997     return false;
2998 
2999   // Check if ADD instr meets requirement.
3000   if (!isADDInstrEligibleForFolding(*ADDMI))
3001     return false;
3002 
3003   unsigned ScaleRegIdx = 0;
3004   int64_t OffsetAddi = 0;
3005   MachineInstr *ADDIMI = nullptr;
3006 
3007   // Check if there is a valid ToBeChangedReg in ADDMI.
3008   // 1: It must be killed.
3009   // 2: Its definition must be a valid ADDIMI.
3010   // 3: It must satify int16 offset requirement.
3011   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
3012     ScaleRegIdx = 2;
3013   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
3014     ScaleRegIdx = 1;
3015   else
3016     return false;
3017 
3018   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3019   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
3020   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
3021   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3022                        MachineBasicBlock::iterator End) {
3023     for (auto It = ++Start; It != End; It++)
3024       if (It->modifiesRegister(Reg, &getRegisterInfo()))
3025         return true;
3026     return false;
3027   };
3028 
3029   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3030   // treated as special zero when ScaleReg is R0/X0 register.
3031   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3032       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3033     return false;
3034 
3035   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3036   // and Imm Instr.
3037   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3038     return false;
3039 
3040   // Now start to do the transformation.
3041   LLVM_DEBUG(dbgs() << "Replace instruction: "
3042                     << "\n");
3043   LLVM_DEBUG(ADDIMI->dump());
3044   LLVM_DEBUG(ADDMI->dump());
3045   LLVM_DEBUG(MI.dump());
3046   LLVM_DEBUG(dbgs() << "with: "
3047                     << "\n");
3048 
3049   // Update ADDI instr.
3050   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
3051 
3052   // Update Imm instr.
3053   MI.setDesc(get(XFormOpcode));
3054   MI.getOperand(III.ImmOpNo)
3055       .ChangeToRegister(ScaleReg, false, false,
3056                         ADDMI->getOperand(ScaleRegIdx).isKill());
3057 
3058   MI.getOperand(III.OpNoForForwarding)
3059       .ChangeToRegister(ToBeChangedReg, false, false, true);
3060 
3061   // Eliminate ADD instr.
3062   ADDMI->eraseFromParent();
3063 
3064   LLVM_DEBUG(ADDIMI->dump());
3065   LLVM_DEBUG(MI.dump());
3066 
3067   return true;
3068 }
3069 
3070 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
3071                                                  int64_t &Imm) const {
3072   unsigned Opc = ADDIMI.getOpcode();
3073 
3074   // Exit if the instruction is not ADDI.
3075   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3076     return false;
3077 
3078   // The operand may not necessarily be an immediate - it could be a relocation.
3079   if (!ADDIMI.getOperand(2).isImm())
3080     return false;
3081 
3082   Imm = ADDIMI.getOperand(2).getImm();
3083 
3084   return true;
3085 }
3086 
3087 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
3088   unsigned Opc = ADDMI.getOpcode();
3089 
3090   // Exit if the instruction is not ADD.
3091   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3092 }
3093 
3094 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
3095                                                 unsigned &ToBeDeletedReg,
3096                                                 unsigned &XFormOpcode,
3097                                                 int64_t &OffsetImm,
3098                                                 ImmInstrInfo &III) const {
3099   // Only handle load/store.
3100   if (!MI.mayLoadOrStore())
3101     return false;
3102 
3103   unsigned Opc = MI.getOpcode();
3104 
3105   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
3106 
3107   // Exit if instruction has no index form.
3108   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3109     return false;
3110 
3111   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3112   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
3113                        III, true))
3114     return false;
3115 
3116   if (!III.IsSummingOperands)
3117     return false;
3118 
3119   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
3120   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
3121   // Only support imm operands, not relocation slots or others.
3122   if (!ImmOperand.isImm())
3123     return false;
3124 
3125   assert(RegOperand.isReg() && "Instruction format is not right");
3126 
3127   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3128   if (!RegOperand.isKill())
3129     return false;
3130 
3131   ToBeDeletedReg = RegOperand.getReg();
3132   OffsetImm = ImmOperand.getImm();
3133 
3134   return true;
3135 }
3136 
3137 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
3138                                          MachineInstr *&ADDIMI,
3139                                          int64_t &OffsetAddi,
3140                                          int64_t OffsetImm) const {
3141   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3142   MachineOperand &MO = ADDMI->getOperand(Index);
3143 
3144   if (!MO.isKill())
3145     return false;
3146 
3147   bool OtherIntermediateUse = false;
3148 
3149   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
3150   // Currently handle only one "add + Imminstr" pair case, exit if other
3151   // intermediate use for ToBeChangedReg found.
3152   // TODO: handle the cases where there are other "add + Imminstr" pairs
3153   // with same offset in Imminstr which is like:
3154   //
3155   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
3156   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3157   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
3158   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3159   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
3160   //
3161   // can be converted to:
3162   //
3163   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3164   //                                       (OffsetAddi + OffsetImm)
3165   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
3166   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
3167 
3168   if (OtherIntermediateUse || !ADDIMI)
3169     return false;
3170   // Check if ADDI instr meets requirement.
3171   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
3172     return false;
3173 
3174   if (isInt<16>(OffsetAddi + OffsetImm))
3175     return true;
3176   return false;
3177 }
3178 
3179 // If this instruction has an immediate form and one of its operands is a
3180 // result of a load-immediate or an add-immediate, convert it to
3181 // the immediate form if the constant is in range.
3182 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
3183                                           MachineInstr **KilledDef) const {
3184   MachineFunction *MF = MI.getParent()->getParent();
3185   MachineRegisterInfo *MRI = &MF->getRegInfo();
3186   bool PostRA = !MRI->isSSA();
3187   bool SeenIntermediateUse = true;
3188   unsigned ForwardingOperand = ~0U;
3189   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
3190                                            SeenIntermediateUse);
3191   if (!DefMI)
3192     return false;
3193   assert(ForwardingOperand < MI.getNumOperands() &&
3194          "The forwarding operand needs to be valid at this point");
3195   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
3196   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3197   if (KilledDef && KillFwdDefMI)
3198     *KilledDef = DefMI;
3199 
3200   // If this is a imm instruction and its register operands is produced by ADDI,
3201   // put the imm into imm inst directly.
3202   if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
3203           PPC::INSTRUCTION_LIST_END &&
3204       transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
3205     return true;
3206 
3207   ImmInstrInfo III;
3208   bool IsVFReg = MI.getOperand(0).isReg()
3209                      ? isVFRegister(MI.getOperand(0).getReg())
3210                      : false;
3211   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
3212   // If this is a reg+reg instruction that has a reg+imm form,
3213   // and one of the operands is produced by an add-immediate,
3214   // try to convert it.
3215   if (HasImmForm &&
3216       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
3217                                  KillFwdDefMI))
3218     return true;
3219 
3220   // If this is a reg+reg instruction that has a reg+imm form,
3221   // and one of the operands is produced by LI, convert it now.
3222   if (HasImmForm &&
3223       transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
3224     return true;
3225 
3226   // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3227   // can be simpified to LI.
3228   if (!HasImmForm && simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef))
3229     return true;
3230 
3231   return false;
3232 }
3233 
3234 // This function tries to combine two RLWINMs. We not only perform such
3235 // optimization in SSA, but also after RA, since some RLWINM is generated after
3236 // RA.
3237 bool PPCInstrInfo::simplifyRotateAndMaskInstr(MachineInstr &MI,
3238                                               MachineInstr *&ToErase) const {
3239   bool Is64Bit = false;
3240   switch (MI.getOpcode()) {
3241   case PPC::RLWINM:
3242   case PPC::RLWINM_rec:
3243     break;
3244   case PPC::RLWINM8:
3245   case PPC::RLWINM8_rec:
3246     Is64Bit = true;
3247     break;
3248   default:
3249     return false;
3250   }
3251   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3252   Register FoldingReg = MI.getOperand(1).getReg();
3253   MachineInstr *SrcMI = nullptr;
3254   bool CanErase = false;
3255   bool OtherIntermediateUse = true;
3256   if (MRI->isSSA()) {
3257     if (!Register::isVirtualRegister(FoldingReg))
3258       return false;
3259     SrcMI = MRI->getVRegDef(FoldingReg);
3260   } else {
3261     SrcMI = getDefMIPostRA(FoldingReg, MI, OtherIntermediateUse);
3262   }
3263   if (!SrcMI)
3264     return false;
3265   // TODO: The pairs of RLWINM8(RLWINM) or RLWINM(RLWINM8) never occur before
3266   // RA, but after RA. And We can fold RLWINM8(RLWINM) -> RLWINM8, or
3267   // RLWINM(RLWINM8) -> RLWINM.
3268   switch (SrcMI->getOpcode()) {
3269   case PPC::RLWINM:
3270   case PPC::RLWINM_rec:
3271     if (Is64Bit)
3272       return false;
3273     break;
3274   case PPC::RLWINM8:
3275   case PPC::RLWINM8_rec:
3276     if (!Is64Bit)
3277       return false;
3278     break;
3279   default:
3280     return false;
3281   }
3282   if (MRI->isSSA()) {
3283     CanErase = !SrcMI->hasImplicitDef() && MRI->hasOneNonDBGUse(FoldingReg);
3284   } else {
3285     CanErase = !OtherIntermediateUse && MI.getOperand(1).isKill() &&
3286                !SrcMI->hasImplicitDef();
3287     // In post-RA, if SrcMI also defines the register to be forwarded, we can
3288     // only do the folding if SrcMI is going to be erased.
3289     if (!CanErase && SrcMI->definesRegister(SrcMI->getOperand(1).getReg()))
3290       return false;
3291   }
3292   assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3293           MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3294           SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3295          "Invalid PPC::RLWINM Instruction!");
3296   uint64_t SHSrc = SrcMI->getOperand(2).getImm();
3297   uint64_t SHMI = MI.getOperand(2).getImm();
3298   uint64_t MBSrc = SrcMI->getOperand(3).getImm();
3299   uint64_t MBMI = MI.getOperand(3).getImm();
3300   uint64_t MESrc = SrcMI->getOperand(4).getImm();
3301   uint64_t MEMI = MI.getOperand(4).getImm();
3302   assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3303          "Invalid PPC::RLWINM Instruction!");
3304   // If MBMI is bigger than MEMI, we always can not get run of ones.
3305   // RotatedSrcMask non-wrap:
3306   //                 0........31|32........63
3307   // RotatedSrcMask:   B---E        B---E
3308   // MaskMI:         -----------|--E  B------
3309   // Result:           -----          ---      (Bad candidate)
3310   //
3311   // RotatedSrcMask wrap:
3312   //                 0........31|32........63
3313   // RotatedSrcMask: --E   B----|--E    B----
3314   // MaskMI:         -----------|--E  B------
3315   // Result:         ---   -----|---    -----  (Bad candidate)
3316   //
3317   // One special case is RotatedSrcMask is a full set mask.
3318   // RotatedSrcMask full:
3319   //                 0........31|32........63
3320   // RotatedSrcMask: ------EB---|-------EB---
3321   // MaskMI:         -----------|--E  B------
3322   // Result:         -----------|---  -------  (Good candidate)
3323 
3324   // Mark special case.
3325   bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3326 
3327   // For other MBMI > MEMI cases, just return.
3328   if ((MBMI > MEMI) && !SrcMaskFull)
3329     return false;
3330 
3331   // Handle MBMI <= MEMI cases.
3332   APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
3333   // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3334   // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3335   // while in PowerPC ISA, lowerest bit is at index 63.
3336   APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
3337 
3338   APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
3339   APInt FinalMask = RotatedSrcMask & MaskMI;
3340   uint32_t NewMB, NewME;
3341   bool Simplified = false;
3342 
3343   // If final mask is 0, MI result should be 0 too.
3344   if (FinalMask.isNullValue()) {
3345     Simplified = true;
3346     LLVM_DEBUG(dbgs() << "Replace Instr: ");
3347     LLVM_DEBUG(MI.dump());
3348 
3349     if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3350       // Replace MI with "LI 0"
3351       MI.RemoveOperand(4);
3352       MI.RemoveOperand(3);
3353       MI.RemoveOperand(2);
3354       MI.getOperand(1).ChangeToImmediate(0);
3355       MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
3356     } else {
3357       // Replace MI with "ANDI_rec reg, 0"
3358       MI.RemoveOperand(4);
3359       MI.RemoveOperand(3);
3360       MI.getOperand(2).setImm(0);
3361       MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3362       MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3363       if (SrcMI->getOperand(1).isKill()) {
3364         MI.getOperand(1).setIsKill(true);
3365         SrcMI->getOperand(1).setIsKill(false);
3366       } else
3367         // About to replace MI.getOperand(1), clear its kill flag.
3368         MI.getOperand(1).setIsKill(false);
3369     }
3370 
3371     LLVM_DEBUG(dbgs() << "With: ");
3372     LLVM_DEBUG(MI.dump());
3373 
3374   } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
3375               NewMB <= NewME) ||
3376              SrcMaskFull) {
3377     // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3378     // than NewME. Otherwise we get a 64 bit value after folding, but MI
3379     // return a 32 bit value.
3380     Simplified = true;
3381     LLVM_DEBUG(dbgs() << "Converting Instr: ");
3382     LLVM_DEBUG(MI.dump());
3383 
3384     uint16_t NewSH = (SHSrc + SHMI) % 32;
3385     MI.getOperand(2).setImm(NewSH);
3386     // If SrcMI mask is full, no need to update MBMI and MEMI.
3387     if (!SrcMaskFull) {
3388       MI.getOperand(3).setImm(NewMB);
3389       MI.getOperand(4).setImm(NewME);
3390     }
3391     MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3392     if (SrcMI->getOperand(1).isKill()) {
3393       MI.getOperand(1).setIsKill(true);
3394       SrcMI->getOperand(1).setIsKill(false);
3395     } else
3396       // About to replace MI.getOperand(1), clear its kill flag.
3397       MI.getOperand(1).setIsKill(false);
3398 
3399     LLVM_DEBUG(dbgs() << "To: ");
3400     LLVM_DEBUG(MI.dump());
3401   }
3402   if (Simplified && CanErase) {
3403     // If SrcMI has no implicit def, and FoldingReg has no non-debug use or
3404     // its flag is "killed", it's safe to delete SrcMI. Otherwise keep it.
3405     ToErase = SrcMI;
3406     LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
3407     LLVM_DEBUG(SrcMI->dump());
3408   }
3409   return Simplified;
3410 }
3411 
3412 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3413                                    ImmInstrInfo &III, bool PostRA) const {
3414   // The vast majority of the instructions would need their operand 2 replaced
3415   // with an immediate when switching to the reg+imm form. A marked exception
3416   // are the update form loads/stores for which a constant operand 2 would need
3417   // to turn into a displacement and move operand 1 to the operand 2 position.
3418   III.ImmOpNo = 2;
3419   III.OpNoForForwarding = 2;
3420   III.ImmWidth = 16;
3421   III.ImmMustBeMultipleOf = 1;
3422   III.TruncateImmTo = 0;
3423   III.IsSummingOperands = false;
3424   switch (Opc) {
3425   default: return false;
3426   case PPC::ADD4:
3427   case PPC::ADD8:
3428     III.SignedImm = true;
3429     III.ZeroIsSpecialOrig = 0;
3430     III.ZeroIsSpecialNew = 1;
3431     III.IsCommutative = true;
3432     III.IsSummingOperands = true;
3433     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3434     break;
3435   case PPC::ADDC:
3436   case PPC::ADDC8:
3437     III.SignedImm = true;
3438     III.ZeroIsSpecialOrig = 0;
3439     III.ZeroIsSpecialNew = 0;
3440     III.IsCommutative = true;
3441     III.IsSummingOperands = true;
3442     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3443     break;
3444   case PPC::ADDC_rec:
3445     III.SignedImm = true;
3446     III.ZeroIsSpecialOrig = 0;
3447     III.ZeroIsSpecialNew = 0;
3448     III.IsCommutative = true;
3449     III.IsSummingOperands = true;
3450     III.ImmOpcode = PPC::ADDIC_rec;
3451     break;
3452   case PPC::SUBFC:
3453   case PPC::SUBFC8:
3454     III.SignedImm = true;
3455     III.ZeroIsSpecialOrig = 0;
3456     III.ZeroIsSpecialNew = 0;
3457     III.IsCommutative = false;
3458     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3459     break;
3460   case PPC::CMPW:
3461   case PPC::CMPD:
3462     III.SignedImm = true;
3463     III.ZeroIsSpecialOrig = 0;
3464     III.ZeroIsSpecialNew = 0;
3465     III.IsCommutative = false;
3466     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3467     break;
3468   case PPC::CMPLW:
3469   case PPC::CMPLD:
3470     III.SignedImm = false;
3471     III.ZeroIsSpecialOrig = 0;
3472     III.ZeroIsSpecialNew = 0;
3473     III.IsCommutative = false;
3474     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3475     break;
3476   case PPC::AND_rec:
3477   case PPC::AND8_rec:
3478   case PPC::OR:
3479   case PPC::OR8:
3480   case PPC::XOR:
3481   case PPC::XOR8:
3482     III.SignedImm = false;
3483     III.ZeroIsSpecialOrig = 0;
3484     III.ZeroIsSpecialNew = 0;
3485     III.IsCommutative = true;
3486     switch(Opc) {
3487     default: llvm_unreachable("Unknown opcode");
3488     case PPC::AND_rec:
3489       III.ImmOpcode = PPC::ANDI_rec;
3490       break;
3491     case PPC::AND8_rec:
3492       III.ImmOpcode = PPC::ANDI8_rec;
3493       break;
3494     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3495     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3496     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3497     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3498     }
3499     break;
3500   case PPC::RLWNM:
3501   case PPC::RLWNM8:
3502   case PPC::RLWNM_rec:
3503   case PPC::RLWNM8_rec:
3504   case PPC::SLW:
3505   case PPC::SLW8:
3506   case PPC::SLW_rec:
3507   case PPC::SLW8_rec:
3508   case PPC::SRW:
3509   case PPC::SRW8:
3510   case PPC::SRW_rec:
3511   case PPC::SRW8_rec:
3512   case PPC::SRAW:
3513   case PPC::SRAW_rec:
3514     III.SignedImm = false;
3515     III.ZeroIsSpecialOrig = 0;
3516     III.ZeroIsSpecialNew = 0;
3517     III.IsCommutative = false;
3518     // This isn't actually true, but the instructions ignore any of the
3519     // upper bits, so any immediate loaded with an LI is acceptable.
3520     // This does not apply to shift right algebraic because a value
3521     // out of range will produce a -1/0.
3522     III.ImmWidth = 16;
3523     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3524         Opc == PPC::RLWNM8_rec)
3525       III.TruncateImmTo = 5;
3526     else
3527       III.TruncateImmTo = 6;
3528     switch(Opc) {
3529     default: llvm_unreachable("Unknown opcode");
3530     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3531     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3532     case PPC::RLWNM_rec:
3533       III.ImmOpcode = PPC::RLWINM_rec;
3534       break;
3535     case PPC::RLWNM8_rec:
3536       III.ImmOpcode = PPC::RLWINM8_rec;
3537       break;
3538     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3539     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3540     case PPC::SLW_rec:
3541       III.ImmOpcode = PPC::RLWINM_rec;
3542       break;
3543     case PPC::SLW8_rec:
3544       III.ImmOpcode = PPC::RLWINM8_rec;
3545       break;
3546     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3547     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3548     case PPC::SRW_rec:
3549       III.ImmOpcode = PPC::RLWINM_rec;
3550       break;
3551     case PPC::SRW8_rec:
3552       III.ImmOpcode = PPC::RLWINM8_rec;
3553       break;
3554     case PPC::SRAW:
3555       III.ImmWidth = 5;
3556       III.TruncateImmTo = 0;
3557       III.ImmOpcode = PPC::SRAWI;
3558       break;
3559     case PPC::SRAW_rec:
3560       III.ImmWidth = 5;
3561       III.TruncateImmTo = 0;
3562       III.ImmOpcode = PPC::SRAWI_rec;
3563       break;
3564     }
3565     break;
3566   case PPC::RLDCL:
3567   case PPC::RLDCL_rec:
3568   case PPC::RLDCR:
3569   case PPC::RLDCR_rec:
3570   case PPC::SLD:
3571   case PPC::SLD_rec:
3572   case PPC::SRD:
3573   case PPC::SRD_rec:
3574   case PPC::SRAD:
3575   case PPC::SRAD_rec:
3576     III.SignedImm = false;
3577     III.ZeroIsSpecialOrig = 0;
3578     III.ZeroIsSpecialNew = 0;
3579     III.IsCommutative = false;
3580     // This isn't actually true, but the instructions ignore any of the
3581     // upper bits, so any immediate loaded with an LI is acceptable.
3582     // This does not apply to shift right algebraic because a value
3583     // out of range will produce a -1/0.
3584     III.ImmWidth = 16;
3585     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3586         Opc == PPC::RLDCR_rec)
3587       III.TruncateImmTo = 6;
3588     else
3589       III.TruncateImmTo = 7;
3590     switch(Opc) {
3591     default: llvm_unreachable("Unknown opcode");
3592     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
3593     case PPC::RLDCL_rec:
3594       III.ImmOpcode = PPC::RLDICL_rec;
3595       break;
3596     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
3597     case PPC::RLDCR_rec:
3598       III.ImmOpcode = PPC::RLDICR_rec;
3599       break;
3600     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
3601     case PPC::SLD_rec:
3602       III.ImmOpcode = PPC::RLDICR_rec;
3603       break;
3604     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
3605     case PPC::SRD_rec:
3606       III.ImmOpcode = PPC::RLDICL_rec;
3607       break;
3608     case PPC::SRAD:
3609       III.ImmWidth = 6;
3610       III.TruncateImmTo = 0;
3611       III.ImmOpcode = PPC::SRADI;
3612        break;
3613     case PPC::SRAD_rec:
3614       III.ImmWidth = 6;
3615       III.TruncateImmTo = 0;
3616       III.ImmOpcode = PPC::SRADI_rec;
3617       break;
3618     }
3619     break;
3620   // Loads and stores:
3621   case PPC::LBZX:
3622   case PPC::LBZX8:
3623   case PPC::LHZX:
3624   case PPC::LHZX8:
3625   case PPC::LHAX:
3626   case PPC::LHAX8:
3627   case PPC::LWZX:
3628   case PPC::LWZX8:
3629   case PPC::LWAX:
3630   case PPC::LDX:
3631   case PPC::LFSX:
3632   case PPC::LFDX:
3633   case PPC::STBX:
3634   case PPC::STBX8:
3635   case PPC::STHX:
3636   case PPC::STHX8:
3637   case PPC::STWX:
3638   case PPC::STWX8:
3639   case PPC::STDX:
3640   case PPC::STFSX:
3641   case PPC::STFDX:
3642     III.SignedImm = true;
3643     III.ZeroIsSpecialOrig = 1;
3644     III.ZeroIsSpecialNew = 2;
3645     III.IsCommutative = true;
3646     III.IsSummingOperands = true;
3647     III.ImmOpNo = 1;
3648     III.OpNoForForwarding = 2;
3649     switch(Opc) {
3650     default: llvm_unreachable("Unknown opcode");
3651     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3652     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3653     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3654     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3655     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3656     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3657     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3658     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3659     case PPC::LWAX:
3660       III.ImmOpcode = PPC::LWA;
3661       III.ImmMustBeMultipleOf = 4;
3662       break;
3663     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3664     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3665     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3666     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3667     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3668     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3669     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3670     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3671     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3672     case PPC::STDX:
3673       III.ImmOpcode = PPC::STD;
3674       III.ImmMustBeMultipleOf = 4;
3675       break;
3676     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3677     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3678     }
3679     break;
3680   case PPC::LBZUX:
3681   case PPC::LBZUX8:
3682   case PPC::LHZUX:
3683   case PPC::LHZUX8:
3684   case PPC::LHAUX:
3685   case PPC::LHAUX8:
3686   case PPC::LWZUX:
3687   case PPC::LWZUX8:
3688   case PPC::LDUX:
3689   case PPC::LFSUX:
3690   case PPC::LFDUX:
3691   case PPC::STBUX:
3692   case PPC::STBUX8:
3693   case PPC::STHUX:
3694   case PPC::STHUX8:
3695   case PPC::STWUX:
3696   case PPC::STWUX8:
3697   case PPC::STDUX:
3698   case PPC::STFSUX:
3699   case PPC::STFDUX:
3700     III.SignedImm = true;
3701     III.ZeroIsSpecialOrig = 2;
3702     III.ZeroIsSpecialNew = 3;
3703     III.IsCommutative = false;
3704     III.IsSummingOperands = true;
3705     III.ImmOpNo = 2;
3706     III.OpNoForForwarding = 3;
3707     switch(Opc) {
3708     default: llvm_unreachable("Unknown opcode");
3709     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3710     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3711     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3712     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3713     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3714     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3715     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3716     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3717     case PPC::LDUX:
3718       III.ImmOpcode = PPC::LDU;
3719       III.ImmMustBeMultipleOf = 4;
3720       break;
3721     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3722     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3723     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3724     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3725     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3726     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3727     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3728     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3729     case PPC::STDUX:
3730       III.ImmOpcode = PPC::STDU;
3731       III.ImmMustBeMultipleOf = 4;
3732       break;
3733     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3734     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3735     }
3736     break;
3737   // Power9 and up only. For some of these, the X-Form version has access to all
3738   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3739   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3740   // into or stored from is one of the VR registers.
3741   case PPC::LXVX:
3742   case PPC::LXSSPX:
3743   case PPC::LXSDX:
3744   case PPC::STXVX:
3745   case PPC::STXSSPX:
3746   case PPC::STXSDX:
3747   case PPC::XFLOADf32:
3748   case PPC::XFLOADf64:
3749   case PPC::XFSTOREf32:
3750   case PPC::XFSTOREf64:
3751     if (!Subtarget.hasP9Vector())
3752       return false;
3753     III.SignedImm = true;
3754     III.ZeroIsSpecialOrig = 1;
3755     III.ZeroIsSpecialNew = 2;
3756     III.IsCommutative = true;
3757     III.IsSummingOperands = true;
3758     III.ImmOpNo = 1;
3759     III.OpNoForForwarding = 2;
3760     III.ImmMustBeMultipleOf = 4;
3761     switch(Opc) {
3762     default: llvm_unreachable("Unknown opcode");
3763     case PPC::LXVX:
3764       III.ImmOpcode = PPC::LXV;
3765       III.ImmMustBeMultipleOf = 16;
3766       break;
3767     case PPC::LXSSPX:
3768       if (PostRA) {
3769         if (IsVFReg)
3770           III.ImmOpcode = PPC::LXSSP;
3771         else {
3772           III.ImmOpcode = PPC::LFS;
3773           III.ImmMustBeMultipleOf = 1;
3774         }
3775         break;
3776       }
3777       LLVM_FALLTHROUGH;
3778     case PPC::XFLOADf32:
3779       III.ImmOpcode = PPC::DFLOADf32;
3780       break;
3781     case PPC::LXSDX:
3782       if (PostRA) {
3783         if (IsVFReg)
3784           III.ImmOpcode = PPC::LXSD;
3785         else {
3786           III.ImmOpcode = PPC::LFD;
3787           III.ImmMustBeMultipleOf = 1;
3788         }
3789         break;
3790       }
3791       LLVM_FALLTHROUGH;
3792     case PPC::XFLOADf64:
3793       III.ImmOpcode = PPC::DFLOADf64;
3794       break;
3795     case PPC::STXVX:
3796       III.ImmOpcode = PPC::STXV;
3797       III.ImmMustBeMultipleOf = 16;
3798       break;
3799     case PPC::STXSSPX:
3800       if (PostRA) {
3801         if (IsVFReg)
3802           III.ImmOpcode = PPC::STXSSP;
3803         else {
3804           III.ImmOpcode = PPC::STFS;
3805           III.ImmMustBeMultipleOf = 1;
3806         }
3807         break;
3808       }
3809       LLVM_FALLTHROUGH;
3810     case PPC::XFSTOREf32:
3811       III.ImmOpcode = PPC::DFSTOREf32;
3812       break;
3813     case PPC::STXSDX:
3814       if (PostRA) {
3815         if (IsVFReg)
3816           III.ImmOpcode = PPC::STXSD;
3817         else {
3818           III.ImmOpcode = PPC::STFD;
3819           III.ImmMustBeMultipleOf = 1;
3820         }
3821         break;
3822       }
3823       LLVM_FALLTHROUGH;
3824     case PPC::XFSTOREf64:
3825       III.ImmOpcode = PPC::DFSTOREf64;
3826       break;
3827     }
3828     break;
3829   }
3830   return true;
3831 }
3832 
3833 // Utility function for swaping two arbitrary operands of an instruction.
3834 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3835   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3836 
3837   unsigned MaxOp = std::max(Op1, Op2);
3838   unsigned MinOp = std::min(Op1, Op2);
3839   MachineOperand MOp1 = MI.getOperand(MinOp);
3840   MachineOperand MOp2 = MI.getOperand(MaxOp);
3841   MI.RemoveOperand(std::max(Op1, Op2));
3842   MI.RemoveOperand(std::min(Op1, Op2));
3843 
3844   // If the operands we are swapping are the two at the end (the common case)
3845   // we can just remove both and add them in the opposite order.
3846   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3847     MI.addOperand(MOp2);
3848     MI.addOperand(MOp1);
3849   } else {
3850     // Store all operands in a temporary vector, remove them and re-add in the
3851     // right order.
3852     SmallVector<MachineOperand, 2> MOps;
3853     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3854     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3855       MOps.push_back(MI.getOperand(i));
3856       MI.RemoveOperand(i);
3857     }
3858     // MOp2 needs to be added next.
3859     MI.addOperand(MOp2);
3860     // Now add the rest.
3861     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3862       if (i == MaxOp)
3863         MI.addOperand(MOp1);
3864       else {
3865         MI.addOperand(MOps.back());
3866         MOps.pop_back();
3867       }
3868     }
3869   }
3870 }
3871 
3872 // Check if the 'MI' that has the index OpNoForForwarding
3873 // meets the requirement described in the ImmInstrInfo.
3874 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3875                                                const ImmInstrInfo &III,
3876                                                unsigned OpNoForForwarding
3877                                                ) const {
3878   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3879   // would not work pre-RA, we can only do the check post RA.
3880   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3881   if (MRI.isSSA())
3882     return false;
3883 
3884   // Cannot do the transform if MI isn't summing the operands.
3885   if (!III.IsSummingOperands)
3886     return false;
3887 
3888   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3889   if (!III.ZeroIsSpecialOrig)
3890     return false;
3891 
3892   // We cannot do the transform if the operand we are trying to replace
3893   // isn't the same as the operand the instruction allows.
3894   if (OpNoForForwarding != III.OpNoForForwarding)
3895     return false;
3896 
3897   // Check if the instruction we are trying to transform really has
3898   // the special zero register as its operand.
3899   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3900       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3901     return false;
3902 
3903   // This machine instruction is convertible if it is,
3904   // 1. summing the operands.
3905   // 2. one of the operands is special zero register.
3906   // 3. the operand we are trying to replace is allowed by the MI.
3907   return true;
3908 }
3909 
3910 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3911 // accordingly.
3912 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3913                                                const ImmInstrInfo &III,
3914                                                MachineOperand *&ImmMO,
3915                                                MachineOperand *&RegMO) const {
3916   unsigned Opc = DefMI.getOpcode();
3917   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3918     return false;
3919 
3920   assert(DefMI.getNumOperands() >= 3 &&
3921          "Add inst must have at least three operands");
3922   RegMO = &DefMI.getOperand(1);
3923   ImmMO = &DefMI.getOperand(2);
3924 
3925   // Before RA, ADDI first operand could be a frame index.
3926   if (!RegMO->isReg())
3927     return false;
3928 
3929   // This DefMI is elgible for forwarding if it is:
3930   // 1. add inst
3931   // 2. one of the operands is Imm/CPI/Global.
3932   return isAnImmediateOperand(*ImmMO);
3933 }
3934 
3935 bool PPCInstrInfo::isRegElgibleForForwarding(
3936     const MachineOperand &RegMO, const MachineInstr &DefMI,
3937     const MachineInstr &MI, bool KillDefMI,
3938     bool &IsFwdFeederRegKilled) const {
3939   // x = addi y, imm
3940   // ...
3941   // z = lfdx 0, x   -> z = lfd imm(y)
3942   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3943   // of "y" between the DEF of "x" and "z".
3944   // The query is only valid post RA.
3945   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3946   if (MRI.isSSA())
3947     return false;
3948 
3949   Register Reg = RegMO.getReg();
3950 
3951   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3952   MachineBasicBlock::const_reverse_iterator It = MI;
3953   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3954   It++;
3955   for (; It != E; ++It) {
3956     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3957       return false;
3958     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3959       IsFwdFeederRegKilled = true;
3960     // Made it to DefMI without encountering a clobber.
3961     if ((&*It) == &DefMI)
3962       break;
3963   }
3964   assert((&*It) == &DefMI && "DefMI is missing");
3965 
3966   // If DefMI also defines the register to be forwarded, we can only forward it
3967   // if DefMI is being erased.
3968   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3969     return KillDefMI;
3970 
3971   return true;
3972 }
3973 
3974 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3975                                              const MachineInstr &DefMI,
3976                                              const ImmInstrInfo &III,
3977                                              int64_t &Imm,
3978                                              int64_t BaseImm) const {
3979   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3980   if (DefMI.getOpcode() == PPC::ADDItocL) {
3981     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3982     // However, we know that, it is 16-bit width, and has the alignment of 4.
3983     // Check if the instruction met the requirement.
3984     if (III.ImmMustBeMultipleOf > 4 ||
3985        III.TruncateImmTo || III.ImmWidth != 16)
3986       return false;
3987 
3988     // Going from XForm to DForm loads means that the displacement needs to be
3989     // not just an immediate but also a multiple of 4, or 16 depending on the
3990     // load. A DForm load cannot be represented if it is a multiple of say 2.
3991     // XForm loads do not have this restriction.
3992     if (ImmMO.isGlobal()) {
3993       const DataLayout &DL = ImmMO.getGlobal()->getParent()->getDataLayout();
3994       if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf)
3995         return false;
3996     }
3997 
3998     return true;
3999   }
4000 
4001   if (ImmMO.isImm()) {
4002     // It is Imm, we need to check if the Imm fit the range.
4003     // Sign-extend to 64-bits.
4004     // DefMI may be folded with another imm form instruction, the result Imm is
4005     // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
4006     Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
4007 
4008     if (Imm % III.ImmMustBeMultipleOf)
4009       return false;
4010     if (III.TruncateImmTo)
4011       Imm &= ((1 << III.TruncateImmTo) - 1);
4012     if (III.SignedImm) {
4013       APInt ActualValue(64, Imm, true);
4014       if (!ActualValue.isSignedIntN(III.ImmWidth))
4015         return false;
4016     } else {
4017       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
4018       if ((uint64_t)Imm > UnsignedMax)
4019         return false;
4020     }
4021   }
4022   else
4023     return false;
4024 
4025   // This ImmMO is forwarded if it meets the requriement describle
4026   // in ImmInstrInfo
4027   return true;
4028 }
4029 
4030 bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4031                                 unsigned OpNoForForwarding,
4032                                 MachineInstr **KilledDef) const {
4033   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4034       !DefMI.getOperand(1).isImm())
4035     return false;
4036 
4037   MachineFunction *MF = MI.getParent()->getParent();
4038   MachineRegisterInfo *MRI = &MF->getRegInfo();
4039   bool PostRA = !MRI->isSSA();
4040 
4041   int64_t Immediate = DefMI.getOperand(1).getImm();
4042   // Sign-extend to 64-bits.
4043   int64_t SExtImm = SignExtend64<16>(Immediate);
4044 
4045   bool IsForwardingOperandKilled = MI.getOperand(OpNoForForwarding).isKill();
4046   Register ForwardingOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4047 
4048   bool ReplaceWithLI = false;
4049   bool Is64BitLI = false;
4050   int64_t NewImm = 0;
4051   bool SetCR = false;
4052   unsigned Opc = MI.getOpcode();
4053   switch (Opc) {
4054   default:
4055     return false;
4056 
4057   // FIXME: Any branches conditional on such a comparison can be made
4058   // unconditional. At this time, this happens too infrequently to be worth
4059   // the implementation effort, but if that ever changes, we could convert
4060   // such a pattern here.
4061   case PPC::CMPWI:
4062   case PPC::CMPLWI:
4063   case PPC::CMPDI:
4064   case PPC::CMPLDI: {
4065     // Doing this post-RA would require dataflow analysis to reliably find uses
4066     // of the CR register set by the compare.
4067     // No need to fixup killed/dead flag since this transformation is only valid
4068     // before RA.
4069     if (PostRA)
4070       return false;
4071     // If a compare-immediate is fed by an immediate and is itself an input of
4072     // an ISEL (the most common case) into a COPY of the correct register.
4073     bool Changed = false;
4074     Register DefReg = MI.getOperand(0).getReg();
4075     int64_t Comparand = MI.getOperand(2).getImm();
4076     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4077                                 ? (Comparand | 0xFFFFFFFFFFFF0000)
4078                                 : Comparand;
4079 
4080     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
4081       unsigned UseOpc = CompareUseMI.getOpcode();
4082       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4083         continue;
4084       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
4085       Register TrueReg = CompareUseMI.getOperand(1).getReg();
4086       Register FalseReg = CompareUseMI.getOperand(2).getReg();
4087       unsigned RegToCopy =
4088           selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
4089       if (RegToCopy == PPC::NoRegister)
4090         continue;
4091       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4092       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4093         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4094         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
4095         CompareUseMI.RemoveOperand(3);
4096         CompareUseMI.RemoveOperand(2);
4097         continue;
4098       }
4099       LLVM_DEBUG(
4100           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4101       LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4102       LLVM_DEBUG(dbgs() << "Is converted to:\n");
4103       // Convert to copy and remove unneeded operands.
4104       CompareUseMI.setDesc(get(PPC::COPY));
4105       CompareUseMI.RemoveOperand(3);
4106       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
4107       CmpIselsConverted++;
4108       Changed = true;
4109       LLVM_DEBUG(CompareUseMI.dump());
4110     }
4111     if (Changed)
4112       return true;
4113     // This may end up incremented multiple times since this function is called
4114     // during a fixed-point transformation, but it is only meant to indicate the
4115     // presence of this opportunity.
4116     MissedConvertibleImmediateInstrs++;
4117     return false;
4118   }
4119 
4120   // Immediate forms - may simply be convertable to an LI.
4121   case PPC::ADDI:
4122   case PPC::ADDI8: {
4123     // Does the sum fit in a 16-bit signed field?
4124     int64_t Addend = MI.getOperand(2).getImm();
4125     if (isInt<16>(Addend + SExtImm)) {
4126       ReplaceWithLI = true;
4127       Is64BitLI = Opc == PPC::ADDI8;
4128       NewImm = Addend + SExtImm;
4129       break;
4130     }
4131     return false;
4132   }
4133   case PPC::SUBFIC:
4134   case PPC::SUBFIC8: {
4135     // Only transform this if the CARRY implicit operand is dead.
4136     if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
4137       return false;
4138     int64_t Minuend = MI.getOperand(2).getImm();
4139     if (isInt<16>(Minuend - SExtImm)) {
4140       ReplaceWithLI = true;
4141       Is64BitLI = Opc == PPC::SUBFIC8;
4142       NewImm = Minuend - SExtImm;
4143       break;
4144     }
4145     return false;
4146   }
4147   case PPC::RLDICL:
4148   case PPC::RLDICL_rec:
4149   case PPC::RLDICL_32:
4150   case PPC::RLDICL_32_64: {
4151     // Use APInt's rotate function.
4152     int64_t SH = MI.getOperand(2).getImm();
4153     int64_t MB = MI.getOperand(3).getImm();
4154     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4155                 SExtImm, true);
4156     InVal = InVal.rotl(SH);
4157     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4158     InVal &= Mask;
4159     // Can't replace negative values with an LI as that will sign-extend
4160     // and not clear the left bits. If we're setting the CR bit, we will use
4161     // ANDI_rec which won't sign extend, so that's safe.
4162     if (isUInt<15>(InVal.getSExtValue()) ||
4163         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
4164       ReplaceWithLI = true;
4165       Is64BitLI = Opc != PPC::RLDICL_32;
4166       NewImm = InVal.getSExtValue();
4167       SetCR = Opc == PPC::RLDICL_rec;
4168       break;
4169     }
4170     return false;
4171   }
4172   case PPC::RLWINM:
4173   case PPC::RLWINM8:
4174   case PPC::RLWINM_rec:
4175   case PPC::RLWINM8_rec: {
4176     int64_t SH = MI.getOperand(2).getImm();
4177     int64_t MB = MI.getOperand(3).getImm();
4178     int64_t ME = MI.getOperand(4).getImm();
4179     APInt InVal(32, SExtImm, true);
4180     InVal = InVal.rotl(SH);
4181     APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
4182     InVal &= Mask;
4183     // Can't replace negative values with an LI as that will sign-extend
4184     // and not clear the left bits. If we're setting the CR bit, we will use
4185     // ANDI_rec which won't sign extend, so that's safe.
4186     bool ValueFits = isUInt<15>(InVal.getSExtValue());
4187     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4188                   isUInt<16>(InVal.getSExtValue()));
4189     if (ValueFits) {
4190       ReplaceWithLI = true;
4191       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4192       NewImm = InVal.getSExtValue();
4193       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4194       break;
4195     }
4196     return false;
4197   }
4198   case PPC::ORI:
4199   case PPC::ORI8:
4200   case PPC::XORI:
4201   case PPC::XORI8: {
4202     int64_t LogicalImm = MI.getOperand(2).getImm();
4203     int64_t Result = 0;
4204     if (Opc == PPC::ORI || Opc == PPC::ORI8)
4205       Result = LogicalImm | SExtImm;
4206     else
4207       Result = LogicalImm ^ SExtImm;
4208     if (isInt<16>(Result)) {
4209       ReplaceWithLI = true;
4210       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4211       NewImm = Result;
4212       break;
4213     }
4214     return false;
4215   }
4216   }
4217 
4218   if (ReplaceWithLI) {
4219     // We need to be careful with CR-setting instructions we're replacing.
4220     if (SetCR) {
4221       // We don't know anything about uses when we're out of SSA, so only
4222       // replace if the new immediate will be reproduced.
4223       bool ImmChanged = (SExtImm & NewImm) != NewImm;
4224       if (PostRA && ImmChanged)
4225         return false;
4226 
4227       if (!PostRA) {
4228         // If the defining load-immediate has no other uses, we can just replace
4229         // the immediate with the new immediate.
4230         if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
4231           DefMI.getOperand(1).setImm(NewImm);
4232 
4233         // If we're not using the GPR result of the CR-setting instruction, we
4234         // just need to and with zero/non-zero depending on the new immediate.
4235         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
4236           if (NewImm) {
4237             assert(Immediate && "Transformation converted zero to non-zero?");
4238             NewImm = Immediate;
4239           }
4240         } else if (ImmChanged)
4241           return false;
4242       }
4243     }
4244 
4245     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4246     LLVM_DEBUG(MI.dump());
4247     LLVM_DEBUG(dbgs() << "Fed by:\n");
4248     LLVM_DEBUG(DefMI.dump());
4249     LoadImmediateInfo LII;
4250     LII.Imm = NewImm;
4251     LII.Is64Bit = Is64BitLI;
4252     LII.SetCR = SetCR;
4253     // If we're setting the CR, the original load-immediate must be kept (as an
4254     // operand to ANDI_rec/ANDI8_rec).
4255     if (KilledDef && SetCR)
4256       *KilledDef = nullptr;
4257     replaceInstrWithLI(MI, LII);
4258 
4259     // Fixup killed/dead flag after transformation.
4260     // Pattern:
4261     // ForwardingOperandReg = LI imm1
4262     // y = op2 imm2, ForwardingOperandReg(killed)
4263     if (IsForwardingOperandKilled)
4264       fixupIsDeadOrKill(&DefMI, &MI, ForwardingOperandReg);
4265 
4266     LLVM_DEBUG(dbgs() << "With:\n");
4267     LLVM_DEBUG(MI.dump());
4268     return true;
4269   }
4270   return false;
4271 }
4272 
4273 bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4274     MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4275   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4276   bool PostRA = !MRI->isSSA();
4277   // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4278   // for post-ra.
4279   if (PostRA)
4280     return false;
4281 
4282   // Only handle load/store.
4283   if (!MI.mayLoadOrStore())
4284     return false;
4285 
4286   unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
4287 
4288   assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4289          "MI must have x-form opcode");
4290 
4291   // get Imm Form info.
4292   ImmInstrInfo III;
4293   bool IsVFReg = MI.getOperand(0).isReg()
4294                      ? isVFRegister(MI.getOperand(0).getReg())
4295                      : false;
4296 
4297   if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
4298     return false;
4299 
4300   if (!III.IsSummingOperands)
4301     return false;
4302 
4303   if (OpNoForForwarding != III.OpNoForForwarding)
4304     return false;
4305 
4306   MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
4307   if (!ImmOperandMI.isImm())
4308     return false;
4309 
4310   // Check DefMI.
4311   MachineOperand *ImmMO = nullptr;
4312   MachineOperand *RegMO = nullptr;
4313   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4314     return false;
4315   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4316 
4317   // Check Imm.
4318   // Set ImmBase from imm instruction as base and get new Imm inside
4319   // isImmElgibleForForwarding.
4320   int64_t ImmBase = ImmOperandMI.getImm();
4321   int64_t Imm = 0;
4322   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
4323     return false;
4324 
4325   // Get killed info in case fixup needed after transformation.
4326   unsigned ForwardKilledOperandReg = ~0U;
4327   if (MI.getOperand(III.OpNoForForwarding).isKill())
4328     ForwardKilledOperandReg = MI.getOperand(III.OpNoForForwarding).getReg();
4329 
4330   // Do the transform
4331   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4332   LLVM_DEBUG(MI.dump());
4333   LLVM_DEBUG(dbgs() << "Fed by:\n");
4334   LLVM_DEBUG(DefMI.dump());
4335 
4336   MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
4337   MI.getOperand(III.OpNoForForwarding).setIsKill(RegMO->isKill());
4338   MI.getOperand(III.ImmOpNo).setImm(Imm);
4339 
4340   // FIXME: fix kill/dead flag if MI and DefMI are not in same basic block.
4341   if (DefMI.getParent() == MI.getParent()) {
4342     // Check if reg is killed between MI and DefMI.
4343     auto IsKilledFor = [&](unsigned Reg) {
4344       MachineBasicBlock::const_reverse_iterator It = MI;
4345       MachineBasicBlock::const_reverse_iterator E = DefMI;
4346       It++;
4347       for (; It != E; ++It) {
4348         if (It->killsRegister(Reg))
4349           return true;
4350       }
4351       return false;
4352     };
4353 
4354     // Update kill flag
4355     if (RegMO->isKill() || IsKilledFor(RegMO->getReg()))
4356       fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4357     if (ForwardKilledOperandReg != ~0U)
4358       fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4359   }
4360 
4361   LLVM_DEBUG(dbgs() << "With:\n");
4362   LLVM_DEBUG(MI.dump());
4363   return true;
4364 }
4365 
4366 // If an X-Form instruction is fed by an add-immediate and one of its operands
4367 // is the literal zero, attempt to forward the source of the add-immediate to
4368 // the corresponding D-Form instruction with the displacement coming from
4369 // the immediate being added.
4370 bool PPCInstrInfo::transformToImmFormFedByAdd(
4371     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4372     MachineInstr &DefMI, bool KillDefMI) const {
4373   //         RegMO ImmMO
4374   //           |    |
4375   // x = addi reg, imm  <----- DefMI
4376   // y = op    0 ,  x   <----- MI
4377   //                |
4378   //         OpNoForForwarding
4379   // Check if the MI meet the requirement described in the III.
4380   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4381     return false;
4382 
4383   // Check if the DefMI meet the requirement
4384   // described in the III. If yes, set the ImmMO and RegMO accordingly.
4385   MachineOperand *ImmMO = nullptr;
4386   MachineOperand *RegMO = nullptr;
4387   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4388     return false;
4389   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4390 
4391   // As we get the Imm operand now, we need to check if the ImmMO meet
4392   // the requirement described in the III. If yes set the Imm.
4393   int64_t Imm = 0;
4394   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
4395     return false;
4396 
4397   bool IsFwdFeederRegKilled = false;
4398   // Check if the RegMO can be forwarded to MI.
4399   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
4400                                  IsFwdFeederRegKilled))
4401     return false;
4402 
4403   // Get killed info in case fixup needed after transformation.
4404   unsigned ForwardKilledOperandReg = ~0U;
4405   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4406   bool PostRA = !MRI.isSSA();
4407   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
4408     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
4409 
4410   // We know that, the MI and DefMI both meet the pattern, and
4411   // the Imm also meet the requirement with the new Imm-form.
4412   // It is safe to do the transformation now.
4413   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
4414   LLVM_DEBUG(MI.dump());
4415   LLVM_DEBUG(dbgs() << "Fed by:\n");
4416   LLVM_DEBUG(DefMI.dump());
4417 
4418   // Update the base reg first.
4419   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
4420                                                         false, false,
4421                                                         RegMO->isKill());
4422 
4423   // Then, update the imm.
4424   if (ImmMO->isImm()) {
4425     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
4426     // directly.
4427     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
4428   }
4429   else {
4430     // Otherwise, it is Constant Pool Index(CPI) or Global,
4431     // which is relocation in fact. We need to replace the special zero
4432     // register with ImmMO.
4433     // Before that, we need to fixup the target flags for imm.
4434     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
4435     if (DefMI.getOpcode() == PPC::ADDItocL)
4436       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
4437 
4438     // MI didn't have the interface such as MI.setOperand(i) though
4439     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
4440     // ImmMO, we need to remove ZERO operand and all the operands behind it,
4441     // and, add the ImmMO, then, move back all the operands behind ZERO.
4442     SmallVector<MachineOperand, 2> MOps;
4443     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
4444       MOps.push_back(MI.getOperand(i));
4445       MI.RemoveOperand(i);
4446     }
4447 
4448     // Remove the last MO in the list, which is ZERO operand in fact.
4449     MOps.pop_back();
4450     // Add the imm operand.
4451     MI.addOperand(*ImmMO);
4452     // Now add the rest back.
4453     for (auto &MO : MOps)
4454       MI.addOperand(MO);
4455   }
4456 
4457   // Update the opcode.
4458   MI.setDesc(get(III.ImmOpcode));
4459 
4460   // Fix up killed/dead flag after transformation.
4461   // Pattern 1:
4462   // x = ADD KilledFwdFeederReg, imm
4463   // n = opn KilledFwdFeederReg(killed), regn
4464   // y = XOP 0, x
4465   // Pattern 2:
4466   // x = ADD reg(killed), imm
4467   // y = XOP 0, x
4468   if (IsFwdFeederRegKilled || RegMO->isKill())
4469     fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
4470   // Pattern 3:
4471   // ForwardKilledOperandReg = ADD reg, imm
4472   // y = XOP 0, ForwardKilledOperandReg(killed)
4473   if (ForwardKilledOperandReg != ~0U)
4474     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4475 
4476   LLVM_DEBUG(dbgs() << "With:\n");
4477   LLVM_DEBUG(MI.dump());
4478 
4479   return true;
4480 }
4481 
4482 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
4483                                              const ImmInstrInfo &III,
4484                                              unsigned ConstantOpNo,
4485                                              MachineInstr &DefMI) const {
4486   // DefMI must be LI or LI8.
4487   if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4488       !DefMI.getOperand(1).isImm())
4489     return false;
4490 
4491   // Get Imm operand and Sign-extend to 64-bits.
4492   int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
4493 
4494   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4495   bool PostRA = !MRI.isSSA();
4496   // Exit early if we can't convert this.
4497   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
4498     return false;
4499   if (Imm % III.ImmMustBeMultipleOf)
4500     return false;
4501   if (III.TruncateImmTo)
4502     Imm &= ((1 << III.TruncateImmTo) - 1);
4503   if (III.SignedImm) {
4504     APInt ActualValue(64, Imm, true);
4505     if (!ActualValue.isSignedIntN(III.ImmWidth))
4506       return false;
4507   } else {
4508     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
4509     if ((uint64_t)Imm > UnsignedMax)
4510       return false;
4511   }
4512 
4513   // If we're post-RA, the instructions don't agree on whether register zero is
4514   // special, we can transform this as long as the register operand that will
4515   // end up in the location where zero is special isn't R0.
4516   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
4517     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
4518       III.ZeroIsSpecialNew + 1;
4519     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
4520     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
4521     // If R0 is in the operand where zero is special for the new instruction,
4522     // it is unsafe to transform if the constant operand isn't that operand.
4523     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
4524         ConstantOpNo != III.ZeroIsSpecialNew)
4525       return false;
4526     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
4527         ConstantOpNo != PosForOrigZero)
4528       return false;
4529   }
4530 
4531   // Get killed info in case fixup needed after transformation.
4532   unsigned ForwardKilledOperandReg = ~0U;
4533   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
4534     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
4535 
4536   unsigned Opc = MI.getOpcode();
4537   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
4538                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
4539                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
4540                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
4541   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
4542                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
4543   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
4544                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
4545   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
4546                     Opc == PPC::SRD_rec;
4547 
4548   MI.setDesc(get(III.ImmOpcode));
4549   if (ConstantOpNo == III.OpNoForForwarding) {
4550     // Converting shifts to immediate form is a bit tricky since they may do
4551     // one of three things:
4552     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
4553     // 2. If the shift amount is zero, the result is unchanged (save for maybe
4554     //    setting CR0)
4555     // 3. If the shift amount is in [1, OpSize), it's just a shift
4556     if (SpecialShift32 || SpecialShift64) {
4557       LoadImmediateInfo LII;
4558       LII.Imm = 0;
4559       LII.SetCR = SetCR;
4560       LII.Is64Bit = SpecialShift64;
4561       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
4562       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
4563         replaceInstrWithLI(MI, LII);
4564       // Shifts by zero don't change the value. If we don't need to set CR0,
4565       // just convert this to a COPY. Can't do this post-RA since we've already
4566       // cleaned up the copies.
4567       else if (!SetCR && ShAmt == 0 && !PostRA) {
4568         MI.RemoveOperand(2);
4569         MI.setDesc(get(PPC::COPY));
4570       } else {
4571         // The 32 bit and 64 bit instructions are quite different.
4572         if (SpecialShift32) {
4573           // Left shifts use (N, 0, 31-N).
4574           // Right shifts use (32-N, N, 31) if 0 < N < 32.
4575           //              use (0, 0, 31)    if N == 0.
4576           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
4577           uint64_t MB = RightShift ? ShAmt : 0;
4578           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
4579           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4580           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
4581             .addImm(ME);
4582         } else {
4583           // Left shifts use (N, 63-N).
4584           // Right shifts use (64-N, N) if 0 < N < 64.
4585           //              use (0, 0)    if N == 0.
4586           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
4587           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
4588           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
4589           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
4590         }
4591       }
4592     } else
4593       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
4594   }
4595   // Convert commutative instructions (switch the operands and convert the
4596   // desired one to an immediate.
4597   else if (III.IsCommutative) {
4598     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
4599     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
4600   } else
4601     llvm_unreachable("Should have exited early!");
4602 
4603   // For instructions for which the constant register replaces a different
4604   // operand than where the immediate goes, we need to swap them.
4605   if (III.OpNoForForwarding != III.ImmOpNo)
4606     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
4607 
4608   // If the special R0/X0 register index are different for original instruction
4609   // and new instruction, we need to fix up the register class in new
4610   // instruction.
4611   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
4612     if (III.ZeroIsSpecialNew) {
4613       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
4614       // need to fix up register class.
4615       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
4616       if (Register::isVirtualRegister(RegToModify)) {
4617         const TargetRegisterClass *NewRC =
4618           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
4619           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
4620         MRI.setRegClass(RegToModify, NewRC);
4621       }
4622     }
4623   }
4624 
4625   // Fix up killed/dead flag after transformation.
4626   // Pattern:
4627   // ForwardKilledOperandReg = LI imm
4628   // y = XOP reg, ForwardKilledOperandReg(killed)
4629   if (ForwardKilledOperandReg != ~0U)
4630     fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
4631   return true;
4632 }
4633 
4634 const TargetRegisterClass *
4635 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
4636   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
4637     return &PPC::VSRCRegClass;
4638   return RC;
4639 }
4640 
4641 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
4642   return PPC::getRecordFormOpcode(Opcode);
4643 }
4644 
4645 // This function returns true if the machine instruction
4646 // always outputs a value by sign-extending a 32 bit value,
4647 // i.e. 0 to 31-th bits are same as 32-th bit.
4648 static bool isSignExtendingOp(const MachineInstr &MI) {
4649   int Opcode = MI.getOpcode();
4650   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
4651       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
4652       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
4653       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
4654       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
4655       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
4656       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
4657       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
4658       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
4659       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
4660       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
4661       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
4662       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
4663       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
4664       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
4665       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
4666       Opcode == PPC::EXTSB8_32_64)
4667     return true;
4668 
4669   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
4670     return true;
4671 
4672   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
4673        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
4674       MI.getOperand(3).getImm() > 0 &&
4675       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
4676     return true;
4677 
4678   return false;
4679 }
4680 
4681 // This function returns true if the machine instruction
4682 // always outputs zeros in higher 32 bits.
4683 static bool isZeroExtendingOp(const MachineInstr &MI) {
4684   int Opcode = MI.getOpcode();
4685   // The 16-bit immediate is sign-extended in li/lis.
4686   // If the most significant bit is zero, all higher bits are zero.
4687   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
4688       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
4689     int64_t Imm = MI.getOperand(1).getImm();
4690     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
4691       return true;
4692   }
4693 
4694   // We have some variations of rotate-and-mask instructions
4695   // that clear higher 32-bits.
4696   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
4697        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
4698        Opcode == PPC::RLDICL_32_64) &&
4699       MI.getOperand(3).getImm() >= 32)
4700     return true;
4701 
4702   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
4703       MI.getOperand(3).getImm() >= 32 &&
4704       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
4705     return true;
4706 
4707   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
4708        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
4709        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
4710       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
4711     return true;
4712 
4713   // There are other instructions that clear higher 32-bits.
4714   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
4715       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
4716       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
4717       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
4718       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
4719       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
4720       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
4721       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
4722       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
4723       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
4724       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
4725       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
4726       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
4727       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
4728       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
4729       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
4730       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
4731       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
4732       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
4733       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
4734       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
4735       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
4736       Opcode == PPC::MFVSRWZ)
4737     return true;
4738 
4739   return false;
4740 }
4741 
4742 // This function returns true if the input MachineInstr is a TOC save
4743 // instruction.
4744 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
4745   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
4746     return false;
4747   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4748   unsigned StackOffset = MI.getOperand(1).getImm();
4749   Register StackReg = MI.getOperand(2).getReg();
4750   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
4751     return true;
4752 
4753   return false;
4754 }
4755 
4756 // We limit the max depth to track incoming values of PHIs or binary ops
4757 // (e.g. AND) to avoid excessive cost.
4758 const unsigned MAX_DEPTH = 1;
4759 
4760 bool
4761 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
4762                                    const unsigned Depth) const {
4763   const MachineFunction *MF = MI.getParent()->getParent();
4764   const MachineRegisterInfo *MRI = &MF->getRegInfo();
4765 
4766   // If we know this instruction returns sign- or zero-extended result,
4767   // return true.
4768   if (SignExt ? isSignExtendingOp(MI):
4769                 isZeroExtendingOp(MI))
4770     return true;
4771 
4772   switch (MI.getOpcode()) {
4773   case PPC::COPY: {
4774     Register SrcReg = MI.getOperand(1).getReg();
4775 
4776     // In both ELFv1 and v2 ABI, method parameters and the return value
4777     // are sign- or zero-extended.
4778     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
4779       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
4780       // We check the ZExt/SExt flags for a method parameter.
4781       if (MI.getParent()->getBasicBlock() ==
4782           &MF->getFunction().getEntryBlock()) {
4783         Register VReg = MI.getOperand(0).getReg();
4784         if (MF->getRegInfo().isLiveIn(VReg))
4785           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
4786                            FuncInfo->isLiveInZExt(VReg);
4787       }
4788 
4789       // For a method return value, we check the ZExt/SExt flags in attribute.
4790       // We assume the following code sequence for method call.
4791       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
4792       //   BL8_NOP @func,...
4793       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
4794       //   %5 = COPY %x3; G8RC:%5
4795       if (SrcReg == PPC::X3) {
4796         const MachineBasicBlock *MBB = MI.getParent();
4797         MachineBasicBlock::const_instr_iterator II =
4798           MachineBasicBlock::const_instr_iterator(&MI);
4799         if (II != MBB->instr_begin() &&
4800             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
4801           const MachineInstr &CallMI = *(--II);
4802           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
4803             const Function *CalleeFn =
4804               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
4805             if (!CalleeFn)
4806               return false;
4807             const IntegerType *IntTy =
4808               dyn_cast<IntegerType>(CalleeFn->getReturnType());
4809             const AttributeSet &Attrs =
4810               CalleeFn->getAttributes().getRetAttributes();
4811             if (IntTy && IntTy->getBitWidth() <= 32)
4812               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
4813                                                   Attribute::ZExt);
4814           }
4815         }
4816       }
4817     }
4818 
4819     // If this is a copy from another register, we recursively check source.
4820     if (!Register::isVirtualRegister(SrcReg))
4821       return false;
4822     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4823     if (SrcMI != NULL)
4824       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4825 
4826     return false;
4827   }
4828 
4829   case PPC::ANDI_rec:
4830   case PPC::ANDIS_rec:
4831   case PPC::ORI:
4832   case PPC::ORIS:
4833   case PPC::XORI:
4834   case PPC::XORIS:
4835   case PPC::ANDI8_rec:
4836   case PPC::ANDIS8_rec:
4837   case PPC::ORI8:
4838   case PPC::ORIS8:
4839   case PPC::XORI8:
4840   case PPC::XORIS8: {
4841     // logical operation with 16-bit immediate does not change the upper bits.
4842     // So, we track the operand register as we do for register copy.
4843     Register SrcReg = MI.getOperand(1).getReg();
4844     if (!Register::isVirtualRegister(SrcReg))
4845       return false;
4846     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4847     if (SrcMI != NULL)
4848       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4849 
4850     return false;
4851   }
4852 
4853   // If all incoming values are sign-/zero-extended,
4854   // the output of OR, ISEL or PHI is also sign-/zero-extended.
4855   case PPC::OR:
4856   case PPC::OR8:
4857   case PPC::ISEL:
4858   case PPC::PHI: {
4859     if (Depth >= MAX_DEPTH)
4860       return false;
4861 
4862     // The input registers for PHI are operand 1, 3, ...
4863     // The input registers for others are operand 1 and 2.
4864     unsigned E = 3, D = 1;
4865     if (MI.getOpcode() == PPC::PHI) {
4866       E = MI.getNumOperands();
4867       D = 2;
4868     }
4869 
4870     for (unsigned I = 1; I != E; I += D) {
4871       if (MI.getOperand(I).isReg()) {
4872         Register SrcReg = MI.getOperand(I).getReg();
4873         if (!Register::isVirtualRegister(SrcReg))
4874           return false;
4875         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4876         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
4877           return false;
4878       }
4879       else
4880         return false;
4881     }
4882     return true;
4883   }
4884 
4885   // If at least one of the incoming values of an AND is zero extended
4886   // then the output is also zero-extended. If both of the incoming values
4887   // are sign-extended then the output is also sign extended.
4888   case PPC::AND:
4889   case PPC::AND8: {
4890     if (Depth >= MAX_DEPTH)
4891        return false;
4892 
4893     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
4894 
4895     Register SrcReg1 = MI.getOperand(1).getReg();
4896     Register SrcReg2 = MI.getOperand(2).getReg();
4897 
4898     if (!Register::isVirtualRegister(SrcReg1) ||
4899         !Register::isVirtualRegister(SrcReg2))
4900       return false;
4901 
4902     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
4903     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
4904     if (!MISrc1 || !MISrc2)
4905         return false;
4906 
4907     if(SignExt)
4908         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
4909                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4910     else
4911         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
4912                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4913   }
4914 
4915   default:
4916     break;
4917   }
4918   return false;
4919 }
4920 
4921 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
4922   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
4923 }
4924 
4925 namespace {
4926 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
4927   MachineInstr *Loop, *EndLoop, *LoopCount;
4928   MachineFunction *MF;
4929   const TargetInstrInfo *TII;
4930   int64_t TripCount;
4931 
4932 public:
4933   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
4934                        MachineInstr *LoopCount)
4935       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
4936         MF(Loop->getParent()->getParent()),
4937         TII(MF->getSubtarget().getInstrInfo()) {
4938     // Inspect the Loop instruction up-front, as it may be deleted when we call
4939     // createTripCountGreaterCondition.
4940     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
4941       TripCount = LoopCount->getOperand(1).getImm();
4942     else
4943       TripCount = -1;
4944   }
4945 
4946   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
4947     // Only ignore the terminator.
4948     return MI == EndLoop;
4949   }
4950 
4951   Optional<bool>
4952   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
4953                                   SmallVectorImpl<MachineOperand> &Cond) override {
4954     if (TripCount == -1) {
4955       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4956       // so we don't need to generate any thing here.
4957       Cond.push_back(MachineOperand::CreateImm(0));
4958       Cond.push_back(MachineOperand::CreateReg(
4959           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
4960           true));
4961       return {};
4962     }
4963 
4964     return TripCount > TC;
4965   }
4966 
4967   void setPreheader(MachineBasicBlock *NewPreheader) override {
4968     // Do nothing. We want the LOOP setup instruction to stay in the *old*
4969     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
4970   }
4971 
4972   void adjustTripCount(int TripCountAdjust) override {
4973     // If the loop trip count is a compile-time value, then just change the
4974     // value.
4975     if (LoopCount->getOpcode() == PPC::LI8 ||
4976         LoopCount->getOpcode() == PPC::LI) {
4977       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
4978       LoopCount->getOperand(1).setImm(TripCount);
4979       return;
4980     }
4981 
4982     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4983     // so we don't need to generate any thing here.
4984   }
4985 
4986   void disposed() override {
4987     Loop->eraseFromParent();
4988     // Ensure the loop setup instruction is deleted too.
4989     LoopCount->eraseFromParent();
4990   }
4991 };
4992 } // namespace
4993 
4994 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4995 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4996   // We really "analyze" only hardware loops right now.
4997   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4998   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4999   if (Preheader == LoopBB)
5000     Preheader = *std::next(LoopBB->pred_begin());
5001   MachineFunction *MF = Preheader->getParent();
5002 
5003   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
5004     SmallPtrSet<MachineBasicBlock *, 8> Visited;
5005     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
5006       Register LoopCountReg = LoopInst->getOperand(0).getReg();
5007       MachineRegisterInfo &MRI = MF->getRegInfo();
5008       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
5009       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
5010     }
5011   }
5012   return nullptr;
5013 }
5014 
5015 MachineInstr *PPCInstrInfo::findLoopInstr(
5016     MachineBasicBlock &PreHeader,
5017     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
5018 
5019   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5020 
5021   // The loop set-up instruction should be in preheader
5022   for (auto &I : PreHeader.instrs())
5023     if (I.getOpcode() == LOOPi)
5024       return &I;
5025   return nullptr;
5026 }
5027 
5028 // Return true if get the base operand, byte offset of an instruction and the
5029 // memory width. Width is the size of memory that is being loaded/stored.
5030 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
5031     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
5032     unsigned &Width, const TargetRegisterInfo *TRI) const {
5033   if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5034     return false;
5035 
5036   // Handle only loads/stores with base register followed by immediate offset.
5037   if (!LdSt.getOperand(1).isImm() ||
5038       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5039     return false;
5040   if (!LdSt.getOperand(1).isImm() ||
5041       (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5042     return false;
5043 
5044   if (!LdSt.hasOneMemOperand())
5045     return false;
5046 
5047   Width = (*LdSt.memoperands_begin())->getSize();
5048   Offset = LdSt.getOperand(1).getImm();
5049   BaseReg = &LdSt.getOperand(2);
5050   return true;
5051 }
5052 
5053 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
5054     const MachineInstr &MIa, const MachineInstr &MIb) const {
5055   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5056   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5057 
5058   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
5059       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
5060     return false;
5061 
5062   // Retrieve the base register, offset from the base register and width. Width
5063   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
5064   // base registers are identical, and the offset of a lower memory access +
5065   // the width doesn't overlap the offset of a higher memory access,
5066   // then the memory accesses are different.
5067   const TargetRegisterInfo *TRI = &getRegisterInfo();
5068   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5069   int64_t OffsetA = 0, OffsetB = 0;
5070   unsigned int WidthA = 0, WidthB = 0;
5071   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
5072       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
5073     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
5074       int LowOffset = std::min(OffsetA, OffsetB);
5075       int HighOffset = std::max(OffsetA, OffsetB);
5076       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5077       if (LowOffset + LowWidth <= HighOffset)
5078         return true;
5079     }
5080   }
5081   return false;
5082 }
5083