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