xref: /llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp (revision feafa1d7f01ee3ca8e33f14af729d962fea91308)
1 //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 //
10 // This pass performs peephole optimizations to clean up ugly code
11 // sequences at the MachineInstruction layer.  It runs at the end of
12 // the SSA phases, following VSX swap removal.  A pass of dead code
13 // elimination follows this one for quick clean-up of any dead
14 // instructions introduced here.  Although we could do this as callbacks
15 // from the generic peephole pass, this would have a couple of bad
16 // effects:  it might remove optimization opportunities for VSX swap
17 // removal, and it would miss cleanups made possible following VSX
18 // swap removal.
19 //
20 //===---------------------------------------------------------------------===//
21 
22 #include "PPC.h"
23 #include "PPCInstrBuilder.h"
24 #include "PPCInstrInfo.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "MCTargetDesc/PPCPredicates.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "ppc-mi-peepholes"
38 
39 STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
40 STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
41 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
42 
43 static cl::opt<bool>
44     EnableSExtElimination("ppc-eliminate-signext",
45                           cl::desc("enable elimination of sign-extensions"),
46                           cl::init(false), cl::Hidden);
47 
48 static cl::opt<bool>
49     EnableZExtElimination("ppc-eliminate-zeroext",
50                           cl::desc("enable elimination of zero-extensions"),
51                           cl::init(false), cl::Hidden);
52 
53 namespace llvm {
54   void initializePPCMIPeepholePass(PassRegistry&);
55 }
56 
57 namespace {
58 
59 struct PPCMIPeephole : public MachineFunctionPass {
60 
61   static char ID;
62   const PPCInstrInfo *TII;
63   MachineFunction *MF;
64   MachineRegisterInfo *MRI;
65 
66   PPCMIPeephole() : MachineFunctionPass(ID) {
67     initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
68   }
69 
70 private:
71   MachineDominatorTree *MDT;
72 
73   // Initialize class variables.
74   void initialize(MachineFunction &MFParm);
75 
76   // Perform peepholes.
77   bool simplifyCode(void);
78 
79   // Perform peepholes.
80   bool eliminateRedundantCompare(void);
81 
82   // Find the "true" register represented by SrcReg (following chains
83   // of copies and subreg_to_reg operations).
84   unsigned lookThruCopyLike(unsigned SrcReg);
85 
86 public:
87 
88   void getAnalysisUsage(AnalysisUsage &AU) const override {
89     AU.addRequired<MachineDominatorTree>();
90     AU.addPreserved<MachineDominatorTree>();
91     MachineFunctionPass::getAnalysisUsage(AU);
92   }
93 
94   // Main entry point for this pass.
95   bool runOnMachineFunction(MachineFunction &MF) override {
96     if (skipFunction(*MF.getFunction()))
97       return false;
98     initialize(MF);
99     return simplifyCode();
100   }
101 };
102 
103 // Initialize class variables.
104 void PPCMIPeephole::initialize(MachineFunction &MFParm) {
105   MF = &MFParm;
106   MRI = &MF->getRegInfo();
107   MDT = &getAnalysis<MachineDominatorTree>();
108   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
109   DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
110   DEBUG(MF->dump());
111 }
112 
113 static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
114                                       MachineRegisterInfo *MRI) {
115   assert(Op && "Invalid Operand!");
116   if (!Op->isReg())
117     return nullptr;
118 
119   unsigned Reg = Op->getReg();
120   if (!TargetRegisterInfo::isVirtualRegister(Reg))
121     return nullptr;
122 
123   return MRI->getVRegDef(Reg);
124 }
125 
126 // This function returns number of known zero bits in output of MI
127 // starting from the most significant bit.
128 static unsigned
129 getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) {
130   unsigned Opcode = MI->getOpcode();
131   if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICLo ||
132       Opcode == PPC::RLDCL  || Opcode == PPC::RLDCLo)
133     return MI->getOperand(3).getImm();
134 
135   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDICo) &&
136        MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
137     return MI->getOperand(3).getImm();
138 
139   if ((Opcode == PPC::RLWINM  || Opcode == PPC::RLWINMo ||
140        Opcode == PPC::RLWNM   || Opcode == PPC::RLWNMo  ||
141        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
142        MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
143     return 32 + MI->getOperand(3).getImm();
144 
145   if (Opcode == PPC::ANDIo) {
146     uint16_t Imm = MI->getOperand(2).getImm();
147     return 48 + countLeadingZeros(Imm);
148   }
149 
150   if (Opcode == PPC::CNTLZW  || Opcode == PPC::CNTLZWo ||
151       Opcode == PPC::CNTTZW  || Opcode == PPC::CNTTZWo ||
152       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
153     // The result ranges from 0 to 32.
154     return 58;
155 
156   if (Opcode == PPC::CNTLZD  || Opcode == PPC::CNTLZDo ||
157       Opcode == PPC::CNTTZD  || Opcode == PPC::CNTTZDo)
158     // The result ranges from 0 to 64.
159     return 57;
160 
161   if (Opcode == PPC::LHZ   || Opcode == PPC::LHZX  ||
162       Opcode == PPC::LHZ8  || Opcode == PPC::LHZX8 ||
163       Opcode == PPC::LHZU  || Opcode == PPC::LHZUX ||
164       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
165     return 48;
166 
167   if (Opcode == PPC::LBZ   || Opcode == PPC::LBZX  ||
168       Opcode == PPC::LBZ8  || Opcode == PPC::LBZX8 ||
169       Opcode == PPC::LBZU  || Opcode == PPC::LBZUX ||
170       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
171     return 56;
172 
173   if (TII->isZeroExtended(*MI))
174     return 32;
175 
176   return 0;
177 }
178 
179 // Perform peephole optimizations.
180 bool PPCMIPeephole::simplifyCode(void) {
181   bool Simplified = false;
182   MachineInstr* ToErase = nullptr;
183 
184   for (MachineBasicBlock &MBB : *MF) {
185     for (MachineInstr &MI : MBB) {
186 
187       // If the previous instruction was marked for elimination,
188       // remove it now.
189       if (ToErase) {
190         ToErase->eraseFromParent();
191         ToErase = nullptr;
192       }
193 
194       // Ignore debug instructions.
195       if (MI.isDebugValue())
196         continue;
197 
198       // Per-opcode peepholes.
199       switch (MI.getOpcode()) {
200 
201       default:
202         break;
203 
204       case PPC::XXPERMDI: {
205         // Perform simplifications of 2x64 vector swaps and splats.
206         // A swap is identified by an immediate value of 2, and a splat
207         // is identified by an immediate value of 0 or 3.
208         int Immed = MI.getOperand(3).getImm();
209 
210         if (Immed != 1) {
211 
212           // For each of these simplifications, we need the two source
213           // regs to match.  Unfortunately, MachineCSE ignores COPY and
214           // SUBREG_TO_REG, so for example we can see
215           //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
216           // We have to look through chains of COPY and SUBREG_TO_REG
217           // to find the real source values for comparison.
218           unsigned TrueReg1 = lookThruCopyLike(MI.getOperand(1).getReg());
219           unsigned TrueReg2 = lookThruCopyLike(MI.getOperand(2).getReg());
220 
221           if (TrueReg1 == TrueReg2
222               && TargetRegisterInfo::isVirtualRegister(TrueReg1)) {
223             MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
224             unsigned DefOpc = DefMI ? DefMI->getOpcode() : 0;
225 
226             // If this is a splat fed by a splatting load, the splat is
227             // redundant. Replace with a copy. This doesn't happen directly due
228             // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
229             // a load of a double to a vector of 64-bit integers.
230             auto isConversionOfLoadAndSplat = [=]() -> bool {
231               if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
232                 return false;
233               unsigned DefReg = lookThruCopyLike(DefMI->getOperand(1).getReg());
234               if (TargetRegisterInfo::isVirtualRegister(DefReg)) {
235                 MachineInstr *LoadMI = MRI->getVRegDef(DefReg);
236                 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
237                   return true;
238               }
239               return false;
240             };
241             if (DefMI && (Immed == 0 || Immed == 3)) {
242               if (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat()) {
243                 DEBUG(dbgs()
244                       << "Optimizing load-and-splat/splat "
245                       "to load-and-splat/copy: ");
246                 DEBUG(MI.dump());
247                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
248                         MI.getOperand(0).getReg())
249                     .add(MI.getOperand(1));
250                 ToErase = &MI;
251                 Simplified = true;
252               }
253             }
254 
255             // If this is a splat or a swap fed by another splat, we
256             // can replace it with a copy.
257             if (DefOpc == PPC::XXPERMDI) {
258               unsigned FeedImmed = DefMI->getOperand(3).getImm();
259               unsigned FeedReg1
260                 = lookThruCopyLike(DefMI->getOperand(1).getReg());
261               unsigned FeedReg2
262                 = lookThruCopyLike(DefMI->getOperand(2).getReg());
263 
264               if ((FeedImmed == 0 || FeedImmed == 3) && FeedReg1 == FeedReg2) {
265                 DEBUG(dbgs()
266                       << "Optimizing splat/swap or splat/splat "
267                       "to splat/copy: ");
268                 DEBUG(MI.dump());
269                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
270                         MI.getOperand(0).getReg())
271                     .add(MI.getOperand(1));
272                 ToErase = &MI;
273                 Simplified = true;
274               }
275 
276               // If this is a splat fed by a swap, we can simplify modify
277               // the splat to splat the other value from the swap's input
278               // parameter.
279               else if ((Immed == 0 || Immed == 3)
280                        && FeedImmed == 2 && FeedReg1 == FeedReg2) {
281                 DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
282                 DEBUG(MI.dump());
283                 MI.getOperand(1).setReg(DefMI->getOperand(1).getReg());
284                 MI.getOperand(2).setReg(DefMI->getOperand(2).getReg());
285                 MI.getOperand(3).setImm(3 - Immed);
286                 Simplified = true;
287               }
288 
289               // If this is a swap fed by a swap, we can replace it
290               // with a copy from the first swap's input.
291               else if (Immed == 2 && FeedImmed == 2 && FeedReg1 == FeedReg2) {
292                 DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
293                 DEBUG(MI.dump());
294                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
295                         MI.getOperand(0).getReg())
296                     .add(DefMI->getOperand(1));
297                 ToErase = &MI;
298                 Simplified = true;
299               }
300             } else if ((Immed == 0 || Immed == 3) && DefOpc == PPC::XXPERMDIs &&
301                        (DefMI->getOperand(2).getImm() == 0 ||
302                         DefMI->getOperand(2).getImm() == 3)) {
303               // Splat fed by another splat - switch the output of the first
304               // and remove the second.
305               DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
306               ToErase = &MI;
307               Simplified = true;
308               DEBUG(dbgs() << "Removing redundant splat: ");
309               DEBUG(MI.dump());
310             }
311           }
312         }
313         break;
314       }
315       case PPC::VSPLTB:
316       case PPC::VSPLTH:
317       case PPC::XXSPLTW: {
318         unsigned MyOpcode = MI.getOpcode();
319         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
320         unsigned TrueReg = lookThruCopyLike(MI.getOperand(OpNo).getReg());
321         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
322           break;
323         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
324         if (!DefMI)
325           break;
326         unsigned DefOpcode = DefMI->getOpcode();
327         auto isConvertOfSplat = [=]() -> bool {
328           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
329             return false;
330           unsigned ConvReg = DefMI->getOperand(1).getReg();
331           if (!TargetRegisterInfo::isVirtualRegister(ConvReg))
332             return false;
333           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
334           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
335             Splt->getOpcode() == PPC::XXSPLTW);
336         };
337         bool AlreadySplat = (MyOpcode == DefOpcode) ||
338           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
339           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
340           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
341           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
342           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
343           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
344         // If the instruction[s] that feed this splat have already splat
345         // the value, this splat is redundant.
346         if (AlreadySplat) {
347           DEBUG(dbgs() << "Changing redundant splat to a copy: ");
348           DEBUG(MI.dump());
349           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
350                   MI.getOperand(0).getReg())
351               .add(MI.getOperand(OpNo));
352           ToErase = &MI;
353           Simplified = true;
354         }
355         // Splat fed by a shift. Usually when we align value to splat into
356         // vector element zero.
357         if (DefOpcode == PPC::XXSLDWI) {
358           unsigned ShiftRes = DefMI->getOperand(0).getReg();
359           unsigned ShiftOp1 = DefMI->getOperand(1).getReg();
360           unsigned ShiftOp2 = DefMI->getOperand(2).getReg();
361           unsigned ShiftImm = DefMI->getOperand(3).getImm();
362           unsigned SplatImm = MI.getOperand(2).getImm();
363           if (ShiftOp1 == ShiftOp2) {
364             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
365             if (MRI->hasOneNonDBGUse(ShiftRes)) {
366               DEBUG(dbgs() << "Removing redundant shift: ");
367               DEBUG(DefMI->dump());
368               ToErase = DefMI;
369             }
370             Simplified = true;
371             DEBUG(dbgs() << "Changing splat immediate from " << SplatImm <<
372                   " to " << NewElem << " in instruction: ");
373             DEBUG(MI.dump());
374             MI.getOperand(1).setReg(ShiftOp1);
375             MI.getOperand(2).setImm(NewElem);
376           }
377         }
378 
379         // Splat is fed by a SWAP which is a permute of this form
380         //  XXPERMDI %VA, %VA, 2
381         // Since the splat instruction can use any of the vector elements to do
382         //  the splat we do not have to rearrange the elements in the vector
383         //  with a swap before we do the splat. We can simply do the splat from
384         //  a different index.
385         // If the swap has only one use (the splat) then we can completely
386         //  remove the swap too.
387         if (DefOpcode == PPC::XXPERMDI && MI.getOperand(1).isImm()) {
388           unsigned SwapRes = DefMI->getOperand(0).getReg();
389           unsigned SwapOp1 = DefMI->getOperand(1).getReg();
390           unsigned SwapOp2 = DefMI->getOperand(2).getReg();
391           unsigned SwapImm = DefMI->getOperand(3).getImm();
392           unsigned SplatImm = MI.getOperand(1).getImm();
393 
394           // Break if this permute is not a swap.
395           if (SwapOp1 != SwapOp2 || SwapImm != 2)
396             break;
397 
398           unsigned NewElem = 0;
399           // Compute the new index to use for the splat.
400           if (MI.getOpcode() == PPC::VSPLTB)
401             NewElem = (SplatImm + 8) & 0xF;
402           else if (MI.getOpcode() == PPC::VSPLTH)
403             NewElem = (SplatImm + 4) & 0x7;
404           else if (MI.getOpcode() == PPC::XXSPLTW)
405             NewElem = (SplatImm + 2) & 0x3;
406           else {
407             DEBUG(dbgs() << "Unknown splat opcode.");
408             DEBUG(MI.dump());
409             break;
410           }
411 
412           if (MRI->hasOneNonDBGUse(SwapRes)) {
413             DEBUG(dbgs() << "Removing redundant swap: ");
414             DEBUG(DefMI->dump());
415             ToErase = DefMI;
416           }
417           Simplified = true;
418           DEBUG(dbgs() << "Changing splat immediate from " << SplatImm <<
419                 " to " << NewElem << " in instruction: ");
420           DEBUG(MI.dump());
421           MI.getOperand(1).setImm(NewElem);
422           MI.getOperand(2).setReg(SwapOp1);
423         }
424 
425         break;
426       }
427       case PPC::XVCVDPSP: {
428         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
429         unsigned TrueReg = lookThruCopyLike(MI.getOperand(1).getReg());
430         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
431           break;
432         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
433 
434         // This can occur when building a vector of single precision or integer
435         // values.
436         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
437           unsigned DefsReg1 = lookThruCopyLike(DefMI->getOperand(1).getReg());
438           unsigned DefsReg2 = lookThruCopyLike(DefMI->getOperand(2).getReg());
439           if (!TargetRegisterInfo::isVirtualRegister(DefsReg1) ||
440               !TargetRegisterInfo::isVirtualRegister(DefsReg2))
441             break;
442           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
443           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
444 
445           if (!P1 || !P2)
446             break;
447 
448           // Remove the passed FRSP instruction if it only feeds this MI and
449           // set any uses of that FRSP (in this MI) to the source of the FRSP.
450           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
451             if (RoundInstr->getOpcode() == PPC::FRSP &&
452                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
453               Simplified = true;
454               unsigned ConvReg1 = RoundInstr->getOperand(1).getReg();
455               unsigned FRSPDefines = RoundInstr->getOperand(0).getReg();
456               MachineInstr &Use = *(MRI->use_instr_begin(FRSPDefines));
457               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
458                 if (Use.getOperand(i).isReg() &&
459                     Use.getOperand(i).getReg() == FRSPDefines)
460                   Use.getOperand(i).setReg(ConvReg1);
461               DEBUG(dbgs() << "Removing redundant FRSP:\n");
462               DEBUG(RoundInstr->dump());
463               DEBUG(dbgs() << "As it feeds instruction:\n");
464               DEBUG(MI.dump());
465               DEBUG(dbgs() << "Through instruction:\n");
466               DEBUG(DefMI->dump());
467               RoundInstr->eraseFromParent();
468             }
469           };
470 
471           // If the input to XVCVDPSP is a vector that was built (even
472           // partially) out of FRSP's, the FRSP(s) can safely be removed
473           // since this instruction performs the same operation.
474           if (P1 != P2) {
475             removeFRSPIfPossible(P1);
476             removeFRSPIfPossible(P2);
477             break;
478           }
479           removeFRSPIfPossible(P1);
480         }
481         break;
482       }
483       case PPC::EXTSH:
484       case PPC::EXTSH8:
485       case PPC::EXTSH8_32_64: {
486         if (!EnableSExtElimination) break;
487         unsigned NarrowReg = MI.getOperand(1).getReg();
488         if (!TargetRegisterInfo::isVirtualRegister(NarrowReg))
489           break;
490 
491         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
492         // If we've used a zero-extending load that we will sign-extend,
493         // just do a sign-extending load.
494         if (SrcMI->getOpcode() == PPC::LHZ ||
495             SrcMI->getOpcode() == PPC::LHZX) {
496           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
497             break;
498           auto is64Bit = [] (unsigned Opcode) {
499             return Opcode == PPC::EXTSH8;
500           };
501           auto isXForm = [] (unsigned Opcode) {
502             return Opcode == PPC::LHZX;
503           };
504           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
505             if (is64Bit)
506               if (isXForm) return PPC::LHAX8;
507               else         return PPC::LHA8;
508             else
509               if (isXForm) return PPC::LHAX;
510               else         return PPC::LHA;
511           };
512           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
513                                        isXForm(SrcMI->getOpcode()));
514           DEBUG(dbgs() << "Zero-extending load\n");
515           DEBUG(SrcMI->dump());
516           DEBUG(dbgs() << "and sign-extension\n");
517           DEBUG(MI.dump());
518           DEBUG(dbgs() << "are merged into sign-extending load\n");
519           SrcMI->setDesc(TII->get(Opc));
520           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
521           ToErase = &MI;
522           Simplified = true;
523           NumEliminatedSExt++;
524         }
525         break;
526       }
527       case PPC::EXTSW:
528       case PPC::EXTSW_32:
529       case PPC::EXTSW_32_64: {
530         if (!EnableSExtElimination) break;
531         unsigned NarrowReg = MI.getOperand(1).getReg();
532         if (!TargetRegisterInfo::isVirtualRegister(NarrowReg))
533           break;
534 
535         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
536         // If we've used a zero-extending load that we will sign-extend,
537         // just do a sign-extending load.
538         if (SrcMI->getOpcode() == PPC::LWZ ||
539             SrcMI->getOpcode() == PPC::LWZX) {
540           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
541             break;
542           auto is64Bit = [] (unsigned Opcode) {
543             return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
544           };
545           auto isXForm = [] (unsigned Opcode) {
546             return Opcode == PPC::LWZX;
547           };
548           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
549             if (is64Bit)
550               if (isXForm) return PPC::LWAX;
551               else         return PPC::LWA;
552             else
553               if (isXForm) return PPC::LWAX_32;
554               else         return PPC::LWA_32;
555           };
556           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
557                                        isXForm(SrcMI->getOpcode()));
558           DEBUG(dbgs() << "Zero-extending load\n");
559           DEBUG(SrcMI->dump());
560           DEBUG(dbgs() << "and sign-extension\n");
561           DEBUG(MI.dump());
562           DEBUG(dbgs() << "are merged into sign-extending load\n");
563           SrcMI->setDesc(TII->get(Opc));
564           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
565           ToErase = &MI;
566           Simplified = true;
567           NumEliminatedSExt++;
568         } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
569                    TII->isSignExtended(*SrcMI)) {
570           // We can eliminate EXTSW if the input is known to be already
571           // sign-extended.
572           DEBUG(dbgs() << "Removing redundant sign-extension\n");
573           unsigned TmpReg =
574             MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
575           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
576                   TmpReg);
577           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
578                   MI.getOperand(0).getReg())
579               .addReg(TmpReg)
580               .addReg(NarrowReg)
581               .addImm(PPC::sub_32);
582           ToErase = &MI;
583           Simplified = true;
584           NumEliminatedSExt++;
585         }
586         break;
587       }
588       case PPC::RLDICL: {
589         // We can eliminate RLDICL (e.g. for zero-extension)
590         // if all bits to clear are already zero in the input.
591         // This code assume following code sequence for zero-extension.
592         //   %vreg6<def> = COPY %vreg5:sub_32; (optional)
593         //   %vreg8<def> = IMPLICIT_DEF;
594         //   %vreg7<def,tied1> = INSERT_SUBREG %vreg8<tied0>, %vreg6, sub_32;
595         if (!EnableZExtElimination) break;
596 
597         if (MI.getOperand(2).getImm() != 0)
598           break;
599 
600         unsigned SrcReg = MI.getOperand(1).getReg();
601         if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
602           break;
603 
604         MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
605         if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
606               SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
607           break;
608 
609         MachineInstr *ImpDefMI, *SubRegMI;
610         ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
611         SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
612         if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
613 
614         SrcMI = SubRegMI;
615         if (SubRegMI->getOpcode() == PPC::COPY) {
616           unsigned CopyReg = SubRegMI->getOperand(1).getReg();
617           if (TargetRegisterInfo::isVirtualRegister(CopyReg))
618             SrcMI = MRI->getVRegDef(CopyReg);
619         }
620 
621         unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
622         if (MI.getOperand(3).getImm() <= KnownZeroCount) {
623           DEBUG(dbgs() << "Removing redundant zero-extension\n");
624           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
625                   MI.getOperand(0).getReg())
626               .addReg(SrcReg);
627           ToErase = &MI;
628           Simplified = true;
629           NumEliminatedZExt++;
630         }
631         break;
632       }
633 
634       // TODO: Any instruction that has an immediate form fed only by a PHI
635       // whose operands are all load immediate can be folded away. We currently
636       // do this for ADD instructions, but should expand it to arithmetic and
637       // binary instructions with immediate forms in the future.
638       case PPC::ADD4:
639       case PPC::ADD8: {
640         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
641           assert(PhiOp && "Invalid Operand!");
642           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
643 
644           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
645                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
646         };
647 
648         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
649                                             MachineOperand *PhiOp) {
650           assert(PhiOp && "Invalid Operand!");
651           assert(DominatorOp && "Invalid Operand!");
652           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
653           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
654 
655           // Note: the vregs only show up at odd indices position of PHI Node,
656           // the even indices position save the BB info.
657           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
658             MachineInstr *LiMI =
659                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
660             if (!LiMI ||
661                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
662                 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
663                 !MDT->dominates(DefDomMI, LiMI))
664               return false;
665           }
666 
667           return true;
668         };
669 
670         MachineOperand Op1 = MI.getOperand(1);
671         MachineOperand Op2 = MI.getOperand(2);
672         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
673           std::swap(Op1, Op2);
674         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
675           break; // We don't have an ADD fed by LI's that can be transformed
676 
677         // Now we know that Op1 is the PHI node and Op2 is the dominator
678         unsigned DominatorReg = Op2.getReg();
679 
680         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
681                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
682                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
683         MRI->setRegClass(DominatorReg, TRC);
684 
685         // replace LIs with ADDIs
686         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
687         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
688           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
689           DEBUG(dbgs() << "Optimizing LI to ADDI: ");
690           DEBUG(LiMI->dump());
691 
692           // There could be repeated registers in the PHI, e.g: %vreg1<def> =
693           // PHI %vreg6, <BB#2>, %vreg8, <BB#3>, %vreg8, <BB#6>; So if we've
694           // already replaced the def instruction, skip.
695           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
696             continue;
697 
698           assert((LiMI->getOpcode() == PPC::LI ||
699                   LiMI->getOpcode() == PPC::LI8) &&
700                  "Invalid Opcode!");
701           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
702           LiMI->RemoveOperand(1);                    // remove the imm of LI
703           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
704                                                               : PPC::ADDI8));
705           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
706               .addReg(DominatorReg)
707               .addImm(LiImm); // restore the imm of LI
708           DEBUG(LiMI->dump());
709         }
710 
711         // Replace ADD with COPY
712         DEBUG(dbgs() << "Optimizing ADD to COPY: ");
713         DEBUG(MI.dump());
714         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
715                 MI.getOperand(0).getReg())
716             .add(Op1);
717         ToErase = &MI;
718         Simplified = true;
719         NumOptADDLIs++;
720         break;
721       }
722       }
723     }
724 
725     // If the last instruction was marked for elimination,
726     // remove it now.
727     if (ToErase) {
728       ToErase->eraseFromParent();
729       ToErase = nullptr;
730     }
731   }
732 
733   // We try to eliminate redundant compare instruction.
734   Simplified |= eliminateRedundantCompare();
735 
736   return Simplified;
737 }
738 
739 // helper functions for eliminateRedundantCompare
740 static bool isEqOrNe(MachineInstr *BI) {
741   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
742   unsigned PredCond = PPC::getPredicateCondition(Pred);
743   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
744 }
745 
746 static bool isSupportedCmpOp(unsigned opCode) {
747   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
748           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
749           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
750           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
751 }
752 
753 static bool is64bitCmpOp(unsigned opCode) {
754   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
755           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
756 }
757 
758 static bool isSignedCmpOp(unsigned opCode) {
759   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
760           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
761 }
762 
763 static unsigned getSignedCmpOpCode(unsigned opCode) {
764   if (opCode == PPC::CMPLD)  return PPC::CMPD;
765   if (opCode == PPC::CMPLW)  return PPC::CMPW;
766   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
767   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
768   return opCode;
769 }
770 
771 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
772 // (LT x) to (LE x-1)
773 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
774   uint64_t Imm = CMPI->getOperand(2).getImm();
775   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
776   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
777     return 0;
778 
779   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
780   unsigned PredCond = PPC::getPredicateCondition(Pred);
781   unsigned PredHint = PPC::getPredicateHint(Pred);
782   if (PredCond == PPC::PRED_GE)
783     return PPC::getPredicate(PPC::PRED_GT, PredHint);
784   if (PredCond == PPC::PRED_LT)
785     return PPC::getPredicate(PPC::PRED_LE, PredHint);
786 
787   return 0;
788 }
789 
790 // We can increment immediate x in (GT x) by changing it to (GE x+1) or
791 // (LE x) to (LT x+1)
792 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
793   uint64_t Imm = CMPI->getOperand(2).getImm();
794   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
795   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
796     return 0;
797 
798   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
799   unsigned PredCond = PPC::getPredicateCondition(Pred);
800   unsigned PredHint = PPC::getPredicateHint(Pred);
801   if (PredCond == PPC::PRED_GT)
802     return PPC::getPredicate(PPC::PRED_GE, PredHint);
803   if (PredCond == PPC::PRED_LE)
804     return PPC::getPredicate(PPC::PRED_LT, PredHint);
805 
806   return 0;
807 }
808 
809 // This takes a Phi node and returns a register value for the spefied BB.
810 static unsigned getIncomingRegForBlock(MachineInstr *Phi,
811                                        MachineBasicBlock *MBB) {
812   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
813     MachineOperand &MO = Phi->getOperand(I);
814     if (MO.getMBB() == MBB)
815       return Phi->getOperand(I-1).getReg();
816   }
817   llvm_unreachable("invalid src basic block for this Phi node\n");
818   return 0;
819 }
820 
821 // This function tracks the source of the register through register copy.
822 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
823 // assuming that the control comes from BB1 into BB2.
824 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
825                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
826   unsigned SrcReg = Reg;
827   while (1) {
828     unsigned NextReg = SrcReg;
829     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
830     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
831       NextReg = getIncomingRegForBlock(Inst, BB1);
832       // We track through PHI only once to avoid infinite loop.
833       BB1 = nullptr;
834     }
835     else if (Inst->isFullCopy())
836       NextReg = Inst->getOperand(1).getReg();
837     if (NextReg == SrcReg || !TargetRegisterInfo::isVirtualRegister(NextReg))
838       break;
839     SrcReg = NextReg;
840   }
841   return SrcReg;
842 }
843 
844 static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
845                                           MachineBasicBlock *&PredMBB,
846                                           MachineBasicBlock *&MBBtoMoveCmp,
847                                           MachineRegisterInfo *MRI) {
848 
849   auto isEligibleBB = [&](MachineBasicBlock &BB) {
850     auto BII = BB.getFirstInstrTerminator();
851     // We optimize BBs ending with a conditional branch.
852     // We check only for BCC here, not BCCLR, because BCCLR
853     // will be formed only later in the pipeline.
854     if (BB.succ_size() == 2 &&
855         BII != BB.instr_end() &&
856         (*BII).getOpcode() == PPC::BCC &&
857         (*BII).getOperand(1).isReg()) {
858       // We optimize only if the condition code is used only by one BCC.
859       unsigned CndReg = (*BII).getOperand(1).getReg();
860       if (!TargetRegisterInfo::isVirtualRegister(CndReg) ||
861           !MRI->hasOneNonDBGUse(CndReg))
862         return false;
863 
864       // We skip this BB if a physical register is used in comparison.
865       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
866       for (MachineOperand &MO : CMPI->operands())
867         if (MO.isReg() && !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
868           return false;
869 
870       return true;
871     }
872     return false;
873   };
874 
875   // If this BB has more than one successor, we can create a new BB and
876   // move the compare instruction in the new BB.
877   // So far, we do not move compare instruction to a BB having multiple
878   // successors to avoid potentially increasing code size.
879   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
880     return BB.succ_size() == 1;
881   };
882 
883   if (!isEligibleBB(MBB))
884     return false;
885 
886   unsigned NumPredBBs = MBB.pred_size();
887   if (NumPredBBs == 1) {
888     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
889     if (isEligibleBB(*TmpMBB)) {
890       PredMBB = TmpMBB;
891       MBBtoMoveCmp = nullptr;
892       return true;
893     }
894   }
895   else if (NumPredBBs == 2) {
896     // We check for partially redundant case.
897     // So far, we support cases with only two predecessors
898     // to avoid increasing the number of instructions.
899     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
900     MachineBasicBlock *Pred1MBB = *PI;
901     MachineBasicBlock *Pred2MBB = *(PI+1);
902 
903     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
904       // We assume Pred1MBB is the BB containing the compare to be merged and
905       // Pred2MBB is the BB to which we will append a compare instruction.
906       // Hence we can proceed as is.
907     }
908     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
909       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
910       std::swap(Pred1MBB, Pred2MBB);
911     }
912     else return false;
913 
914     // Here, Pred2MBB is the BB to which we need to append a compare inst.
915     // We cannot move the compare instruction if operands are not available
916     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
917     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
918     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
919     for (int I = 1; I <= 2; I++)
920       if (CMPI->getOperand(I).isReg()) {
921         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
922         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
923           return false;
924       }
925 
926     PredMBB = Pred1MBB;
927     MBBtoMoveCmp = Pred2MBB;
928     return true;
929   }
930 
931   return false;
932 }
933 
934 // If multiple conditional branches are executed based on the (essentially)
935 // same comparison, we merge compare instructions into one and make multiple
936 // conditional branches on this comparison.
937 // For example,
938 //   if (a == 0) { ... }
939 //   else if (a < 0) { ... }
940 // can be executed by one compare and two conditional branches instead of
941 // two pairs of a compare and a conditional branch.
942 //
943 // This method merges two compare instructions in two MBBs and modifies the
944 // compare and conditional branch instructions if needed.
945 // For the above example, the input for this pass looks like:
946 //   cmplwi r3, 0
947 //   beq    0, .LBB0_3
948 //   cmpwi  r3, -1
949 //   bgt    0, .LBB0_4
950 // So, before merging two compares, we need to modify these instructions as
951 //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
952 //   beq    0, .LBB0_3
953 //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
954 //   bge    0, .LBB0_4
955 
956 bool PPCMIPeephole::eliminateRedundantCompare(void) {
957   bool Simplified = false;
958 
959   for (MachineBasicBlock &MBB2 : *MF) {
960     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
961 
962     // For fully redundant case, we select two basic blocks MBB1 and MBB2
963     // as an optimization target if
964     // - both MBBs end with a conditional branch,
965     // - MBB1 is the only predecessor of MBB2, and
966     // - compare does not take a physical register as a operand in both MBBs.
967     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
968     //
969     // As partially redundant case, we additionally handle if MBB2 has one
970     // additional predecessor, which has only one successor (MBB2).
971     // In this case, we move the compre instruction originally in MBB2 into
972     // MBBtoMoveCmp. This partially redundant case is typically appear by
973     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
974     //
975     // Overview of CFG of related basic blocks
976     // Fully redundant case        Partially redundant case
977     //   --------                   ----------------  --------
978     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
979     //   --------                   ----------------  --------
980     //      |    \                     (w/ 1 succ) \     |    \
981     //      |     \                                 \    |     \
982     //      |                                        \   |
983     //   --------                                     --------
984     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
985     //   -------- and 2 succ)                         -------- and 2 succ)
986     //      |    \                                       |    \
987     //      |     \                                      |     \
988     //
989     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
990       continue;
991 
992     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
993     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
994 
995     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
996     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
997     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
998 
999     // We cannot optimize an unsupported compare opcode or
1000     // a mix of 32-bit and 64-bit comaprisons
1001     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1002         !isSupportedCmpOp(CMPI2->getOpcode()) ||
1003         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1004       continue;
1005 
1006     unsigned NewOpCode = 0;
1007     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1008     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1009     bool SwapOperands = false;
1010 
1011     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1012       // Typically, unsigned comparison is used for equality check, but
1013       // we replace it with a signed comparison if the comparison
1014       // to be merged is a signed comparison.
1015       // In other cases of opcode mismatch, we cannot optimize this.
1016       if (isEqOrNe(BI2) &&
1017           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1018         NewOpCode = CMPI1->getOpcode();
1019       else if (isEqOrNe(BI1) &&
1020                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1021         NewOpCode = CMPI2->getOpcode();
1022       else continue;
1023     }
1024 
1025     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1026       // In case of comparisons between two registers, these two registers
1027       // must be same to merge two comparisons.
1028       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1029                                          nullptr, nullptr, MRI);
1030       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1031                                          nullptr, nullptr, MRI);
1032       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1033                                          MBB1, &MBB2, MRI);
1034       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1035                                          MBB1, &MBB2, MRI);
1036 
1037       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1038         // Same pair of registers in the same order; ready to merge as is.
1039       }
1040       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1041         // Same pair of registers in different order.
1042         // We reverse the predicate to merge compare instructions.
1043         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
1044         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1045         // In case of partial redundancy, we need to swap operands
1046         // in another compare instruction.
1047         SwapOperands = true;
1048       }
1049       else continue;
1050     }
1051     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1052       // In case of comparisons between a register and an immediate,
1053       // the operand register must be same for two compare instructions.
1054       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1055                                          nullptr, nullptr, MRI);
1056       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1057                                          MBB1, &MBB2, MRI);
1058       if (Cmp1Operand1 != Cmp2Operand1)
1059         continue;
1060 
1061       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1062       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1063 
1064       // If immediate are not same, we try to adjust by changing predicate;
1065       // e.g. GT imm means GE (imm+1).
1066       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1067         int Diff = Imm1 - Imm2;
1068         if (Diff < -2 || Diff > 2)
1069           continue;
1070 
1071         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1072         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1073         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1074         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1075         if (Diff == 2) {
1076           if (PredToInc2 && PredToDec1) {
1077             NewPredicate2 = PredToInc2;
1078             NewPredicate1 = PredToDec1;
1079             NewImm2++;
1080             NewImm1--;
1081           }
1082         }
1083         else if (Diff == 1) {
1084           if (PredToInc2) {
1085             NewImm2++;
1086             NewPredicate2 = PredToInc2;
1087           }
1088           else if (PredToDec1) {
1089             NewImm1--;
1090             NewPredicate1 = PredToDec1;
1091           }
1092         }
1093         else if (Diff == -1) {
1094           if (PredToDec2) {
1095             NewImm2--;
1096             NewPredicate2 = PredToDec2;
1097           }
1098           else if (PredToInc1) {
1099             NewImm1++;
1100             NewPredicate1 = PredToInc1;
1101           }
1102         }
1103         else if (Diff == -2) {
1104           if (PredToDec2 && PredToInc1) {
1105             NewPredicate2 = PredToDec2;
1106             NewPredicate1 = PredToInc1;
1107             NewImm2--;
1108             NewImm1++;
1109           }
1110         }
1111       }
1112 
1113       // We cannnot merge two compares if the immediates are not same.
1114       if (NewImm2 != NewImm1)
1115         continue;
1116     }
1117 
1118     DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1119     DEBUG(CMPI1->dump());
1120     DEBUG(BI1->dump());
1121     DEBUG(CMPI2->dump());
1122     DEBUG(BI2->dump());
1123 
1124     // We adjust opcode, predicates and immediate as we determined above.
1125     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1126       CMPI1->setDesc(TII->get(NewOpCode));
1127     }
1128     if (NewPredicate1) {
1129       BI1->getOperand(0).setImm(NewPredicate1);
1130     }
1131     if (NewPredicate2) {
1132       BI2->getOperand(0).setImm(NewPredicate2);
1133     }
1134     if (NewImm1 != Imm1) {
1135       CMPI1->getOperand(2).setImm(NewImm1);
1136     }
1137 
1138     if (IsPartiallyRedundant) {
1139       // We touch up the compare instruction in MBB2 and move it to
1140       // a previous BB to handle partially redundant case.
1141       if (SwapOperands) {
1142         unsigned Op1 = CMPI2->getOperand(1).getReg();
1143         unsigned Op2 = CMPI2->getOperand(2).getReg();
1144         CMPI2->getOperand(1).setReg(Op2);
1145         CMPI2->getOperand(2).setReg(Op1);
1146       }
1147       if (NewImm2 != Imm2)
1148         CMPI2->getOperand(2).setImm(NewImm2);
1149 
1150       for (int I = 1; I <= 2; I++) {
1151         if (CMPI2->getOperand(I).isReg()) {
1152           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1153           if (Inst->getParent() != &MBB2)
1154             continue;
1155 
1156           assert(Inst->getOpcode() == PPC::PHI &&
1157                  "We cannot support if an operand comes from this BB.");
1158           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1159           CMPI2->getOperand(I).setReg(SrcReg);
1160         }
1161       }
1162       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1163       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1164 
1165       DebugLoc DL = CMPI2->getDebugLoc();
1166       unsigned NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1167       BuildMI(MBB2, MBB2.begin(), DL,
1168               TII->get(PPC::PHI), NewVReg)
1169         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1170         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1171       BI2->getOperand(1).setReg(NewVReg);
1172     }
1173     else {
1174       // We finally eliminate compare instruction in MBB2.
1175       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1176       CMPI2->eraseFromParent();
1177     }
1178     BI2->getOperand(1).setIsKill(true);
1179     BI1->getOperand(1).setIsKill(false);
1180 
1181     DEBUG(dbgs() << "into a compare and two branches:\n");
1182     DEBUG(CMPI1->dump());
1183     DEBUG(BI1->dump());
1184     DEBUG(BI2->dump());
1185     if (IsPartiallyRedundant) {
1186       DEBUG(dbgs() << "The following compare is moved into BB#" <<
1187             MBBtoMoveCmp->getNumber() << " to handle partial redundancy.\n");
1188       DEBUG(CMPI2->dump());
1189     }
1190 
1191     Simplified = true;
1192   }
1193 
1194   return Simplified;
1195 }
1196 
1197 // This is used to find the "true" source register for an
1198 // XXPERMDI instruction, since MachineCSE does not handle the
1199 // "copy-like" operations (Copy and SubregToReg).  Returns
1200 // the original SrcReg unless it is the target of a copy-like
1201 // operation, in which case we chain backwards through all
1202 // such operations to the ultimate source register.  If a
1203 // physical register is encountered, we stop the search.
1204 unsigned PPCMIPeephole::lookThruCopyLike(unsigned SrcReg) {
1205 
1206   while (true) {
1207 
1208     MachineInstr *MI = MRI->getVRegDef(SrcReg);
1209     if (!MI->isCopyLike())
1210       return SrcReg;
1211 
1212     unsigned CopySrcReg;
1213     if (MI->isCopy())
1214       CopySrcReg = MI->getOperand(1).getReg();
1215     else {
1216       assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
1217       CopySrcReg = MI->getOperand(2).getReg();
1218     }
1219 
1220     if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg))
1221       return CopySrcReg;
1222 
1223     SrcReg = CopySrcReg;
1224   }
1225 }
1226 
1227 } // end default namespace
1228 
1229 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
1230                       "PowerPC MI Peephole Optimization", false, false)
1231 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
1232                     "PowerPC MI Peephole Optimization", false, false)
1233 
1234 char PPCMIPeephole::ID = 0;
1235 FunctionPass*
1236 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
1237 
1238