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