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