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