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