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