xref: /llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp (revision 79c0bec06ee471b41b97d17c7fb6297f15eb2b19)
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 "MCTargetDesc/PPCPredicates.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "ppc-mi-peepholes"
37 
38 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
39 
40 namespace llvm {
41   void initializePPCMIPeepholePass(PassRegistry&);
42 }
43 
44 namespace {
45 
46 struct PPCMIPeephole : public MachineFunctionPass {
47 
48   static char ID;
49   const PPCInstrInfo *TII;
50   MachineFunction *MF;
51   MachineRegisterInfo *MRI;
52 
53   PPCMIPeephole() : MachineFunctionPass(ID) {
54     initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
55   }
56 
57 private:
58   MachineDominatorTree *MDT;
59 
60   // Initialize class variables.
61   void initialize(MachineFunction &MFParm);
62 
63   // Perform peepholes.
64   bool simplifyCode(void);
65 
66   // Perform peepholes.
67   bool eliminateRedundantCompare(void);
68 
69   // Find the "true" register represented by SrcReg (following chains
70   // of copies and subreg_to_reg operations).
71   unsigned lookThruCopyLike(unsigned SrcReg);
72 
73 public:
74 
75   void getAnalysisUsage(AnalysisUsage &AU) const override {
76     AU.addRequired<MachineDominatorTree>();
77     AU.addPreserved<MachineDominatorTree>();
78     MachineFunctionPass::getAnalysisUsage(AU);
79   }
80 
81   // Main entry point for this pass.
82   bool runOnMachineFunction(MachineFunction &MF) override {
83     if (skipFunction(*MF.getFunction()))
84       return false;
85     initialize(MF);
86     return simplifyCode();
87   }
88 };
89 
90 // Initialize class variables.
91 void PPCMIPeephole::initialize(MachineFunction &MFParm) {
92   MF = &MFParm;
93   MRI = &MF->getRegInfo();
94   MDT = &getAnalysis<MachineDominatorTree>();
95   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
96   DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
97   DEBUG(MF->dump());
98 }
99 
100 static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
101                                       MachineRegisterInfo *MRI) {
102   assert(Op && "Invalid Operand!");
103   if (!Op->isReg())
104     return nullptr;
105 
106   unsigned Reg = Op->getReg();
107   if (!TargetRegisterInfo::isVirtualRegister(Reg))
108     return nullptr;
109 
110   return MRI->getVRegDef(Reg);
111 }
112 
113 // Perform peephole optimizations.
114 bool PPCMIPeephole::simplifyCode(void) {
115   bool Simplified = false;
116   MachineInstr* ToErase = nullptr;
117 
118   for (MachineBasicBlock &MBB : *MF) {
119     for (MachineInstr &MI : MBB) {
120 
121       // If the previous instruction was marked for elimination,
122       // remove it now.
123       if (ToErase) {
124         ToErase->eraseFromParent();
125         ToErase = nullptr;
126       }
127 
128       // Ignore debug instructions.
129       if (MI.isDebugValue())
130         continue;
131 
132       // Per-opcode peepholes.
133       switch (MI.getOpcode()) {
134 
135       default:
136         break;
137 
138       case PPC::XXPERMDI: {
139         // Perform simplifications of 2x64 vector swaps and splats.
140         // A swap is identified by an immediate value of 2, and a splat
141         // is identified by an immediate value of 0 or 3.
142         int Immed = MI.getOperand(3).getImm();
143 
144         if (Immed != 1) {
145 
146           // For each of these simplifications, we need the two source
147           // regs to match.  Unfortunately, MachineCSE ignores COPY and
148           // SUBREG_TO_REG, so for example we can see
149           //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
150           // We have to look through chains of COPY and SUBREG_TO_REG
151           // to find the real source values for comparison.
152           unsigned TrueReg1 = lookThruCopyLike(MI.getOperand(1).getReg());
153           unsigned TrueReg2 = lookThruCopyLike(MI.getOperand(2).getReg());
154 
155           if (TrueReg1 == TrueReg2
156               && TargetRegisterInfo::isVirtualRegister(TrueReg1)) {
157             MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
158             unsigned DefOpc = DefMI ? DefMI->getOpcode() : 0;
159 
160             // If this is a splat fed by a splatting load, the splat is
161             // redundant. Replace with a copy. This doesn't happen directly due
162             // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
163             // a load of a double to a vector of 64-bit integers.
164             auto isConversionOfLoadAndSplat = [=]() -> bool {
165               if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
166                 return false;
167               unsigned DefReg = lookThruCopyLike(DefMI->getOperand(1).getReg());
168               if (TargetRegisterInfo::isVirtualRegister(DefReg)) {
169                 MachineInstr *LoadMI = MRI->getVRegDef(DefReg);
170                 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
171                   return true;
172               }
173               return false;
174             };
175             if (DefMI && (Immed == 0 || Immed == 3)) {
176               if (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat()) {
177                 DEBUG(dbgs()
178                       << "Optimizing load-and-splat/splat "
179                       "to load-and-splat/copy: ");
180                 DEBUG(MI.dump());
181                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
182                         MI.getOperand(0).getReg())
183                     .add(MI.getOperand(1));
184                 ToErase = &MI;
185                 Simplified = true;
186               }
187             }
188 
189             // If this is a splat or a swap fed by another splat, we
190             // can replace it with a copy.
191             if (DefOpc == PPC::XXPERMDI) {
192               unsigned FeedImmed = DefMI->getOperand(3).getImm();
193               unsigned FeedReg1
194                 = lookThruCopyLike(DefMI->getOperand(1).getReg());
195               unsigned FeedReg2
196                 = lookThruCopyLike(DefMI->getOperand(2).getReg());
197 
198               if ((FeedImmed == 0 || FeedImmed == 3) && FeedReg1 == FeedReg2) {
199                 DEBUG(dbgs()
200                       << "Optimizing splat/swap or splat/splat "
201                       "to splat/copy: ");
202                 DEBUG(MI.dump());
203                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
204                         MI.getOperand(0).getReg())
205                     .add(MI.getOperand(1));
206                 ToErase = &MI;
207                 Simplified = true;
208               }
209 
210               // If this is a splat fed by a swap, we can simplify modify
211               // the splat to splat the other value from the swap's input
212               // parameter.
213               else if ((Immed == 0 || Immed == 3)
214                        && FeedImmed == 2 && FeedReg1 == FeedReg2) {
215                 DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
216                 DEBUG(MI.dump());
217                 MI.getOperand(1).setReg(DefMI->getOperand(1).getReg());
218                 MI.getOperand(2).setReg(DefMI->getOperand(2).getReg());
219                 MI.getOperand(3).setImm(3 - Immed);
220                 Simplified = true;
221               }
222 
223               // If this is a swap fed by a swap, we can replace it
224               // with a copy from the first swap's input.
225               else if (Immed == 2 && FeedImmed == 2 && FeedReg1 == FeedReg2) {
226                 DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
227                 DEBUG(MI.dump());
228                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
229                         MI.getOperand(0).getReg())
230                     .add(DefMI->getOperand(1));
231                 ToErase = &MI;
232                 Simplified = true;
233               }
234             } else if ((Immed == 0 || Immed == 3) && DefOpc == PPC::XXPERMDIs &&
235                        (DefMI->getOperand(2).getImm() == 0 ||
236                         DefMI->getOperand(2).getImm() == 3)) {
237               // Splat fed by another splat - switch the output of the first
238               // and remove the second.
239               DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
240               ToErase = &MI;
241               Simplified = true;
242               DEBUG(dbgs() << "Removing redundant splat: ");
243               DEBUG(MI.dump());
244             }
245           }
246         }
247         break;
248       }
249       case PPC::VSPLTB:
250       case PPC::VSPLTH:
251       case PPC::XXSPLTW: {
252         unsigned MyOpcode = MI.getOpcode();
253         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
254         unsigned TrueReg = lookThruCopyLike(MI.getOperand(OpNo).getReg());
255         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
256           break;
257         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
258         if (!DefMI)
259           break;
260         unsigned DefOpcode = DefMI->getOpcode();
261         auto isConvertOfSplat = [=]() -> bool {
262           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
263             return false;
264           unsigned ConvReg = DefMI->getOperand(1).getReg();
265           if (!TargetRegisterInfo::isVirtualRegister(ConvReg))
266             return false;
267           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
268           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
269             Splt->getOpcode() == PPC::XXSPLTW);
270         };
271         bool AlreadySplat = (MyOpcode == DefOpcode) ||
272           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
273           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
274           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
275           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
276           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
277           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
278         // If the instruction[s] that feed this splat have already splat
279         // the value, this splat is redundant.
280         if (AlreadySplat) {
281           DEBUG(dbgs() << "Changing redundant splat to a copy: ");
282           DEBUG(MI.dump());
283           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
284                   MI.getOperand(0).getReg())
285               .add(MI.getOperand(OpNo));
286           ToErase = &MI;
287           Simplified = true;
288         }
289         // Splat fed by a shift. Usually when we align value to splat into
290         // vector element zero.
291         if (DefOpcode == PPC::XXSLDWI) {
292           unsigned ShiftRes = DefMI->getOperand(0).getReg();
293           unsigned ShiftOp1 = DefMI->getOperand(1).getReg();
294           unsigned ShiftOp2 = DefMI->getOperand(2).getReg();
295           unsigned ShiftImm = DefMI->getOperand(3).getImm();
296           unsigned SplatImm = MI.getOperand(2).getImm();
297           if (ShiftOp1 == ShiftOp2) {
298             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
299             if (MRI->hasOneNonDBGUse(ShiftRes)) {
300               DEBUG(dbgs() << "Removing redundant shift: ");
301               DEBUG(DefMI->dump());
302               ToErase = DefMI;
303             }
304             Simplified = true;
305             DEBUG(dbgs() << "Changing splat immediate from " << SplatImm <<
306                   " to " << NewElem << " in instruction: ");
307             DEBUG(MI.dump());
308             MI.getOperand(1).setReg(ShiftOp1);
309             MI.getOperand(2).setImm(NewElem);
310           }
311         }
312         break;
313       }
314       case PPC::XVCVDPSP: {
315         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
316         unsigned TrueReg = lookThruCopyLike(MI.getOperand(1).getReg());
317         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
318           break;
319         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
320 
321         // This can occur when building a vector of single precision or integer
322         // values.
323         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
324           unsigned DefsReg1 = lookThruCopyLike(DefMI->getOperand(1).getReg());
325           unsigned DefsReg2 = lookThruCopyLike(DefMI->getOperand(2).getReg());
326           if (!TargetRegisterInfo::isVirtualRegister(DefsReg1) ||
327               !TargetRegisterInfo::isVirtualRegister(DefsReg2))
328             break;
329           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
330           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
331 
332           if (!P1 || !P2)
333             break;
334 
335           // Remove the passed FRSP instruction if it only feeds this MI and
336           // set any uses of that FRSP (in this MI) to the source of the FRSP.
337           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
338             if (RoundInstr->getOpcode() == PPC::FRSP &&
339                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
340               Simplified = true;
341               unsigned ConvReg1 = RoundInstr->getOperand(1).getReg();
342               unsigned FRSPDefines = RoundInstr->getOperand(0).getReg();
343               MachineInstr &Use = *(MRI->use_instr_begin(FRSPDefines));
344               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
345                 if (Use.getOperand(i).isReg() &&
346                     Use.getOperand(i).getReg() == FRSPDefines)
347                   Use.getOperand(i).setReg(ConvReg1);
348               DEBUG(dbgs() << "Removing redundant FRSP:\n");
349               DEBUG(RoundInstr->dump());
350               DEBUG(dbgs() << "As it feeds instruction:\n");
351               DEBUG(MI.dump());
352               DEBUG(dbgs() << "Through instruction:\n");
353               DEBUG(DefMI->dump());
354               RoundInstr->eraseFromParent();
355             }
356           };
357 
358           // If the input to XVCVDPSP is a vector that was built (even
359           // partially) out of FRSP's, the FRSP(s) can safely be removed
360           // since this instruction performs the same operation.
361           if (P1 != P2) {
362             removeFRSPIfPossible(P1);
363             removeFRSPIfPossible(P2);
364             break;
365           }
366           removeFRSPIfPossible(P1);
367         }
368         break;
369       }
370 
371       // TODO: Any instruction that has an immediate form fed only by a PHI
372       // whose operands are all load immediate can be folded away. We currently
373       // do this for ADD instructions, but should expand it to arithmetic and
374       // binary instructions with immediate forms in the future.
375       case PPC::ADD4:
376       case PPC::ADD8: {
377         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
378           assert(PhiOp && "Invalid Operand!");
379           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
380 
381           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
382                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
383         };
384 
385         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
386                                             MachineOperand *PhiOp) {
387           assert(PhiOp && "Invalid Operand!");
388           assert(DominatorOp && "Invalid Operand!");
389           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
390           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
391 
392           // Note: the vregs only show up at odd indices position of PHI Node,
393           // the even indices position save the BB info.
394           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
395             MachineInstr *LiMI =
396                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
397             if (!LiMI || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
398                 !MDT->dominates(DefDomMI, LiMI) ||
399                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8))
400               return false;
401           }
402 
403           return true;
404         };
405 
406         MachineOperand Op1 = MI.getOperand(1);
407         MachineOperand Op2 = MI.getOperand(2);
408         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
409           std::swap(Op1, Op2);
410         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
411           break; // We don't have an ADD fed by LI's that can be transformed
412 
413         // Now we know that Op1 is the PHI node and Op2 is the dominator
414         unsigned DominatorReg = Op2.getReg();
415 
416         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
417                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
418                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
419         MRI->setRegClass(DominatorReg, TRC);
420 
421         // replace LIs with ADDIs
422         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
423         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
424           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
425           DEBUG(dbgs() << "Optimizing LI to ADDI: ");
426           DEBUG(LiMI->dump());
427 
428           // There could be repeated registers in the PHI, e.g: %vreg1<def> =
429           // PHI %vreg6, <BB#2>, %vreg8, <BB#3>, %vreg8, <BB#6>; So if we've
430           // already replaced the def instruction, skip.
431           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
432             continue;
433 
434           assert((LiMI->getOpcode() == PPC::LI ||
435                   LiMI->getOpcode() == PPC::LI8) &&
436                  "Invalid Opcode!");
437           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
438           LiMI->RemoveOperand(1);                    // remove the imm of LI
439           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
440                                                               : PPC::ADDI8));
441           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
442               .addReg(DominatorReg)
443               .addImm(LiImm); // restore the imm of LI
444           DEBUG(LiMI->dump());
445         }
446 
447         // Replace ADD with COPY
448         DEBUG(dbgs() << "Optimizing ADD to COPY: ");
449         DEBUG(MI.dump());
450         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
451                 MI.getOperand(0).getReg())
452             .add(Op1);
453         ToErase = &MI;
454         Simplified = true;
455         NumOptADDLIs++;
456         break;
457       }
458       }
459     }
460 
461     // If the last instruction was marked for elimination,
462     // remove it now.
463     if (ToErase) {
464       ToErase->eraseFromParent();
465       ToErase = nullptr;
466     }
467   }
468 
469   // We try to eliminate redundant compare instruction.
470   Simplified |= eliminateRedundantCompare();
471 
472   return Simplified;
473 }
474 
475 // helper functions for eliminateRedundantCompare
476 static bool isEqOrNe(MachineInstr *BI) {
477   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
478   unsigned PredCond = PPC::getPredicateCondition(Pred);
479   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
480 }
481 
482 static bool isSupportedCmpOp(unsigned opCode) {
483   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
484           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
485           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
486           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
487 }
488 
489 static bool is64bitCmpOp(unsigned opCode) {
490   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
491           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
492 }
493 
494 static bool isSignedCmpOp(unsigned opCode) {
495   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
496           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
497 }
498 
499 static unsigned getSignedCmpOpCode(unsigned opCode) {
500   if (opCode == PPC::CMPLD)  return PPC::CMPD;
501   if (opCode == PPC::CMPLW)  return PPC::CMPW;
502   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
503   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
504   return opCode;
505 }
506 
507 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
508 // (LT x) to (LE x-1)
509 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
510   uint64_t Imm = CMPI->getOperand(2).getImm();
511   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
512   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
513     return 0;
514 
515   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
516   unsigned PredCond = PPC::getPredicateCondition(Pred);
517   unsigned PredHint = PPC::getPredicateHint(Pred);
518   if (PredCond == PPC::PRED_GE)
519     return PPC::getPredicate(PPC::PRED_GT, PredHint);
520   if (PredCond == PPC::PRED_LT)
521     return PPC::getPredicate(PPC::PRED_LE, PredHint);
522 
523   return 0;
524 }
525 
526 // We can increment immediate x in (GT x) by changing it to (GE x+1) or
527 // (LE x) to (LT x+1)
528 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
529   uint64_t Imm = CMPI->getOperand(2).getImm();
530   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
531   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
532     return 0;
533 
534   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
535   unsigned PredCond = PPC::getPredicateCondition(Pred);
536   unsigned PredHint = PPC::getPredicateHint(Pred);
537   if (PredCond == PPC::PRED_GT)
538     return PPC::getPredicate(PPC::PRED_GE, PredHint);
539   if (PredCond == PPC::PRED_LE)
540     return PPC::getPredicate(PPC::PRED_LT, PredHint);
541 
542   return 0;
543 }
544 
545 // This takes a Phi node and returns a register value for the spefied BB.
546 static unsigned getIncomingRegForBlock(MachineInstr *Phi,
547                                        MachineBasicBlock *MBB) {
548   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
549     MachineOperand &MO = Phi->getOperand(I);
550     if (MO.getMBB() == MBB)
551       return Phi->getOperand(I-1).getReg();
552   }
553   llvm_unreachable("invalid src basic block for this Phi node\n");
554   return 0;
555 }
556 
557 // This function tracks the source of the register through register copy.
558 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
559 // assuming that the control comes from BB1 into BB2.
560 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
561                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
562   unsigned SrcReg = Reg;
563   while (1) {
564     unsigned NextReg = SrcReg;
565     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
566     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
567       NextReg = getIncomingRegForBlock(Inst, BB1);
568       // We track through PHI only once to avoid infinite loop.
569       BB1 = nullptr;
570     }
571     else if (Inst->isFullCopy())
572       NextReg = Inst->getOperand(1).getReg();
573     if (NextReg == SrcReg || !TargetRegisterInfo::isVirtualRegister(NextReg))
574       break;
575     SrcReg = NextReg;
576   }
577   return SrcReg;
578 }
579 
580 static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
581                                           MachineBasicBlock *&PredMBB,
582                                           MachineBasicBlock *&MBBtoMoveCmp,
583                                           MachineRegisterInfo *MRI) {
584 
585   auto isEligibleBB = [&](MachineBasicBlock &BB) {
586     auto BII = BB.getFirstInstrTerminator();
587     // We optimize BBs ending with a conditional branch.
588     // We check only for BCC here, not BCCLR, because BCCLR
589     // will be formed only later in the pipeline.
590     if (BB.succ_size() == 2 &&
591         BII != BB.instr_end() &&
592         (*BII).getOpcode() == PPC::BCC &&
593         (*BII).getOperand(1).isReg()) {
594       // We optimize only if the condition code is used only by one BCC.
595       unsigned CndReg = (*BII).getOperand(1).getReg();
596       if (!TargetRegisterInfo::isVirtualRegister(CndReg) ||
597           !MRI->hasOneNonDBGUse(CndReg))
598         return false;
599 
600       // We skip this BB if a physical register is used in comparison.
601       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
602       for (MachineOperand &MO : CMPI->operands())
603         if (MO.isReg() && !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
604           return false;
605 
606       return true;
607     }
608     return false;
609   };
610 
611   // If this BB has more than one successor, we can create a new BB and
612   // move the compare instruction in the new BB.
613   // So far, we do not move compare instruction to a BB having multiple
614   // successors to avoid potentially increasing code size.
615   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
616     return BB.succ_size() == 1;
617   };
618 
619   if (!isEligibleBB(MBB))
620     return false;
621 
622   unsigned NumPredBBs = MBB.pred_size();
623   if (NumPredBBs == 1) {
624     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
625     if (isEligibleBB(*TmpMBB)) {
626       PredMBB = TmpMBB;
627       MBBtoMoveCmp = nullptr;
628       return true;
629     }
630   }
631   else if (NumPredBBs == 2) {
632     // We check for partially redundant case.
633     // So far, we support cases with only two predecessors
634     // to avoid increasing the number of instructions.
635     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
636     MachineBasicBlock *Pred1MBB = *PI;
637     MachineBasicBlock *Pred2MBB = *(PI+1);
638 
639     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
640       // We assume Pred1MBB is the BB containing the compare to be merged and
641       // Pred2MBB is the BB to which we will append a compare instruction.
642       // Hence we can proceed as is.
643     }
644     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
645       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
646       std::swap(Pred1MBB, Pred2MBB);
647     }
648     else return false;
649 
650     // Here, Pred2MBB is the BB to which we need to append a compare inst.
651     // We cannot move the compare instruction if operands are not available
652     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
653     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
654     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
655     for (int I = 1; I <= 2; I++)
656       if (CMPI->getOperand(I).isReg()) {
657         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
658         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
659           return false;
660       }
661 
662     PredMBB = Pred1MBB;
663     MBBtoMoveCmp = Pred2MBB;
664     return true;
665   }
666 
667   return false;
668 }
669 
670 // If multiple conditional branches are executed based on the (essentially)
671 // same comparison, we merge compare instructions into one and make multiple
672 // conditional branches on this comparison.
673 // For example,
674 //   if (a == 0) { ... }
675 //   else if (a < 0) { ... }
676 // can be executed by one compare and two conditional branches instead of
677 // two pairs of a compare and a conditional branch.
678 //
679 // This method merges two compare instructions in two MBBs and modifies the
680 // compare and conditional branch instructions if needed.
681 // For the above example, the input for this pass looks like:
682 //   cmplwi r3, 0
683 //   beq    0, .LBB0_3
684 //   cmpwi  r3, -1
685 //   bgt    0, .LBB0_4
686 // So, before merging two compares, we need to modify these instructions as
687 //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
688 //   beq    0, .LBB0_3
689 //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
690 //   bge    0, .LBB0_4
691 
692 bool PPCMIPeephole::eliminateRedundantCompare(void) {
693   bool Simplified = false;
694 
695   for (MachineBasicBlock &MBB2 : *MF) {
696     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
697 
698     // For fully redundant case, we select two basic blocks MBB1 and MBB2
699     // as an optimization target if
700     // - both MBBs end with a conditional branch,
701     // - MBB1 is the only predecessor of MBB2, and
702     // - compare does not take a physical register as a operand in both MBBs.
703     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
704     //
705     // As partially redundant case, we additionally handle if MBB2 has one
706     // additional predecessor, which has only one successor (MBB2).
707     // In this case, we move the compre instruction originally in MBB2 into
708     // MBBtoMoveCmp. This partially redundant case is typically appear by
709     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
710     //
711     // Overview of CFG of related basic blocks
712     // Fully redundant case        Partially redundant case
713     //   --------                   ----------------  --------
714     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
715     //   --------                   ----------------  --------
716     //      |    \                     (w/ 1 succ) \     |    \
717     //      |     \                                 \    |     \
718     //      |                                        \   |
719     //   --------                                     --------
720     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
721     //   -------- and 2 succ)                         -------- and 2 succ)
722     //      |    \                                       |    \
723     //      |     \                                      |     \
724     //
725     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
726       continue;
727 
728     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
729     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
730 
731     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
732     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
733     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
734 
735     // We cannot optimize an unsupported compare opcode or
736     // a mix of 32-bit and 64-bit comaprisons
737     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
738         !isSupportedCmpOp(CMPI2->getOpcode()) ||
739         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
740       continue;
741 
742     unsigned NewOpCode = 0;
743     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
744     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
745     bool SwapOperands = false;
746 
747     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
748       // Typically, unsigned comparison is used for equality check, but
749       // we replace it with a signed comparison if the comparison
750       // to be merged is a signed comparison.
751       // In other cases of opcode mismatch, we cannot optimize this.
752       if (isEqOrNe(BI2) &&
753           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
754         NewOpCode = CMPI1->getOpcode();
755       else if (isEqOrNe(BI1) &&
756                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
757         NewOpCode = CMPI2->getOpcode();
758       else continue;
759     }
760 
761     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
762       // In case of comparisons between two registers, these two registers
763       // must be same to merge two comparisons.
764       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
765                                          nullptr, nullptr, MRI);
766       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
767                                          nullptr, nullptr, MRI);
768       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
769                                          MBB1, &MBB2, MRI);
770       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
771                                          MBB1, &MBB2, MRI);
772 
773       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
774         // Same pair of registers in the same order; ready to merge as is.
775       }
776       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
777         // Same pair of registers in different order.
778         // We reverse the predicate to merge compare instructions.
779         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
780         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
781         // In case of partial redundancy, we need to swap operands
782         // in another compare instruction.
783         SwapOperands = true;
784       }
785       else continue;
786     }
787     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()){
788       // In case of comparisons between a register and an immediate,
789       // the operand register must be same for two compare instructions.
790       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
791                                          nullptr, nullptr, MRI);
792       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
793                                          MBB1, &MBB2, MRI);
794       if (Cmp1Operand1 != Cmp2Operand1)
795         continue;
796 
797       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
798       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
799 
800       // If immediate are not same, we try to adjust by changing predicate;
801       // e.g. GT imm means GE (imm+1).
802       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
803         int Diff = Imm1 - Imm2;
804         if (Diff < -2 || Diff > 2)
805           continue;
806 
807         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
808         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
809         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
810         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
811         if (Diff == 2) {
812           if (PredToInc2 && PredToDec1) {
813             NewPredicate2 = PredToInc2;
814             NewPredicate1 = PredToDec1;
815             NewImm2++;
816             NewImm1--;
817           }
818         }
819         else if (Diff == 1) {
820           if (PredToInc2) {
821             NewImm2++;
822             NewPredicate2 = PredToInc2;
823           }
824           else if (PredToDec1) {
825             NewImm1--;
826             NewPredicate1 = PredToDec1;
827           }
828         }
829         else if (Diff == -1) {
830           if (PredToDec2) {
831             NewImm2--;
832             NewPredicate2 = PredToDec2;
833           }
834           else if (PredToInc1) {
835             NewImm1++;
836             NewPredicate1 = PredToInc1;
837           }
838         }
839         else if (Diff == -2) {
840           if (PredToDec2 && PredToInc1) {
841             NewPredicate2 = PredToDec2;
842             NewPredicate1 = PredToInc1;
843             NewImm2--;
844             NewImm1++;
845           }
846         }
847       }
848 
849       // We cannnot merge two compares if the immediates are not same.
850       if (NewImm2 != NewImm1)
851         continue;
852     }
853 
854     DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
855     DEBUG(CMPI1->dump());
856     DEBUG(BI1->dump());
857     DEBUG(CMPI2->dump());
858     DEBUG(BI2->dump());
859 
860     // We adjust opcode, predicates and immediate as we determined above.
861     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
862       CMPI1->setDesc(TII->get(NewOpCode));
863     }
864     if (NewPredicate1) {
865       BI1->getOperand(0).setImm(NewPredicate1);
866     }
867     if (NewPredicate2) {
868       BI2->getOperand(0).setImm(NewPredicate2);
869     }
870     if (NewImm1 != Imm1) {
871       CMPI1->getOperand(2).setImm(NewImm1);
872     }
873 
874     if (IsPartiallyRedundant) {
875       // We touch up the compare instruction in MBB2 and move it to
876       // a previous BB to handle partially redundant case.
877       if (SwapOperands) {
878         unsigned Op1 = CMPI2->getOperand(1).getReg();
879         unsigned Op2 = CMPI2->getOperand(2).getReg();
880         CMPI2->getOperand(1).setReg(Op2);
881         CMPI2->getOperand(2).setReg(Op1);
882       }
883       if (NewImm2 != Imm2)
884         CMPI2->getOperand(2).setImm(NewImm2);
885 
886       for (int I = 1; I <= 2; I++) {
887         if (CMPI2->getOperand(I).isReg()) {
888           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
889           if (Inst->getParent() != &MBB2)
890             continue;
891 
892           assert(Inst->getOpcode() == PPC::PHI &&
893                  "We cannot support if an operand comes from this BB.");
894           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
895           CMPI2->getOperand(I).setReg(SrcReg);
896         }
897       }
898       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
899       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
900 
901       DebugLoc DL = CMPI2->getDebugLoc();
902       unsigned NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
903       BuildMI(MBB2, MBB2.begin(), DL,
904               TII->get(PPC::PHI), NewVReg)
905         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
906         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
907       BI2->getOperand(1).setReg(NewVReg);
908     }
909     else {
910       // We finally eliminate compare instruction in MBB2.
911       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
912       CMPI2->eraseFromParent();
913     }
914     BI2->getOperand(1).setIsKill(true);
915     BI1->getOperand(1).setIsKill(false);
916 
917     DEBUG(dbgs() << "into a compare and two branches:\n");
918     DEBUG(CMPI1->dump());
919     DEBUG(BI1->dump());
920     DEBUG(BI2->dump());
921     if (IsPartiallyRedundant) {
922       DEBUG(dbgs() << "The following compare is moved into BB#" <<
923             MBBtoMoveCmp->getNumber() << " to handle partial redundancy.\n");
924       DEBUG(CMPI2->dump());
925     }
926 
927     Simplified = true;
928   }
929 
930   return Simplified;
931 }
932 
933 // This is used to find the "true" source register for an
934 // XXPERMDI instruction, since MachineCSE does not handle the
935 // "copy-like" operations (Copy and SubregToReg).  Returns
936 // the original SrcReg unless it is the target of a copy-like
937 // operation, in which case we chain backwards through all
938 // such operations to the ultimate source register.  If a
939 // physical register is encountered, we stop the search.
940 unsigned PPCMIPeephole::lookThruCopyLike(unsigned SrcReg) {
941 
942   while (true) {
943 
944     MachineInstr *MI = MRI->getVRegDef(SrcReg);
945     if (!MI->isCopyLike())
946       return SrcReg;
947 
948     unsigned CopySrcReg;
949     if (MI->isCopy())
950       CopySrcReg = MI->getOperand(1).getReg();
951     else {
952       assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
953       CopySrcReg = MI->getOperand(2).getReg();
954     }
955 
956     if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg))
957       return CopySrcReg;
958 
959     SrcReg = CopySrcReg;
960   }
961 }
962 
963 } // end default namespace
964 
965 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
966                       "PowerPC MI Peephole Optimization", false, false)
967 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
968                     "PowerPC MI Peephole Optimization", false, false)
969 
970 char PPCMIPeephole::ID = 0;
971 FunctionPass*
972 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
973 
974