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                                          Register &SrcReg, Register &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                                    Register DstReg, Register TrueReg,
758                                    Register 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, Register DestReg,
796                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
797                                 Register 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   Register 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     Register 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.getObjectAlign(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.getObjectAlign(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                                  Register 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   MCRegister 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, Register &SrcReg,
1603                                   Register &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, Register SrcReg,
1633                                         Register 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   Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
1662   if (ActualSrc.isVirtual())
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"},
2050       {MO_PIC_FLAG, "ppc-pic"},
2051       {MO_PCREL_FLAG, "ppc-pcrel"},
2052       {MO_GOT_FLAG, "ppc-got"}};
2053   return makeArrayRef(TargetFlags);
2054 }
2055 
2056 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2057 // The VSX versions have the advantage of a full 64-register target whereas
2058 // the FP ones have the advantage of lower latency and higher throughput. So
2059 // what we are after is using the faster instructions in low register pressure
2060 // situations and using the larger register file in high register pressure
2061 // situations.
2062 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2063     unsigned UpperOpcode, LowerOpcode;
2064     switch (MI.getOpcode()) {
2065     case PPC::DFLOADf32:
2066       UpperOpcode = PPC::LXSSP;
2067       LowerOpcode = PPC::LFS;
2068       break;
2069     case PPC::DFLOADf64:
2070       UpperOpcode = PPC::LXSD;
2071       LowerOpcode = PPC::LFD;
2072       break;
2073     case PPC::DFSTOREf32:
2074       UpperOpcode = PPC::STXSSP;
2075       LowerOpcode = PPC::STFS;
2076       break;
2077     case PPC::DFSTOREf64:
2078       UpperOpcode = PPC::STXSD;
2079       LowerOpcode = PPC::STFD;
2080       break;
2081     case PPC::XFLOADf32:
2082       UpperOpcode = PPC::LXSSPX;
2083       LowerOpcode = PPC::LFSX;
2084       break;
2085     case PPC::XFLOADf64:
2086       UpperOpcode = PPC::LXSDX;
2087       LowerOpcode = PPC::LFDX;
2088       break;
2089     case PPC::XFSTOREf32:
2090       UpperOpcode = PPC::STXSSPX;
2091       LowerOpcode = PPC::STFSX;
2092       break;
2093     case PPC::XFSTOREf64:
2094       UpperOpcode = PPC::STXSDX;
2095       LowerOpcode = PPC::STFDX;
2096       break;
2097     case PPC::LIWAX:
2098       UpperOpcode = PPC::LXSIWAX;
2099       LowerOpcode = PPC::LFIWAX;
2100       break;
2101     case PPC::LIWZX:
2102       UpperOpcode = PPC::LXSIWZX;
2103       LowerOpcode = PPC::LFIWZX;
2104       break;
2105     case PPC::STIWX:
2106       UpperOpcode = PPC::STXSIWX;
2107       LowerOpcode = PPC::STFIWX;
2108       break;
2109     default:
2110       llvm_unreachable("Unknown Operation!");
2111     }
2112 
2113     Register TargetReg = MI.getOperand(0).getReg();
2114     unsigned Opcode;
2115     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2116         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2117       Opcode = LowerOpcode;
2118     else
2119       Opcode = UpperOpcode;
2120     MI.setDesc(get(Opcode));
2121     return true;
2122 }
2123 
2124 static bool isAnImmediateOperand(const MachineOperand &MO) {
2125   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2126 }
2127 
2128 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2129   auto &MBB = *MI.getParent();
2130   auto DL = MI.getDebugLoc();
2131 
2132   switch (MI.getOpcode()) {
2133   case TargetOpcode::LOAD_STACK_GUARD: {
2134     assert(Subtarget.isTargetLinux() &&
2135            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2136     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2137     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2138     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2139     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2140         .addImm(Offset)
2141         .addReg(Reg);
2142     return true;
2143   }
2144   case PPC::DFLOADf32:
2145   case PPC::DFLOADf64:
2146   case PPC::DFSTOREf32:
2147   case PPC::DFSTOREf64: {
2148     assert(Subtarget.hasP9Vector() &&
2149            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2150     assert(MI.getOperand(2).isReg() &&
2151            isAnImmediateOperand(MI.getOperand(1)) &&
2152            "D-form op must have register and immediate operands");
2153     return expandVSXMemPseudo(MI);
2154   }
2155   case PPC::XFLOADf32:
2156   case PPC::XFSTOREf32:
2157   case PPC::LIWAX:
2158   case PPC::LIWZX:
2159   case PPC::STIWX: {
2160     assert(Subtarget.hasP8Vector() &&
2161            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2162     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2163            "X-form op must have register and register operands");
2164     return expandVSXMemPseudo(MI);
2165   }
2166   case PPC::XFLOADf64:
2167   case PPC::XFSTOREf64: {
2168     assert(Subtarget.hasVSX() &&
2169            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2170     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2171            "X-form op must have register and register operands");
2172     return expandVSXMemPseudo(MI);
2173   }
2174   case PPC::SPILLTOVSR_LD: {
2175     Register TargetReg = MI.getOperand(0).getReg();
2176     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2177       MI.setDesc(get(PPC::DFLOADf64));
2178       return expandPostRAPseudo(MI);
2179     }
2180     else
2181       MI.setDesc(get(PPC::LD));
2182     return true;
2183   }
2184   case PPC::SPILLTOVSR_ST: {
2185     Register SrcReg = MI.getOperand(0).getReg();
2186     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2187       NumStoreSPILLVSRRCAsVec++;
2188       MI.setDesc(get(PPC::DFSTOREf64));
2189       return expandPostRAPseudo(MI);
2190     } else {
2191       NumStoreSPILLVSRRCAsGpr++;
2192       MI.setDesc(get(PPC::STD));
2193     }
2194     return true;
2195   }
2196   case PPC::SPILLTOVSR_LDX: {
2197     Register TargetReg = MI.getOperand(0).getReg();
2198     if (PPC::VSFRCRegClass.contains(TargetReg))
2199       MI.setDesc(get(PPC::LXSDX));
2200     else
2201       MI.setDesc(get(PPC::LDX));
2202     return true;
2203   }
2204   case PPC::SPILLTOVSR_STX: {
2205     Register SrcReg = MI.getOperand(0).getReg();
2206     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2207       NumStoreSPILLVSRRCAsVec++;
2208       MI.setDesc(get(PPC::STXSDX));
2209     } else {
2210       NumStoreSPILLVSRRCAsGpr++;
2211       MI.setDesc(get(PPC::STDX));
2212     }
2213     return true;
2214   }
2215 
2216   case PPC::CFENCE8: {
2217     auto Val = MI.getOperand(0).getReg();
2218     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2219     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2220         .addImm(PPC::PRED_NE_MINUS)
2221         .addReg(PPC::CR7)
2222         .addImm(1);
2223     MI.setDesc(get(PPC::ISYNC));
2224     MI.RemoveOperand(0);
2225     return true;
2226   }
2227   }
2228   return false;
2229 }
2230 
2231 // Essentially a compile-time implementation of a compare->isel sequence.
2232 // It takes two constants to compare, along with the true/false registers
2233 // and the comparison type (as a subreg to a CR field) and returns one
2234 // of the true/false registers, depending on the comparison results.
2235 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2236                           unsigned TrueReg, unsigned FalseReg,
2237                           unsigned CRSubReg) {
2238   // Signed comparisons. The immediates are assumed to be sign-extended.
2239   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2240     switch (CRSubReg) {
2241     default: llvm_unreachable("Unknown integer comparison type.");
2242     case PPC::sub_lt:
2243       return Imm1 < Imm2 ? TrueReg : FalseReg;
2244     case PPC::sub_gt:
2245       return Imm1 > Imm2 ? TrueReg : FalseReg;
2246     case PPC::sub_eq:
2247       return Imm1 == Imm2 ? TrueReg : FalseReg;
2248     }
2249   }
2250   // Unsigned comparisons.
2251   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2252     switch (CRSubReg) {
2253     default: llvm_unreachable("Unknown integer comparison type.");
2254     case PPC::sub_lt:
2255       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2256     case PPC::sub_gt:
2257       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2258     case PPC::sub_eq:
2259       return Imm1 == Imm2 ? TrueReg : FalseReg;
2260     }
2261   }
2262   return PPC::NoRegister;
2263 }
2264 
2265 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2266                                               unsigned OpNo,
2267                                               int64_t Imm) const {
2268   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2269   // Replace the REG with the Immediate.
2270   Register InUseReg = MI.getOperand(OpNo).getReg();
2271   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2272 
2273   if (MI.implicit_operands().empty())
2274     return;
2275 
2276   // We need to make sure that the MI didn't have any implicit use
2277   // of this REG any more.
2278   const TargetRegisterInfo *TRI = &getRegisterInfo();
2279   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2280   if (UseOpIdx >= 0) {
2281     MachineOperand &MO = MI.getOperand(UseOpIdx);
2282     if (MO.isImplicit())
2283       // The operands must always be in the following order:
2284       // - explicit reg defs,
2285       // - other explicit operands (reg uses, immediates, etc.),
2286       // - implicit reg defs
2287       // - implicit reg uses
2288       // Therefore, removing the implicit operand won't change the explicit
2289       // operands layout.
2290       MI.RemoveOperand(UseOpIdx);
2291   }
2292 }
2293 
2294 // Replace an instruction with one that materializes a constant (and sets
2295 // CR0 if the original instruction was a record-form instruction).
2296 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2297                                       const LoadImmediateInfo &LII) const {
2298   // Remove existing operands.
2299   int OperandToKeep = LII.SetCR ? 1 : 0;
2300   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2301     MI.RemoveOperand(i);
2302 
2303   // Replace the instruction.
2304   if (LII.SetCR) {
2305     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
2306     // Set the immediate.
2307     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2308         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2309     return;
2310   }
2311   else
2312     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2313 
2314   // Set the immediate.
2315   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2316       .addImm(LII.Imm);
2317 }
2318 
2319 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2320                                            bool &SeenIntermediateUse) const {
2321   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2322          "Should be called after register allocation.");
2323   const TargetRegisterInfo *TRI = &getRegisterInfo();
2324   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2325   It++;
2326   SeenIntermediateUse = false;
2327   for (; It != E; ++It) {
2328     if (It->modifiesRegister(Reg, TRI))
2329       return &*It;
2330     if (It->readsRegister(Reg, TRI))
2331       SeenIntermediateUse = true;
2332   }
2333   return nullptr;
2334 }
2335 
2336 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2337   MachineInstr &MI,
2338   unsigned &OpNoForForwarding,
2339   bool &SeenIntermediateUse) const {
2340   OpNoForForwarding = ~0U;
2341   MachineInstr *DefMI = nullptr;
2342   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2343   const TargetRegisterInfo *TRI = &getRegisterInfo();
2344   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2345   // within the basic block to see if the register is defined using an LI/LI8.
2346   if (MRI->isSSA()) {
2347     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2348       if (!MI.getOperand(i).isReg())
2349         continue;
2350       Register Reg = MI.getOperand(i).getReg();
2351       if (!Register::isVirtualRegister(Reg))
2352         continue;
2353       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2354       if (Register::isVirtualRegister(TrueReg)) {
2355         DefMI = MRI->getVRegDef(TrueReg);
2356         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) {
2357           OpNoForForwarding = i;
2358           break;
2359         }
2360       }
2361     }
2362   } else {
2363     // Looking back through the definition for each operand could be expensive,
2364     // so exit early if this isn't an instruction that either has an immediate
2365     // form or is already an immediate form that we can handle.
2366     ImmInstrInfo III;
2367     unsigned Opc = MI.getOpcode();
2368     bool ConvertibleImmForm =
2369         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
2370         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2371         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
2372         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
2373         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2374         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
2375         Opc == PPC::RLWINM8_rec;
2376     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2377                        ? isVFRegister(MI.getOperand(0).getReg())
2378                        : false;
2379     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2380       return nullptr;
2381 
2382     // Don't convert or %X, %Y, %Y since that's just a register move.
2383     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2384         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2385       return nullptr;
2386     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2387       MachineOperand &MO = MI.getOperand(i);
2388       SeenIntermediateUse = false;
2389       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2390         Register Reg = MI.getOperand(i).getReg();
2391         // If we see another use of this reg between the def and the MI,
2392         // we want to flat it so the def isn't deleted.
2393         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2394         if (DefMI) {
2395           // Is this register defined by some form of add-immediate (including
2396           // load-immediate) within this basic block?
2397           switch (DefMI->getOpcode()) {
2398           default:
2399             break;
2400           case PPC::LI:
2401           case PPC::LI8:
2402           case PPC::ADDItocL:
2403           case PPC::ADDI:
2404           case PPC::ADDI8:
2405             OpNoForForwarding = i;
2406             return DefMI;
2407           }
2408         }
2409       }
2410     }
2411   }
2412   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2413 }
2414 
2415 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2416   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2417       // Power 8
2418       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2419        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,
2420        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2421        PPC::SPILLTOVSR_ST, PPC::EVSTDD},
2422       // Power 9
2423       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2424        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,
2425        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2426        PPC::SPILLTOVSR_ST}};
2427 
2428   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2429 }
2430 
2431 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2432   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2433       // Power 8
2434       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2435        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,
2436        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2437        PPC::SPILLTOVSR_LD, PPC::EVLDD},
2438       // Power 9
2439       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2440        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32,
2441        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2442        PPC::SPILLTOVSR_LD}};
2443 
2444   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2445 }
2446 
2447 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI,
2448                                      unsigned RegNo) const {
2449   const MachineRegisterInfo &MRI =
2450       StartMI.getParent()->getParent()->getRegInfo();
2451   if (MRI.isSSA())
2452     return;
2453 
2454   // Instructions between [StartMI, EndMI] should be in same basic block.
2455   assert((StartMI.getParent() == EndMI.getParent()) &&
2456          "Instructions are not in same basic block");
2457 
2458   bool IsKillSet = false;
2459 
2460   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2461     MachineOperand &MO = MI.getOperand(Index);
2462     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2463         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2464       MO.setIsKill(false);
2465   };
2466 
2467   // Set killed flag for EndMI.
2468   // No need to do anything if EndMI defines RegNo.
2469   int UseIndex =
2470       EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2471   if (UseIndex != -1) {
2472     EndMI.getOperand(UseIndex).setIsKill(true);
2473     IsKillSet = true;
2474     // Clear killed flag for other EndMI operands related to RegNo. In some
2475     // upexpected cases, killed may be set multiple times for same register
2476     // operand in same MI.
2477     for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i)
2478       if (i != UseIndex)
2479         clearOperandKillInfo(EndMI, i);
2480   }
2481 
2482   // Walking the inst in reverse order (EndMI -> StartMI].
2483   MachineBasicBlock::reverse_iterator It = EndMI;
2484   MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend();
2485   // EndMI has been handled above, skip it here.
2486   It++;
2487   MachineOperand *MO = nullptr;
2488   for (; It != E; ++It) {
2489     // Skip insturctions which could not be a def/use of RegNo.
2490     if (It->isDebugInstr() || It->isPosition())
2491       continue;
2492 
2493     // Clear killed flag for all It operands related to RegNo. In some
2494     // upexpected cases, killed may be set multiple times for same register
2495     // operand in same MI.
2496     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2497         clearOperandKillInfo(*It, i);
2498 
2499     // If killed is not set, set killed for its last use or set dead for its def
2500     // if no use found.
2501     if (!IsKillSet) {
2502       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2503         // Use found, set it killed.
2504         IsKillSet = true;
2505         MO->setIsKill(true);
2506         continue;
2507       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2508                                                   &getRegisterInfo()))) {
2509         // No use found, set dead for its def.
2510         assert(&*It == &StartMI && "No new def between StartMI and EndMI.");
2511         MO->setIsDead(true);
2512         break;
2513       }
2514     }
2515 
2516     if ((&*It) == &StartMI)
2517       break;
2518   }
2519   // Ensure RegMo liveness is killed after EndMI.
2520   assert((IsKillSet || (MO && MO->isDead())) &&
2521          "RegNo should be killed or dead");
2522 }
2523 
2524 // This opt tries to convert the following imm form to an index form to save an
2525 // add for stack variables.
2526 // Return false if no such pattern found.
2527 //
2528 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
2529 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
2530 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
2531 //
2532 // can be converted to:
2533 //
2534 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
2535 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
2536 //
2537 // In order to eliminate ADD instr, make sure that:
2538 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
2539 //    new ADDI instr and ADDI can only take int16 Imm.
2540 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
2541 //    between ADDI and ADD instr since its original def in ADDI will be changed
2542 //    in new ADDI instr. And also there should be no new def for it between
2543 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
2544 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
2545 //    between ADD and Imm instr since ADD instr will be eliminated.
2546 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
2547 //    moved to Index instr.
2548 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
2549   MachineFunction *MF = MI.getParent()->getParent();
2550   MachineRegisterInfo *MRI = &MF->getRegInfo();
2551   bool PostRA = !MRI->isSSA();
2552   // Do this opt after PEI which is after RA. The reason is stack slot expansion
2553   // in PEI may expose such opportunities since in PEI, stack slot offsets to
2554   // frame base(OffsetAddi) are determined.
2555   if (!PostRA)
2556     return false;
2557   unsigned ToBeDeletedReg = 0;
2558   int64_t OffsetImm = 0;
2559   unsigned XFormOpcode = 0;
2560   ImmInstrInfo III;
2561 
2562   // Check if Imm instr meets requirement.
2563   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
2564                                     III))
2565     return false;
2566 
2567   bool OtherIntermediateUse = false;
2568   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
2569 
2570   // Exit if there is other use between ADD and Imm instr or no def found.
2571   if (OtherIntermediateUse || !ADDMI)
2572     return false;
2573 
2574   // Check if ADD instr meets requirement.
2575   if (!isADDInstrEligibleForFolding(*ADDMI))
2576     return false;
2577 
2578   unsigned ScaleRegIdx = 0;
2579   int64_t OffsetAddi = 0;
2580   MachineInstr *ADDIMI = nullptr;
2581 
2582   // Check if there is a valid ToBeChangedReg in ADDMI.
2583   // 1: It must be killed.
2584   // 2: Its definition must be a valid ADDIMI.
2585   // 3: It must satify int16 offset requirement.
2586   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
2587     ScaleRegIdx = 2;
2588   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
2589     ScaleRegIdx = 1;
2590   else
2591     return false;
2592 
2593   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
2594   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
2595   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
2596   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
2597                        MachineBasicBlock::iterator End) {
2598     for (auto It = ++Start; It != End; It++)
2599       if (It->modifiesRegister(Reg, &getRegisterInfo()))
2600         return true;
2601     return false;
2602   };
2603 
2604   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
2605   // treated as special zero when ScaleReg is R0/X0 register.
2606   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
2607       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
2608     return false;
2609 
2610   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
2611   // and Imm Instr.
2612   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
2613     return false;
2614 
2615   // Now start to do the transformation.
2616   LLVM_DEBUG(dbgs() << "Replace instruction: "
2617                     << "\n");
2618   LLVM_DEBUG(ADDIMI->dump());
2619   LLVM_DEBUG(ADDMI->dump());
2620   LLVM_DEBUG(MI.dump());
2621   LLVM_DEBUG(dbgs() << "with: "
2622                     << "\n");
2623 
2624   // Update ADDI instr.
2625   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
2626 
2627   // Update Imm instr.
2628   MI.setDesc(get(XFormOpcode));
2629   MI.getOperand(III.ImmOpNo)
2630       .ChangeToRegister(ScaleReg, false, false,
2631                         ADDMI->getOperand(ScaleRegIdx).isKill());
2632 
2633   MI.getOperand(III.OpNoForForwarding)
2634       .ChangeToRegister(ToBeChangedReg, false, false, true);
2635 
2636   // Eliminate ADD instr.
2637   ADDMI->eraseFromParent();
2638 
2639   LLVM_DEBUG(ADDIMI->dump());
2640   LLVM_DEBUG(MI.dump());
2641 
2642   return true;
2643 }
2644 
2645 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
2646                                                  int64_t &Imm) const {
2647   unsigned Opc = ADDIMI.getOpcode();
2648 
2649   // Exit if the instruction is not ADDI.
2650   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
2651     return false;
2652 
2653   Imm = ADDIMI.getOperand(2).getImm();
2654 
2655   return true;
2656 }
2657 
2658 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
2659   unsigned Opc = ADDMI.getOpcode();
2660 
2661   // Exit if the instruction is not ADD.
2662   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
2663 }
2664 
2665 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
2666                                                 unsigned &ToBeDeletedReg,
2667                                                 unsigned &XFormOpcode,
2668                                                 int64_t &OffsetImm,
2669                                                 ImmInstrInfo &III) const {
2670   // Only handle load/store.
2671   if (!MI.mayLoadOrStore())
2672     return false;
2673 
2674   unsigned Opc = MI.getOpcode();
2675 
2676   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
2677 
2678   // Exit if instruction has no index form.
2679   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
2680     return false;
2681 
2682   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
2683   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
2684                        III, true))
2685     return false;
2686 
2687   if (!III.IsSummingOperands)
2688     return false;
2689 
2690   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
2691   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
2692   // Only support imm operands, not relocation slots or others.
2693   if (!ImmOperand.isImm())
2694     return false;
2695 
2696   assert(RegOperand.isReg() && "Instruction format is not right");
2697 
2698   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
2699   if (!RegOperand.isKill())
2700     return false;
2701 
2702   ToBeDeletedReg = RegOperand.getReg();
2703   OffsetImm = ImmOperand.getImm();
2704 
2705   return true;
2706 }
2707 
2708 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
2709                                          MachineInstr *&ADDIMI,
2710                                          int64_t &OffsetAddi,
2711                                          int64_t OffsetImm) const {
2712   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
2713   MachineOperand &MO = ADDMI->getOperand(Index);
2714 
2715   if (!MO.isKill())
2716     return false;
2717 
2718   bool OtherIntermediateUse = false;
2719 
2720   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
2721   // Currently handle only one "add + Imminstr" pair case, exit if other
2722   // intermediate use for ToBeChangedReg found.
2723   // TODO: handle the cases where there are other "add + Imminstr" pairs
2724   // with same offset in Imminstr which is like:
2725   //
2726   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
2727   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
2728   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
2729   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
2730   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
2731   //
2732   // can be converted to:
2733   //
2734   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
2735   //                                       (OffsetAddi + OffsetImm)
2736   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
2737   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
2738 
2739   if (OtherIntermediateUse || !ADDIMI)
2740     return false;
2741   // Check if ADDI instr meets requirement.
2742   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
2743     return false;
2744 
2745   if (isInt<16>(OffsetAddi + OffsetImm))
2746     return true;
2747   return false;
2748 }
2749 
2750 // If this instruction has an immediate form and one of its operands is a
2751 // result of a load-immediate or an add-immediate, convert it to
2752 // the immediate form if the constant is in range.
2753 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
2754                                           MachineInstr **KilledDef) const {
2755   MachineFunction *MF = MI.getParent()->getParent();
2756   MachineRegisterInfo *MRI = &MF->getRegInfo();
2757   bool PostRA = !MRI->isSSA();
2758   bool SeenIntermediateUse = true;
2759   unsigned ForwardingOperand = ~0U;
2760   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
2761                                            SeenIntermediateUse);
2762   if (!DefMI)
2763     return false;
2764   assert(ForwardingOperand < MI.getNumOperands() &&
2765          "The forwarding operand needs to be valid at this point");
2766   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
2767   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
2768   Register ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg();
2769   if (KilledDef && KillFwdDefMI)
2770     *KilledDef = DefMI;
2771 
2772   ImmInstrInfo III;
2773   bool IsVFReg = MI.getOperand(0).isReg()
2774                      ? isVFRegister(MI.getOperand(0).getReg())
2775                      : false;
2776   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
2777   // If this is a reg+reg instruction that has a reg+imm form,
2778   // and one of the operands is produced by an add-immediate,
2779   // try to convert it.
2780   if (HasImmForm &&
2781       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
2782                                  KillFwdDefMI))
2783     return true;
2784 
2785   if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) ||
2786       !DefMI->getOperand(1).isImm())
2787     return false;
2788 
2789   int64_t Immediate = DefMI->getOperand(1).getImm();
2790   // Sign-extend to 64-bits.
2791   int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
2792     (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
2793 
2794   // If this is a reg+reg instruction that has a reg+imm form,
2795   // and one of the operands is produced by LI, convert it now.
2796   if (HasImmForm)
2797     return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm);
2798 
2799   bool ReplaceWithLI = false;
2800   bool Is64BitLI = false;
2801   int64_t NewImm = 0;
2802   bool SetCR = false;
2803   unsigned Opc = MI.getOpcode();
2804   switch (Opc) {
2805   default: return false;
2806 
2807   // FIXME: Any branches conditional on such a comparison can be made
2808   // unconditional. At this time, this happens too infrequently to be worth
2809   // the implementation effort, but if that ever changes, we could convert
2810   // such a pattern here.
2811   case PPC::CMPWI:
2812   case PPC::CMPLWI:
2813   case PPC::CMPDI:
2814   case PPC::CMPLDI: {
2815     // Doing this post-RA would require dataflow analysis to reliably find uses
2816     // of the CR register set by the compare.
2817     // No need to fixup killed/dead flag since this transformation is only valid
2818     // before RA.
2819     if (PostRA)
2820       return false;
2821     // If a compare-immediate is fed by an immediate and is itself an input of
2822     // an ISEL (the most common case) into a COPY of the correct register.
2823     bool Changed = false;
2824     Register DefReg = MI.getOperand(0).getReg();
2825     int64_t Comparand = MI.getOperand(2).getImm();
2826     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ?
2827       (Comparand | 0xFFFFFFFFFFFF0000) : Comparand;
2828 
2829     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
2830       unsigned UseOpc = CompareUseMI.getOpcode();
2831       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
2832         continue;
2833       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
2834       Register TrueReg = CompareUseMI.getOperand(1).getReg();
2835       Register FalseReg = CompareUseMI.getOperand(2).getReg();
2836       unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg,
2837                                      FalseReg, CRSubReg);
2838       if (RegToCopy == PPC::NoRegister)
2839         continue;
2840       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
2841       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
2842         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
2843         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
2844         CompareUseMI.RemoveOperand(3);
2845         CompareUseMI.RemoveOperand(2);
2846         continue;
2847       }
2848       LLVM_DEBUG(
2849           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
2850       LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump());
2851       LLVM_DEBUG(dbgs() << "Is converted to:\n");
2852       // Convert to copy and remove unneeded operands.
2853       CompareUseMI.setDesc(get(PPC::COPY));
2854       CompareUseMI.RemoveOperand(3);
2855       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
2856       CmpIselsConverted++;
2857       Changed = true;
2858       LLVM_DEBUG(CompareUseMI.dump());
2859     }
2860     if (Changed)
2861       return true;
2862     // This may end up incremented multiple times since this function is called
2863     // during a fixed-point transformation, but it is only meant to indicate the
2864     // presence of this opportunity.
2865     MissedConvertibleImmediateInstrs++;
2866     return false;
2867   }
2868 
2869   // Immediate forms - may simply be convertable to an LI.
2870   case PPC::ADDI:
2871   case PPC::ADDI8: {
2872     // Does the sum fit in a 16-bit signed field?
2873     int64_t Addend = MI.getOperand(2).getImm();
2874     if (isInt<16>(Addend + SExtImm)) {
2875       ReplaceWithLI = true;
2876       Is64BitLI = Opc == PPC::ADDI8;
2877       NewImm = Addend + SExtImm;
2878       break;
2879     }
2880     return false;
2881   }
2882   case PPC::RLDICL:
2883   case PPC::RLDICL_rec:
2884   case PPC::RLDICL_32:
2885   case PPC::RLDICL_32_64: {
2886     // Use APInt's rotate function.
2887     int64_t SH = MI.getOperand(2).getImm();
2888     int64_t MB = MI.getOperand(3).getImm();
2889     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
2890                 SExtImm, true);
2891     InVal = InVal.rotl(SH);
2892     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
2893     InVal &= Mask;
2894     // Can't replace negative values with an LI as that will sign-extend
2895     // and not clear the left bits. If we're setting the CR bit, we will use
2896     // ANDI_rec which won't sign extend, so that's safe.
2897     if (isUInt<15>(InVal.getSExtValue()) ||
2898         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
2899       ReplaceWithLI = true;
2900       Is64BitLI = Opc != PPC::RLDICL_32;
2901       NewImm = InVal.getSExtValue();
2902       SetCR = Opc == PPC::RLDICL_rec;
2903       break;
2904     }
2905     return false;
2906   }
2907   case PPC::RLWINM:
2908   case PPC::RLWINM8:
2909   case PPC::RLWINM_rec:
2910   case PPC::RLWINM8_rec: {
2911     int64_t SH = MI.getOperand(2).getImm();
2912     int64_t MB = MI.getOperand(3).getImm();
2913     int64_t ME = MI.getOperand(4).getImm();
2914     APInt InVal(32, SExtImm, true);
2915     InVal = InVal.rotl(SH);
2916     // Set the bits (        MB + 32        ) to (        ME + 32        ).
2917     uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2918     InVal &= Mask;
2919     // Can't replace negative values with an LI as that will sign-extend
2920     // and not clear the left bits. If we're setting the CR bit, we will use
2921     // ANDI_rec which won't sign extend, so that's safe.
2922     bool ValueFits = isUInt<15>(InVal.getSExtValue());
2923     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
2924                   isUInt<16>(InVal.getSExtValue()));
2925     if (ValueFits) {
2926       ReplaceWithLI = true;
2927       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
2928       NewImm = InVal.getSExtValue();
2929       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
2930       break;
2931     }
2932     return false;
2933   }
2934   case PPC::ORI:
2935   case PPC::ORI8:
2936   case PPC::XORI:
2937   case PPC::XORI8: {
2938     int64_t LogicalImm = MI.getOperand(2).getImm();
2939     int64_t Result = 0;
2940     if (Opc == PPC::ORI || Opc == PPC::ORI8)
2941       Result = LogicalImm | SExtImm;
2942     else
2943       Result = LogicalImm ^ SExtImm;
2944     if (isInt<16>(Result)) {
2945       ReplaceWithLI = true;
2946       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
2947       NewImm = Result;
2948       break;
2949     }
2950     return false;
2951   }
2952   }
2953 
2954   if (ReplaceWithLI) {
2955     // We need to be careful with CR-setting instructions we're replacing.
2956     if (SetCR) {
2957       // We don't know anything about uses when we're out of SSA, so only
2958       // replace if the new immediate will be reproduced.
2959       bool ImmChanged = (SExtImm & NewImm) != NewImm;
2960       if (PostRA && ImmChanged)
2961         return false;
2962 
2963       if (!PostRA) {
2964         // If the defining load-immediate has no other uses, we can just replace
2965         // the immediate with the new immediate.
2966         if (MRI->hasOneUse(DefMI->getOperand(0).getReg()))
2967           DefMI->getOperand(1).setImm(NewImm);
2968 
2969         // If we're not using the GPR result of the CR-setting instruction, we
2970         // just need to and with zero/non-zero depending on the new immediate.
2971         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
2972           if (NewImm) {
2973             assert(Immediate && "Transformation converted zero to non-zero?");
2974             NewImm = Immediate;
2975           }
2976         }
2977         else if (ImmChanged)
2978           return false;
2979       }
2980     }
2981 
2982     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
2983     LLVM_DEBUG(MI.dump());
2984     LLVM_DEBUG(dbgs() << "Fed by:\n");
2985     LLVM_DEBUG(DefMI->dump());
2986     LoadImmediateInfo LII;
2987     LII.Imm = NewImm;
2988     LII.Is64Bit = Is64BitLI;
2989     LII.SetCR = SetCR;
2990     // If we're setting the CR, the original load-immediate must be kept (as an
2991     // operand to ANDI_rec/ANDI8_rec).
2992     if (KilledDef && SetCR)
2993       *KilledDef = nullptr;
2994     replaceInstrWithLI(MI, LII);
2995 
2996     // Fixup killed/dead flag after transformation.
2997     // Pattern:
2998     // ForwardingOperandReg = LI imm1
2999     // y = op2 imm2, ForwardingOperandReg(killed)
3000     if (IsForwardingOperandKilled)
3001       fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg);
3002 
3003     LLVM_DEBUG(dbgs() << "With:\n");
3004     LLVM_DEBUG(MI.dump());
3005     return true;
3006   }
3007   return false;
3008 }
3009 
3010 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3011                                    ImmInstrInfo &III, bool PostRA) const {
3012   // The vast majority of the instructions would need their operand 2 replaced
3013   // with an immediate when switching to the reg+imm form. A marked exception
3014   // are the update form loads/stores for which a constant operand 2 would need
3015   // to turn into a displacement and move operand 1 to the operand 2 position.
3016   III.ImmOpNo = 2;
3017   III.OpNoForForwarding = 2;
3018   III.ImmWidth = 16;
3019   III.ImmMustBeMultipleOf = 1;
3020   III.TruncateImmTo = 0;
3021   III.IsSummingOperands = false;
3022   switch (Opc) {
3023   default: return false;
3024   case PPC::ADD4:
3025   case PPC::ADD8:
3026     III.SignedImm = true;
3027     III.ZeroIsSpecialOrig = 0;
3028     III.ZeroIsSpecialNew = 1;
3029     III.IsCommutative = true;
3030     III.IsSummingOperands = true;
3031     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3032     break;
3033   case PPC::ADDC:
3034   case PPC::ADDC8:
3035     III.SignedImm = true;
3036     III.ZeroIsSpecialOrig = 0;
3037     III.ZeroIsSpecialNew = 0;
3038     III.IsCommutative = true;
3039     III.IsSummingOperands = true;
3040     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3041     break;
3042   case PPC::ADDC_rec:
3043     III.SignedImm = true;
3044     III.ZeroIsSpecialOrig = 0;
3045     III.ZeroIsSpecialNew = 0;
3046     III.IsCommutative = true;
3047     III.IsSummingOperands = true;
3048     III.ImmOpcode = PPC::ADDIC_rec;
3049     break;
3050   case PPC::SUBFC:
3051   case PPC::SUBFC8:
3052     III.SignedImm = true;
3053     III.ZeroIsSpecialOrig = 0;
3054     III.ZeroIsSpecialNew = 0;
3055     III.IsCommutative = false;
3056     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3057     break;
3058   case PPC::CMPW:
3059   case PPC::CMPD:
3060     III.SignedImm = true;
3061     III.ZeroIsSpecialOrig = 0;
3062     III.ZeroIsSpecialNew = 0;
3063     III.IsCommutative = false;
3064     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3065     break;
3066   case PPC::CMPLW:
3067   case PPC::CMPLD:
3068     III.SignedImm = false;
3069     III.ZeroIsSpecialOrig = 0;
3070     III.ZeroIsSpecialNew = 0;
3071     III.IsCommutative = false;
3072     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3073     break;
3074   case PPC::AND_rec:
3075   case PPC::AND8_rec:
3076   case PPC::OR:
3077   case PPC::OR8:
3078   case PPC::XOR:
3079   case PPC::XOR8:
3080     III.SignedImm = false;
3081     III.ZeroIsSpecialOrig = 0;
3082     III.ZeroIsSpecialNew = 0;
3083     III.IsCommutative = true;
3084     switch(Opc) {
3085     default: llvm_unreachable("Unknown opcode");
3086     case PPC::AND_rec:
3087       III.ImmOpcode = PPC::ANDI_rec;
3088       break;
3089     case PPC::AND8_rec:
3090       III.ImmOpcode = PPC::ANDI8_rec;
3091       break;
3092     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3093     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3094     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3095     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3096     }
3097     break;
3098   case PPC::RLWNM:
3099   case PPC::RLWNM8:
3100   case PPC::RLWNM_rec:
3101   case PPC::RLWNM8_rec:
3102   case PPC::SLW:
3103   case PPC::SLW8:
3104   case PPC::SLW_rec:
3105   case PPC::SLW8_rec:
3106   case PPC::SRW:
3107   case PPC::SRW8:
3108   case PPC::SRW_rec:
3109   case PPC::SRW8_rec:
3110   case PPC::SRAW:
3111   case PPC::SRAW_rec:
3112     III.SignedImm = false;
3113     III.ZeroIsSpecialOrig = 0;
3114     III.ZeroIsSpecialNew = 0;
3115     III.IsCommutative = false;
3116     // This isn't actually true, but the instructions ignore any of the
3117     // upper bits, so any immediate loaded with an LI is acceptable.
3118     // This does not apply to shift right algebraic because a value
3119     // out of range will produce a -1/0.
3120     III.ImmWidth = 16;
3121     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3122         Opc == PPC::RLWNM8_rec)
3123       III.TruncateImmTo = 5;
3124     else
3125       III.TruncateImmTo = 6;
3126     switch(Opc) {
3127     default: llvm_unreachable("Unknown opcode");
3128     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3129     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3130     case PPC::RLWNM_rec:
3131       III.ImmOpcode = PPC::RLWINM_rec;
3132       break;
3133     case PPC::RLWNM8_rec:
3134       III.ImmOpcode = PPC::RLWINM8_rec;
3135       break;
3136     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3137     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3138     case PPC::SLW_rec:
3139       III.ImmOpcode = PPC::RLWINM_rec;
3140       break;
3141     case PPC::SLW8_rec:
3142       III.ImmOpcode = PPC::RLWINM8_rec;
3143       break;
3144     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3145     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3146     case PPC::SRW_rec:
3147       III.ImmOpcode = PPC::RLWINM_rec;
3148       break;
3149     case PPC::SRW8_rec:
3150       III.ImmOpcode = PPC::RLWINM8_rec;
3151       break;
3152     case PPC::SRAW:
3153       III.ImmWidth = 5;
3154       III.TruncateImmTo = 0;
3155       III.ImmOpcode = PPC::SRAWI;
3156       break;
3157     case PPC::SRAW_rec:
3158       III.ImmWidth = 5;
3159       III.TruncateImmTo = 0;
3160       III.ImmOpcode = PPC::SRAWI_rec;
3161       break;
3162     }
3163     break;
3164   case PPC::RLDCL:
3165   case PPC::RLDCL_rec:
3166   case PPC::RLDCR:
3167   case PPC::RLDCR_rec:
3168   case PPC::SLD:
3169   case PPC::SLD_rec:
3170   case PPC::SRD:
3171   case PPC::SRD_rec:
3172   case PPC::SRAD:
3173   case PPC::SRAD_rec:
3174     III.SignedImm = false;
3175     III.ZeroIsSpecialOrig = 0;
3176     III.ZeroIsSpecialNew = 0;
3177     III.IsCommutative = false;
3178     // This isn't actually true, but the instructions ignore any of the
3179     // upper bits, so any immediate loaded with an LI is acceptable.
3180     // This does not apply to shift right algebraic because a value
3181     // out of range will produce a -1/0.
3182     III.ImmWidth = 16;
3183     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3184         Opc == PPC::RLDCR_rec)
3185       III.TruncateImmTo = 6;
3186     else
3187       III.TruncateImmTo = 7;
3188     switch(Opc) {
3189     default: llvm_unreachable("Unknown opcode");
3190     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
3191     case PPC::RLDCL_rec:
3192       III.ImmOpcode = PPC::RLDICL_rec;
3193       break;
3194     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
3195     case PPC::RLDCR_rec:
3196       III.ImmOpcode = PPC::RLDICR_rec;
3197       break;
3198     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
3199     case PPC::SLD_rec:
3200       III.ImmOpcode = PPC::RLDICR_rec;
3201       break;
3202     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
3203     case PPC::SRD_rec:
3204       III.ImmOpcode = PPC::RLDICL_rec;
3205       break;
3206     case PPC::SRAD:
3207       III.ImmWidth = 6;
3208       III.TruncateImmTo = 0;
3209       III.ImmOpcode = PPC::SRADI;
3210        break;
3211     case PPC::SRAD_rec:
3212       III.ImmWidth = 6;
3213       III.TruncateImmTo = 0;
3214       III.ImmOpcode = PPC::SRADI_rec;
3215       break;
3216     }
3217     break;
3218   // Loads and stores:
3219   case PPC::LBZX:
3220   case PPC::LBZX8:
3221   case PPC::LHZX:
3222   case PPC::LHZX8:
3223   case PPC::LHAX:
3224   case PPC::LHAX8:
3225   case PPC::LWZX:
3226   case PPC::LWZX8:
3227   case PPC::LWAX:
3228   case PPC::LDX:
3229   case PPC::LFSX:
3230   case PPC::LFDX:
3231   case PPC::STBX:
3232   case PPC::STBX8:
3233   case PPC::STHX:
3234   case PPC::STHX8:
3235   case PPC::STWX:
3236   case PPC::STWX8:
3237   case PPC::STDX:
3238   case PPC::STFSX:
3239   case PPC::STFDX:
3240     III.SignedImm = true;
3241     III.ZeroIsSpecialOrig = 1;
3242     III.ZeroIsSpecialNew = 2;
3243     III.IsCommutative = true;
3244     III.IsSummingOperands = true;
3245     III.ImmOpNo = 1;
3246     III.OpNoForForwarding = 2;
3247     switch(Opc) {
3248     default: llvm_unreachable("Unknown opcode");
3249     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3250     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3251     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3252     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3253     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3254     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3255     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3256     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3257     case PPC::LWAX:
3258       III.ImmOpcode = PPC::LWA;
3259       III.ImmMustBeMultipleOf = 4;
3260       break;
3261     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3262     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3263     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3264     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3265     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3266     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3267     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3268     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3269     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3270     case PPC::STDX:
3271       III.ImmOpcode = PPC::STD;
3272       III.ImmMustBeMultipleOf = 4;
3273       break;
3274     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3275     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3276     }
3277     break;
3278   case PPC::LBZUX:
3279   case PPC::LBZUX8:
3280   case PPC::LHZUX:
3281   case PPC::LHZUX8:
3282   case PPC::LHAUX:
3283   case PPC::LHAUX8:
3284   case PPC::LWZUX:
3285   case PPC::LWZUX8:
3286   case PPC::LDUX:
3287   case PPC::LFSUX:
3288   case PPC::LFDUX:
3289   case PPC::STBUX:
3290   case PPC::STBUX8:
3291   case PPC::STHUX:
3292   case PPC::STHUX8:
3293   case PPC::STWUX:
3294   case PPC::STWUX8:
3295   case PPC::STDUX:
3296   case PPC::STFSUX:
3297   case PPC::STFDUX:
3298     III.SignedImm = true;
3299     III.ZeroIsSpecialOrig = 2;
3300     III.ZeroIsSpecialNew = 3;
3301     III.IsCommutative = false;
3302     III.IsSummingOperands = true;
3303     III.ImmOpNo = 2;
3304     III.OpNoForForwarding = 3;
3305     switch(Opc) {
3306     default: llvm_unreachable("Unknown opcode");
3307     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3308     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3309     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3310     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3311     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3312     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3313     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3314     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3315     case PPC::LDUX:
3316       III.ImmOpcode = PPC::LDU;
3317       III.ImmMustBeMultipleOf = 4;
3318       break;
3319     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3320     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3321     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3322     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3323     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3324     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3325     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3326     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3327     case PPC::STDUX:
3328       III.ImmOpcode = PPC::STDU;
3329       III.ImmMustBeMultipleOf = 4;
3330       break;
3331     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3332     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3333     }
3334     break;
3335   // Power9 and up only. For some of these, the X-Form version has access to all
3336   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3337   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3338   // into or stored from is one of the VR registers.
3339   case PPC::LXVX:
3340   case PPC::LXSSPX:
3341   case PPC::LXSDX:
3342   case PPC::STXVX:
3343   case PPC::STXSSPX:
3344   case PPC::STXSDX:
3345   case PPC::XFLOADf32:
3346   case PPC::XFLOADf64:
3347   case PPC::XFSTOREf32:
3348   case PPC::XFSTOREf64:
3349     if (!Subtarget.hasP9Vector())
3350       return false;
3351     III.SignedImm = true;
3352     III.ZeroIsSpecialOrig = 1;
3353     III.ZeroIsSpecialNew = 2;
3354     III.IsCommutative = true;
3355     III.IsSummingOperands = true;
3356     III.ImmOpNo = 1;
3357     III.OpNoForForwarding = 2;
3358     III.ImmMustBeMultipleOf = 4;
3359     switch(Opc) {
3360     default: llvm_unreachable("Unknown opcode");
3361     case PPC::LXVX:
3362       III.ImmOpcode = PPC::LXV;
3363       III.ImmMustBeMultipleOf = 16;
3364       break;
3365     case PPC::LXSSPX:
3366       if (PostRA) {
3367         if (IsVFReg)
3368           III.ImmOpcode = PPC::LXSSP;
3369         else {
3370           III.ImmOpcode = PPC::LFS;
3371           III.ImmMustBeMultipleOf = 1;
3372         }
3373         break;
3374       }
3375       LLVM_FALLTHROUGH;
3376     case PPC::XFLOADf32:
3377       III.ImmOpcode = PPC::DFLOADf32;
3378       break;
3379     case PPC::LXSDX:
3380       if (PostRA) {
3381         if (IsVFReg)
3382           III.ImmOpcode = PPC::LXSD;
3383         else {
3384           III.ImmOpcode = PPC::LFD;
3385           III.ImmMustBeMultipleOf = 1;
3386         }
3387         break;
3388       }
3389       LLVM_FALLTHROUGH;
3390     case PPC::XFLOADf64:
3391       III.ImmOpcode = PPC::DFLOADf64;
3392       break;
3393     case PPC::STXVX:
3394       III.ImmOpcode = PPC::STXV;
3395       III.ImmMustBeMultipleOf = 16;
3396       break;
3397     case PPC::STXSSPX:
3398       if (PostRA) {
3399         if (IsVFReg)
3400           III.ImmOpcode = PPC::STXSSP;
3401         else {
3402           III.ImmOpcode = PPC::STFS;
3403           III.ImmMustBeMultipleOf = 1;
3404         }
3405         break;
3406       }
3407       LLVM_FALLTHROUGH;
3408     case PPC::XFSTOREf32:
3409       III.ImmOpcode = PPC::DFSTOREf32;
3410       break;
3411     case PPC::STXSDX:
3412       if (PostRA) {
3413         if (IsVFReg)
3414           III.ImmOpcode = PPC::STXSD;
3415         else {
3416           III.ImmOpcode = PPC::STFD;
3417           III.ImmMustBeMultipleOf = 1;
3418         }
3419         break;
3420       }
3421       LLVM_FALLTHROUGH;
3422     case PPC::XFSTOREf64:
3423       III.ImmOpcode = PPC::DFSTOREf64;
3424       break;
3425     }
3426     break;
3427   }
3428   return true;
3429 }
3430 
3431 // Utility function for swaping two arbitrary operands of an instruction.
3432 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3433   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3434 
3435   unsigned MaxOp = std::max(Op1, Op2);
3436   unsigned MinOp = std::min(Op1, Op2);
3437   MachineOperand MOp1 = MI.getOperand(MinOp);
3438   MachineOperand MOp2 = MI.getOperand(MaxOp);
3439   MI.RemoveOperand(std::max(Op1, Op2));
3440   MI.RemoveOperand(std::min(Op1, Op2));
3441 
3442   // If the operands we are swapping are the two at the end (the common case)
3443   // we can just remove both and add them in the opposite order.
3444   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3445     MI.addOperand(MOp2);
3446     MI.addOperand(MOp1);
3447   } else {
3448     // Store all operands in a temporary vector, remove them and re-add in the
3449     // right order.
3450     SmallVector<MachineOperand, 2> MOps;
3451     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3452     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3453       MOps.push_back(MI.getOperand(i));
3454       MI.RemoveOperand(i);
3455     }
3456     // MOp2 needs to be added next.
3457     MI.addOperand(MOp2);
3458     // Now add the rest.
3459     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3460       if (i == MaxOp)
3461         MI.addOperand(MOp1);
3462       else {
3463         MI.addOperand(MOps.back());
3464         MOps.pop_back();
3465       }
3466     }
3467   }
3468 }
3469 
3470 // Check if the 'MI' that has the index OpNoForForwarding
3471 // meets the requirement described in the ImmInstrInfo.
3472 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3473                                                const ImmInstrInfo &III,
3474                                                unsigned OpNoForForwarding
3475                                                ) const {
3476   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3477   // would not work pre-RA, we can only do the check post RA.
3478   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3479   if (MRI.isSSA())
3480     return false;
3481 
3482   // Cannot do the transform if MI isn't summing the operands.
3483   if (!III.IsSummingOperands)
3484     return false;
3485 
3486   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3487   if (!III.ZeroIsSpecialOrig)
3488     return false;
3489 
3490   // We cannot do the transform if the operand we are trying to replace
3491   // isn't the same as the operand the instruction allows.
3492   if (OpNoForForwarding != III.OpNoForForwarding)
3493     return false;
3494 
3495   // Check if the instruction we are trying to transform really has
3496   // the special zero register as its operand.
3497   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3498       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3499     return false;
3500 
3501   // This machine instruction is convertible if it is,
3502   // 1. summing the operands.
3503   // 2. one of the operands is special zero register.
3504   // 3. the operand we are trying to replace is allowed by the MI.
3505   return true;
3506 }
3507 
3508 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3509 // accordingly.
3510 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3511                                                const ImmInstrInfo &III,
3512                                                MachineOperand *&ImmMO,
3513                                                MachineOperand *&RegMO) const {
3514   unsigned Opc = DefMI.getOpcode();
3515   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3516     return false;
3517 
3518   assert(DefMI.getNumOperands() >= 3 &&
3519          "Add inst must have at least three operands");
3520   RegMO = &DefMI.getOperand(1);
3521   ImmMO = &DefMI.getOperand(2);
3522 
3523   // This DefMI is elgible for forwarding if it is:
3524   // 1. add inst
3525   // 2. one of the operands is Imm/CPI/Global.
3526   return isAnImmediateOperand(*ImmMO);
3527 }
3528 
3529 bool PPCInstrInfo::isRegElgibleForForwarding(
3530     const MachineOperand &RegMO, const MachineInstr &DefMI,
3531     const MachineInstr &MI, bool KillDefMI,
3532     bool &IsFwdFeederRegKilled) const {
3533   // x = addi y, imm
3534   // ...
3535   // z = lfdx 0, x   -> z = lfd imm(y)
3536   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3537   // of "y" between the DEF of "x" and "z".
3538   // The query is only valid post RA.
3539   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3540   if (MRI.isSSA())
3541     return false;
3542 
3543   Register Reg = RegMO.getReg();
3544 
3545   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3546   MachineBasicBlock::const_reverse_iterator It = MI;
3547   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3548   It++;
3549   for (; It != E; ++It) {
3550     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3551       return false;
3552     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3553       IsFwdFeederRegKilled = true;
3554     // Made it to DefMI without encountering a clobber.
3555     if ((&*It) == &DefMI)
3556       break;
3557   }
3558   assert((&*It) == &DefMI && "DefMI is missing");
3559 
3560   // If DefMI also defines the register to be forwarded, we can only forward it
3561   // if DefMI is being erased.
3562   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3563     return KillDefMI;
3564 
3565   return true;
3566 }
3567 
3568 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3569                                              const MachineInstr &DefMI,
3570                                              const ImmInstrInfo &III,
3571                                              int64_t &Imm) const {
3572   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3573   if (DefMI.getOpcode() == PPC::ADDItocL) {
3574     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3575     // However, we know that, it is 16-bit width, and has the alignment of 4.
3576     // Check if the instruction met the requirement.
3577     if (III.ImmMustBeMultipleOf > 4 ||
3578        III.TruncateImmTo || III.ImmWidth != 16)
3579       return false;
3580 
3581     // Going from XForm to DForm loads means that the displacement needs to be
3582     // not just an immediate but also a multiple of 4, or 16 depending on the
3583     // load. A DForm load cannot be represented if it is a multiple of say 2.
3584     // XForm loads do not have this restriction.
3585     if (ImmMO.isGlobal() &&
3586         ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf)
3587       return false;
3588 
3589     return true;
3590   }
3591 
3592   if (ImmMO.isImm()) {
3593     // It is Imm, we need to check if the Imm fit the range.
3594     int64_t Immediate = ImmMO.getImm();
3595     // Sign-extend to 64-bits.
3596     Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
3597       (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
3598 
3599     if (Imm % III.ImmMustBeMultipleOf)
3600       return false;
3601     if (III.TruncateImmTo)
3602       Imm &= ((1 << III.TruncateImmTo) - 1);
3603     if (III.SignedImm) {
3604       APInt ActualValue(64, Imm, true);
3605       if (!ActualValue.isSignedIntN(III.ImmWidth))
3606         return false;
3607     } else {
3608       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3609       if ((uint64_t)Imm > UnsignedMax)
3610         return false;
3611     }
3612   }
3613   else
3614     return false;
3615 
3616   // This ImmMO is forwarded if it meets the requriement describle
3617   // in ImmInstrInfo
3618   return true;
3619 }
3620 
3621 // If an X-Form instruction is fed by an add-immediate and one of its operands
3622 // is the literal zero, attempt to forward the source of the add-immediate to
3623 // the corresponding D-Form instruction with the displacement coming from
3624 // the immediate being added.
3625 bool PPCInstrInfo::transformToImmFormFedByAdd(
3626     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
3627     MachineInstr &DefMI, bool KillDefMI) const {
3628   //         RegMO ImmMO
3629   //           |    |
3630   // x = addi reg, imm  <----- DefMI
3631   // y = op    0 ,  x   <----- MI
3632   //                |
3633   //         OpNoForForwarding
3634   // Check if the MI meet the requirement described in the III.
3635   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
3636     return false;
3637 
3638   // Check if the DefMI meet the requirement
3639   // described in the III. If yes, set the ImmMO and RegMO accordingly.
3640   MachineOperand *ImmMO = nullptr;
3641   MachineOperand *RegMO = nullptr;
3642   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
3643     return false;
3644   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
3645 
3646   // As we get the Imm operand now, we need to check if the ImmMO meet
3647   // the requirement described in the III. If yes set the Imm.
3648   int64_t Imm = 0;
3649   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
3650     return false;
3651 
3652   bool IsFwdFeederRegKilled = false;
3653   // Check if the RegMO can be forwarded to MI.
3654   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
3655                                  IsFwdFeederRegKilled))
3656     return false;
3657 
3658   // Get killed info in case fixup needed after transformation.
3659   unsigned ForwardKilledOperandReg = ~0U;
3660   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3661   bool PostRA = !MRI.isSSA();
3662   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
3663     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
3664 
3665   // We know that, the MI and DefMI both meet the pattern, and
3666   // the Imm also meet the requirement with the new Imm-form.
3667   // It is safe to do the transformation now.
3668   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3669   LLVM_DEBUG(MI.dump());
3670   LLVM_DEBUG(dbgs() << "Fed by:\n");
3671   LLVM_DEBUG(DefMI.dump());
3672 
3673   // Update the base reg first.
3674   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
3675                                                         false, false,
3676                                                         RegMO->isKill());
3677 
3678   // Then, update the imm.
3679   if (ImmMO->isImm()) {
3680     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
3681     // directly.
3682     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
3683   }
3684   else {
3685     // Otherwise, it is Constant Pool Index(CPI) or Global,
3686     // which is relocation in fact. We need to replace the special zero
3687     // register with ImmMO.
3688     // Before that, we need to fixup the target flags for imm.
3689     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
3690     if (DefMI.getOpcode() == PPC::ADDItocL)
3691       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
3692 
3693     // MI didn't have the interface such as MI.setOperand(i) though
3694     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
3695     // ImmMO, we need to remove ZERO operand and all the operands behind it,
3696     // and, add the ImmMO, then, move back all the operands behind ZERO.
3697     SmallVector<MachineOperand, 2> MOps;
3698     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
3699       MOps.push_back(MI.getOperand(i));
3700       MI.RemoveOperand(i);
3701     }
3702 
3703     // Remove the last MO in the list, which is ZERO operand in fact.
3704     MOps.pop_back();
3705     // Add the imm operand.
3706     MI.addOperand(*ImmMO);
3707     // Now add the rest back.
3708     for (auto &MO : MOps)
3709       MI.addOperand(MO);
3710   }
3711 
3712   // Update the opcode.
3713   MI.setDesc(get(III.ImmOpcode));
3714 
3715   // Fix up killed/dead flag after transformation.
3716   // Pattern 1:
3717   // x = ADD KilledFwdFeederReg, imm
3718   // n = opn KilledFwdFeederReg(killed), regn
3719   // y = XOP 0, x
3720   // Pattern 2:
3721   // x = ADD reg(killed), imm
3722   // y = XOP 0, x
3723   if (IsFwdFeederRegKilled || RegMO->isKill())
3724     fixupIsDeadOrKill(DefMI, MI, RegMO->getReg());
3725   // Pattern 3:
3726   // ForwardKilledOperandReg = ADD reg, imm
3727   // y = XOP 0, ForwardKilledOperandReg(killed)
3728   if (ForwardKilledOperandReg != ~0U)
3729     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3730 
3731   LLVM_DEBUG(dbgs() << "With:\n");
3732   LLVM_DEBUG(MI.dump());
3733 
3734   return true;
3735 }
3736 
3737 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
3738                                              const ImmInstrInfo &III,
3739                                              unsigned ConstantOpNo,
3740                                              MachineInstr &DefMI,
3741                                              int64_t Imm) const {
3742   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3743   bool PostRA = !MRI.isSSA();
3744   // Exit early if we can't convert this.
3745   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
3746     return false;
3747   if (Imm % III.ImmMustBeMultipleOf)
3748     return false;
3749   if (III.TruncateImmTo)
3750     Imm &= ((1 << III.TruncateImmTo) - 1);
3751   if (III.SignedImm) {
3752     APInt ActualValue(64, Imm, true);
3753     if (!ActualValue.isSignedIntN(III.ImmWidth))
3754       return false;
3755   } else {
3756     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3757     if ((uint64_t)Imm > UnsignedMax)
3758       return false;
3759   }
3760 
3761   // If we're post-RA, the instructions don't agree on whether register zero is
3762   // special, we can transform this as long as the register operand that will
3763   // end up in the location where zero is special isn't R0.
3764   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3765     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
3766       III.ZeroIsSpecialNew + 1;
3767     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
3768     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3769     // If R0 is in the operand where zero is special for the new instruction,
3770     // it is unsafe to transform if the constant operand isn't that operand.
3771     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
3772         ConstantOpNo != III.ZeroIsSpecialNew)
3773       return false;
3774     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
3775         ConstantOpNo != PosForOrigZero)
3776       return false;
3777   }
3778 
3779   // Get killed info in case fixup needed after transformation.
3780   unsigned ForwardKilledOperandReg = ~0U;
3781   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
3782     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
3783 
3784   unsigned Opc = MI.getOpcode();
3785   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
3786                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
3787                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
3788                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
3789   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
3790                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
3791   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
3792                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
3793   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
3794                     Opc == PPC::SRD_rec;
3795 
3796   MI.setDesc(get(III.ImmOpcode));
3797   if (ConstantOpNo == III.OpNoForForwarding) {
3798     // Converting shifts to immediate form is a bit tricky since they may do
3799     // one of three things:
3800     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
3801     // 2. If the shift amount is zero, the result is unchanged (save for maybe
3802     //    setting CR0)
3803     // 3. If the shift amount is in [1, OpSize), it's just a shift
3804     if (SpecialShift32 || SpecialShift64) {
3805       LoadImmediateInfo LII;
3806       LII.Imm = 0;
3807       LII.SetCR = SetCR;
3808       LII.Is64Bit = SpecialShift64;
3809       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
3810       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
3811         replaceInstrWithLI(MI, LII);
3812       // Shifts by zero don't change the value. If we don't need to set CR0,
3813       // just convert this to a COPY. Can't do this post-RA since we've already
3814       // cleaned up the copies.
3815       else if (!SetCR && ShAmt == 0 && !PostRA) {
3816         MI.RemoveOperand(2);
3817         MI.setDesc(get(PPC::COPY));
3818       } else {
3819         // The 32 bit and 64 bit instructions are quite different.
3820         if (SpecialShift32) {
3821           // Left shifts use (N, 0, 31-N).
3822           // Right shifts use (32-N, N, 31) if 0 < N < 32.
3823           //              use (0, 0, 31)    if N == 0.
3824           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
3825           uint64_t MB = RightShift ? ShAmt : 0;
3826           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
3827           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3828           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
3829             .addImm(ME);
3830         } else {
3831           // Left shifts use (N, 63-N).
3832           // Right shifts use (64-N, N) if 0 < N < 64.
3833           //              use (0, 0)    if N == 0.
3834           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
3835           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
3836           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3837           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
3838         }
3839       }
3840     } else
3841       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3842   }
3843   // Convert commutative instructions (switch the operands and convert the
3844   // desired one to an immediate.
3845   else if (III.IsCommutative) {
3846     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3847     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
3848   } else
3849     llvm_unreachable("Should have exited early!");
3850 
3851   // For instructions for which the constant register replaces a different
3852   // operand than where the immediate goes, we need to swap them.
3853   if (III.OpNoForForwarding != III.ImmOpNo)
3854     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
3855 
3856   // If the special R0/X0 register index are different for original instruction
3857   // and new instruction, we need to fix up the register class in new
3858   // instruction.
3859   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3860     if (III.ZeroIsSpecialNew) {
3861       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
3862       // need to fix up register class.
3863       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3864       if (Register::isVirtualRegister(RegToModify)) {
3865         const TargetRegisterClass *NewRC =
3866           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
3867           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
3868         MRI.setRegClass(RegToModify, NewRC);
3869       }
3870     }
3871   }
3872 
3873   // Fix up killed/dead flag after transformation.
3874   // Pattern:
3875   // ForwardKilledOperandReg = LI imm
3876   // y = XOP reg, ForwardKilledOperandReg(killed)
3877   if (ForwardKilledOperandReg != ~0U)
3878     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3879   return true;
3880 }
3881 
3882 const TargetRegisterClass *
3883 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
3884   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
3885     return &PPC::VSRCRegClass;
3886   return RC;
3887 }
3888 
3889 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
3890   return PPC::getRecordFormOpcode(Opcode);
3891 }
3892 
3893 // This function returns true if the machine instruction
3894 // always outputs a value by sign-extending a 32 bit value,
3895 // i.e. 0 to 31-th bits are same as 32-th bit.
3896 static bool isSignExtendingOp(const MachineInstr &MI) {
3897   int Opcode = MI.getOpcode();
3898   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
3899       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
3900       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
3901       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
3902       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
3903       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
3904       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
3905       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3906       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
3907       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
3908       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
3909       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
3910       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
3911       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
3912       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
3913       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
3914       Opcode == PPC::EXTSB8_32_64)
3915     return true;
3916 
3917   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
3918     return true;
3919 
3920   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3921        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
3922       MI.getOperand(3).getImm() > 0 &&
3923       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3924     return true;
3925 
3926   return false;
3927 }
3928 
3929 // This function returns true if the machine instruction
3930 // always outputs zeros in higher 32 bits.
3931 static bool isZeroExtendingOp(const MachineInstr &MI) {
3932   int Opcode = MI.getOpcode();
3933   // The 16-bit immediate is sign-extended in li/lis.
3934   // If the most significant bit is zero, all higher bits are zero.
3935   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
3936       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
3937     int64_t Imm = MI.getOperand(1).getImm();
3938     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
3939       return true;
3940   }
3941 
3942   // We have some variations of rotate-and-mask instructions
3943   // that clear higher 32-bits.
3944   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
3945        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
3946        Opcode == PPC::RLDICL_32_64) &&
3947       MI.getOperand(3).getImm() >= 32)
3948     return true;
3949 
3950   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
3951       MI.getOperand(3).getImm() >= 32 &&
3952       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
3953     return true;
3954 
3955   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3956        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
3957        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
3958       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3959     return true;
3960 
3961   // There are other instructions that clear higher 32-bits.
3962   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
3963       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
3964       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
3965       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
3966       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
3967       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
3968       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
3969       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
3970       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
3971       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
3972       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
3973       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
3974       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
3975       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
3976       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
3977       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
3978       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
3979       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
3980       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3981       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
3982       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
3983       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
3984       Opcode == PPC::MFVSRWZ)
3985     return true;
3986 
3987   return false;
3988 }
3989 
3990 // This function returns true if the input MachineInstr is a TOC save
3991 // instruction.
3992 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
3993   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
3994     return false;
3995   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
3996   unsigned StackOffset = MI.getOperand(1).getImm();
3997   Register StackReg = MI.getOperand(2).getReg();
3998   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
3999     return true;
4000 
4001   return false;
4002 }
4003 
4004 // We limit the max depth to track incoming values of PHIs or binary ops
4005 // (e.g. AND) to avoid excessive cost.
4006 const unsigned MAX_DEPTH = 1;
4007 
4008 bool
4009 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
4010                                    const unsigned Depth) const {
4011   const MachineFunction *MF = MI.getParent()->getParent();
4012   const MachineRegisterInfo *MRI = &MF->getRegInfo();
4013 
4014   // If we know this instruction returns sign- or zero-extended result,
4015   // return true.
4016   if (SignExt ? isSignExtendingOp(MI):
4017                 isZeroExtendingOp(MI))
4018     return true;
4019 
4020   switch (MI.getOpcode()) {
4021   case PPC::COPY: {
4022     Register SrcReg = MI.getOperand(1).getReg();
4023 
4024     // In both ELFv1 and v2 ABI, method parameters and the return value
4025     // are sign- or zero-extended.
4026     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
4027       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
4028       // We check the ZExt/SExt flags for a method parameter.
4029       if (MI.getParent()->getBasicBlock() ==
4030           &MF->getFunction().getEntryBlock()) {
4031         Register VReg = MI.getOperand(0).getReg();
4032         if (MF->getRegInfo().isLiveIn(VReg))
4033           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
4034                            FuncInfo->isLiveInZExt(VReg);
4035       }
4036 
4037       // For a method return value, we check the ZExt/SExt flags in attribute.
4038       // We assume the following code sequence for method call.
4039       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
4040       //   BL8_NOP @func,...
4041       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
4042       //   %5 = COPY %x3; G8RC:%5
4043       if (SrcReg == PPC::X3) {
4044         const MachineBasicBlock *MBB = MI.getParent();
4045         MachineBasicBlock::const_instr_iterator II =
4046           MachineBasicBlock::const_instr_iterator(&MI);
4047         if (II != MBB->instr_begin() &&
4048             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
4049           const MachineInstr &CallMI = *(--II);
4050           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
4051             const Function *CalleeFn =
4052               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
4053             if (!CalleeFn)
4054               return false;
4055             const IntegerType *IntTy =
4056               dyn_cast<IntegerType>(CalleeFn->getReturnType());
4057             const AttributeSet &Attrs =
4058               CalleeFn->getAttributes().getRetAttributes();
4059             if (IntTy && IntTy->getBitWidth() <= 32)
4060               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
4061                                                   Attribute::ZExt);
4062           }
4063         }
4064       }
4065     }
4066 
4067     // If this is a copy from another register, we recursively check source.
4068     if (!Register::isVirtualRegister(SrcReg))
4069       return false;
4070     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4071     if (SrcMI != NULL)
4072       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4073 
4074     return false;
4075   }
4076 
4077   case PPC::ANDI_rec:
4078   case PPC::ANDIS_rec:
4079   case PPC::ORI:
4080   case PPC::ORIS:
4081   case PPC::XORI:
4082   case PPC::XORIS:
4083   case PPC::ANDI8_rec:
4084   case PPC::ANDIS8_rec:
4085   case PPC::ORI8:
4086   case PPC::ORIS8:
4087   case PPC::XORI8:
4088   case PPC::XORIS8: {
4089     // logical operation with 16-bit immediate does not change the upper bits.
4090     // So, we track the operand register as we do for register copy.
4091     Register SrcReg = MI.getOperand(1).getReg();
4092     if (!Register::isVirtualRegister(SrcReg))
4093       return false;
4094     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4095     if (SrcMI != NULL)
4096       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4097 
4098     return false;
4099   }
4100 
4101   // If all incoming values are sign-/zero-extended,
4102   // the output of OR, ISEL or PHI is also sign-/zero-extended.
4103   case PPC::OR:
4104   case PPC::OR8:
4105   case PPC::ISEL:
4106   case PPC::PHI: {
4107     if (Depth >= MAX_DEPTH)
4108       return false;
4109 
4110     // The input registers for PHI are operand 1, 3, ...
4111     // The input registers for others are operand 1 and 2.
4112     unsigned E = 3, D = 1;
4113     if (MI.getOpcode() == PPC::PHI) {
4114       E = MI.getNumOperands();
4115       D = 2;
4116     }
4117 
4118     for (unsigned I = 1; I != E; I += D) {
4119       if (MI.getOperand(I).isReg()) {
4120         Register SrcReg = MI.getOperand(I).getReg();
4121         if (!Register::isVirtualRegister(SrcReg))
4122           return false;
4123         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4124         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
4125           return false;
4126       }
4127       else
4128         return false;
4129     }
4130     return true;
4131   }
4132 
4133   // If at least one of the incoming values of an AND is zero extended
4134   // then the output is also zero-extended. If both of the incoming values
4135   // are sign-extended then the output is also sign extended.
4136   case PPC::AND:
4137   case PPC::AND8: {
4138     if (Depth >= MAX_DEPTH)
4139        return false;
4140 
4141     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
4142 
4143     Register SrcReg1 = MI.getOperand(1).getReg();
4144     Register SrcReg2 = MI.getOperand(2).getReg();
4145 
4146     if (!Register::isVirtualRegister(SrcReg1) ||
4147         !Register::isVirtualRegister(SrcReg2))
4148       return false;
4149 
4150     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
4151     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
4152     if (!MISrc1 || !MISrc2)
4153         return false;
4154 
4155     if(SignExt)
4156         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
4157                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4158     else
4159         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
4160                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4161   }
4162 
4163   default:
4164     break;
4165   }
4166   return false;
4167 }
4168 
4169 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
4170   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
4171 }
4172 
4173 namespace {
4174 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
4175   MachineInstr *Loop, *EndLoop, *LoopCount;
4176   MachineFunction *MF;
4177   const TargetInstrInfo *TII;
4178   int64_t TripCount;
4179 
4180 public:
4181   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
4182                        MachineInstr *LoopCount)
4183       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
4184         MF(Loop->getParent()->getParent()),
4185         TII(MF->getSubtarget().getInstrInfo()) {
4186     // Inspect the Loop instruction up-front, as it may be deleted when we call
4187     // createTripCountGreaterCondition.
4188     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
4189       TripCount = LoopCount->getOperand(1).getImm();
4190     else
4191       TripCount = -1;
4192   }
4193 
4194   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
4195     // Only ignore the terminator.
4196     return MI == EndLoop;
4197   }
4198 
4199   Optional<bool>
4200   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
4201                                   SmallVectorImpl<MachineOperand> &Cond) override {
4202     if (TripCount == -1) {
4203       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4204       // so we don't need to generate any thing here.
4205       Cond.push_back(MachineOperand::CreateImm(0));
4206       Cond.push_back(MachineOperand::CreateReg(
4207           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
4208           true));
4209       return {};
4210     }
4211 
4212     return TripCount > TC;
4213   }
4214 
4215   void setPreheader(MachineBasicBlock *NewPreheader) override {
4216     // Do nothing. We want the LOOP setup instruction to stay in the *old*
4217     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
4218   }
4219 
4220   void adjustTripCount(int TripCountAdjust) override {
4221     // If the loop trip count is a compile-time value, then just change the
4222     // value.
4223     if (LoopCount->getOpcode() == PPC::LI8 ||
4224         LoopCount->getOpcode() == PPC::LI) {
4225       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
4226       LoopCount->getOperand(1).setImm(TripCount);
4227       return;
4228     }
4229 
4230     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4231     // so we don't need to generate any thing here.
4232   }
4233 
4234   void disposed() override {
4235     Loop->eraseFromParent();
4236     // Ensure the loop setup instruction is deleted too.
4237     LoopCount->eraseFromParent();
4238   }
4239 };
4240 } // namespace
4241 
4242 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4243 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4244   // We really "analyze" only hardware loops right now.
4245   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4246   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4247   if (Preheader == LoopBB)
4248     Preheader = *std::next(LoopBB->pred_begin());
4249   MachineFunction *MF = Preheader->getParent();
4250 
4251   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
4252     SmallPtrSet<MachineBasicBlock *, 8> Visited;
4253     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
4254       Register LoopCountReg = LoopInst->getOperand(0).getReg();
4255       MachineRegisterInfo &MRI = MF->getRegInfo();
4256       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
4257       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
4258     }
4259   }
4260   return nullptr;
4261 }
4262 
4263 MachineInstr *PPCInstrInfo::findLoopInstr(
4264     MachineBasicBlock &PreHeader,
4265     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
4266 
4267   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
4268 
4269   // The loop set-up instruction should be in preheader
4270   for (auto &I : PreHeader.instrs())
4271     if (I.getOpcode() == LOOPi)
4272       return &I;
4273   return nullptr;
4274 }
4275 
4276 // Return true if get the base operand, byte offset of an instruction and the
4277 // memory width. Width is the size of memory that is being loaded/stored.
4278 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
4279     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
4280     unsigned &Width, const TargetRegisterInfo *TRI) const {
4281   if (!LdSt.mayLoadOrStore())
4282     return false;
4283 
4284   // Handle only loads/stores with base register followed by immediate offset.
4285   if (LdSt.getNumExplicitOperands() != 3)
4286     return false;
4287   if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg())
4288     return false;
4289 
4290   if (!LdSt.hasOneMemOperand())
4291     return false;
4292 
4293   Width = (*LdSt.memoperands_begin())->getSize();
4294   Offset = LdSt.getOperand(1).getImm();
4295   BaseReg = &LdSt.getOperand(2);
4296   return true;
4297 }
4298 
4299 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
4300     const MachineInstr &MIa, const MachineInstr &MIb) const {
4301   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
4302   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
4303 
4304   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
4305       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4306     return false;
4307 
4308   // Retrieve the base register, offset from the base register and width. Width
4309   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
4310   // base registers are identical, and the offset of a lower memory access +
4311   // the width doesn't overlap the offset of a higher memory access,
4312   // then the memory accesses are different.
4313   const TargetRegisterInfo *TRI = &getRegisterInfo();
4314   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
4315   int64_t OffsetA = 0, OffsetB = 0;
4316   unsigned int WidthA = 0, WidthB = 0;
4317   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
4318       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
4319     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
4320       int LowOffset = std::min(OffsetA, OffsetB);
4321       int HighOffset = std::max(OffsetA, OffsetB);
4322       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4323       if (LowOffset + LowWidth <= HighOffset)
4324         return true;
4325     }
4326   }
4327   return false;
4328 }
4329