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