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