1 //===-- HexagonPeephole.cpp - Hexagon Peephole Optimiztions ---------------===//
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 // This peephole pass optimizes in the following cases.
8 // 1. Optimizes redundant sign extends for the following case
9 //    Transform the following pattern
10 //    %170 = SXTW %166
11 //    ...
12 //    %176 = COPY %170:isub_lo
13 //
14 //    Into
15 //    %176 = COPY %166
16 //
17 //  2. Optimizes redundant negation of predicates.
18 //     %15 = CMPGTrr %6, %2
19 //     ...
20 //     %16 = NOT_p killed %15
21 //     ...
22 //     JMP_c killed %16, <%bb.1>, implicit dead %pc
23 //
24 //     Into
25 //     %15 = CMPGTrr %6, %2;
26 //     ...
27 //     JMP_cNot killed %15, <%bb.1>, implicit dead %pc;
28 //
29 // Note: The peephole pass makes the instrucstions like
30 // %170 = SXTW %166 or %16 = NOT_p killed %15
31 // redundant and relies on some form of dead removal instructions, like
32 // DCE or DIE to actually eliminate them.
33 
34 //===----------------------------------------------------------------------===//
35 
36 #include "Hexagon.h"
37 #include "HexagonTargetMachine.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/Passes.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include <algorithm>
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "hexagon-peephole"
58 
59 static cl::opt<bool> DisableHexagonPeephole("disable-hexagon-peephole",
60     cl::Hidden, cl::ZeroOrMore, cl::init(false),
61     cl::desc("Disable Peephole Optimization"));
62 
63 static cl::opt<bool> DisablePNotP("disable-hexagon-pnotp",
64     cl::Hidden, cl::ZeroOrMore, cl::init(false),
65     cl::desc("Disable Optimization of PNotP"));
66 
67 static cl::opt<bool> DisableOptSZExt("disable-hexagon-optszext",
68     cl::Hidden, cl::ZeroOrMore, cl::init(true),
69     cl::desc("Disable Optimization of Sign/Zero Extends"));
70 
71 static cl::opt<bool> DisableOptExtTo64("disable-hexagon-opt-ext-to-64",
72     cl::Hidden, cl::ZeroOrMore, cl::init(true),
73     cl::desc("Disable Optimization of extensions to i64."));
74 
75 namespace llvm {
76   FunctionPass *createHexagonPeephole();
77   void initializeHexagonPeepholePass(PassRegistry&);
78 }
79 
80 namespace {
81   struct HexagonPeephole : public MachineFunctionPass {
82     const HexagonInstrInfo    *QII;
83     const HexagonRegisterInfo *QRI;
84     const MachineRegisterInfo *MRI;
85 
86   public:
87     static char ID;
HexagonPeephole__anon315ff9f50111::HexagonPeephole88     HexagonPeephole() : MachineFunctionPass(ID) {
89       initializeHexagonPeepholePass(*PassRegistry::getPassRegistry());
90     }
91 
92     bool runOnMachineFunction(MachineFunction &MF) override;
93 
getPassName__anon315ff9f50111::HexagonPeephole94     StringRef getPassName() const override {
95       return "Hexagon optimize redundant zero and size extends";
96     }
97 
getAnalysisUsage__anon315ff9f50111::HexagonPeephole98     void getAnalysisUsage(AnalysisUsage &AU) const override {
99       MachineFunctionPass::getAnalysisUsage(AU);
100     }
101   };
102 }
103 
104 char HexagonPeephole::ID = 0;
105 
106 INITIALIZE_PASS(HexagonPeephole, "hexagon-peephole", "Hexagon Peephole",
107                 false, false)
108 
runOnMachineFunction(MachineFunction & MF)109 bool HexagonPeephole::runOnMachineFunction(MachineFunction &MF) {
110   if (skipFunction(MF.getFunction()))
111     return false;
112 
113   QII = static_cast<const HexagonInstrInfo *>(MF.getSubtarget().getInstrInfo());
114   QRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
115   MRI = &MF.getRegInfo();
116 
117   DenseMap<unsigned, unsigned> PeepholeMap;
118   DenseMap<unsigned, std::pair<unsigned, unsigned> > PeepholeDoubleRegsMap;
119 
120   if (DisableHexagonPeephole) return false;
121 
122   // Loop over all of the basic blocks.
123   for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
124        MBBb != MBBe; ++MBBb) {
125     MachineBasicBlock *MBB = &*MBBb;
126     PeepholeMap.clear();
127     PeepholeDoubleRegsMap.clear();
128 
129     // Traverse the basic block.
130     for (auto I = MBB->begin(), E = MBB->end(), NextI = I; I != E; I = NextI) {
131       NextI = std::next(I);
132       MachineInstr &MI = *I;
133       // Look for sign extends:
134       // %170 = SXTW %166
135       if (!DisableOptSZExt && MI.getOpcode() == Hexagon::A2_sxtw) {
136         assert(MI.getNumOperands() == 2);
137         MachineOperand &Dst = MI.getOperand(0);
138         MachineOperand &Src = MI.getOperand(1);
139         Register DstReg = Dst.getReg();
140         Register SrcReg = Src.getReg();
141         // Just handle virtual registers.
142         if (DstReg.isVirtual() && SrcReg.isVirtual()) {
143           // Map the following:
144           // %170 = SXTW %166
145           // PeepholeMap[170] = %166
146           PeepholeMap[DstReg] = SrcReg;
147         }
148       }
149 
150       // Look for  %170 = COMBINE_ir_V4 (0, %169)
151       // %170:DoublRegs, %169:IntRegs
152       if (!DisableOptExtTo64 && MI.getOpcode() == Hexagon::A4_combineir) {
153         assert(MI.getNumOperands() == 3);
154         MachineOperand &Dst = MI.getOperand(0);
155         MachineOperand &Src1 = MI.getOperand(1);
156         MachineOperand &Src2 = MI.getOperand(2);
157         if (Src1.getImm() != 0)
158           continue;
159         Register DstReg = Dst.getReg();
160         Register SrcReg = Src2.getReg();
161         PeepholeMap[DstReg] = SrcReg;
162       }
163 
164       // Look for this sequence below
165       // %DoubleReg1 = LSRd_ri %DoubleReg0, 32
166       // %IntReg = COPY %DoubleReg1:isub_lo.
167       // and convert into
168       // %IntReg = COPY %DoubleReg0:isub_hi.
169       if (MI.getOpcode() == Hexagon::S2_lsr_i_p) {
170         assert(MI.getNumOperands() == 3);
171         MachineOperand &Dst = MI.getOperand(0);
172         MachineOperand &Src1 = MI.getOperand(1);
173         MachineOperand &Src2 = MI.getOperand(2);
174         if (Src2.getImm() != 32)
175           continue;
176         Register DstReg = Dst.getReg();
177         Register SrcReg = Src1.getReg();
178         PeepholeDoubleRegsMap[DstReg] =
179           std::make_pair(*&SrcReg, Hexagon::isub_hi);
180       }
181 
182       // Look for P=NOT(P).
183       if (!DisablePNotP && MI.getOpcode() == Hexagon::C2_not) {
184         assert(MI.getNumOperands() == 2);
185         MachineOperand &Dst = MI.getOperand(0);
186         MachineOperand &Src = MI.getOperand(1);
187         Register DstReg = Dst.getReg();
188         Register SrcReg = Src.getReg();
189         // Just handle virtual registers.
190         if (DstReg.isVirtual() && SrcReg.isVirtual()) {
191           // Map the following:
192           // %170 = NOT_xx %166
193           // PeepholeMap[170] = %166
194           PeepholeMap[DstReg] = SrcReg;
195         }
196       }
197 
198       // Look for copy:
199       // %176 = COPY %170:isub_lo
200       if (!DisableOptSZExt && MI.isCopy()) {
201         assert(MI.getNumOperands() == 2);
202         MachineOperand &Dst = MI.getOperand(0);
203         MachineOperand &Src = MI.getOperand(1);
204 
205         // Make sure we are copying the lower 32 bits.
206         if (Src.getSubReg() != Hexagon::isub_lo)
207           continue;
208 
209         Register DstReg = Dst.getReg();
210         Register SrcReg = Src.getReg();
211         if (DstReg.isVirtual() && SrcReg.isVirtual()) {
212           // Try to find in the map.
213           if (unsigned PeepholeSrc = PeepholeMap.lookup(SrcReg)) {
214             // Change the 1st operand.
215             MI.RemoveOperand(1);
216             MI.addOperand(MachineOperand::CreateReg(PeepholeSrc, false));
217           } else  {
218             DenseMap<unsigned, std::pair<unsigned, unsigned> >::iterator DI =
219               PeepholeDoubleRegsMap.find(SrcReg);
220             if (DI != PeepholeDoubleRegsMap.end()) {
221               std::pair<unsigned,unsigned> PeepholeSrc = DI->second;
222               MI.RemoveOperand(1);
223               MI.addOperand(MachineOperand::CreateReg(
224                   PeepholeSrc.first, false /*isDef*/, false /*isImp*/,
225                   false /*isKill*/, false /*isDead*/, false /*isUndef*/,
226                   false /*isEarlyClobber*/, PeepholeSrc.second));
227             }
228           }
229         }
230       }
231 
232       // Look for Predicated instructions.
233       if (!DisablePNotP) {
234         bool Done = false;
235         if (QII->isPredicated(MI)) {
236           MachineOperand &Op0 = MI.getOperand(0);
237           Register Reg0 = Op0.getReg();
238           const TargetRegisterClass *RC0 = MRI->getRegClass(Reg0);
239           if (RC0->getID() == Hexagon::PredRegsRegClassID) {
240             // Handle instructions that have a prediate register in op0
241             // (most cases of predicable instructions).
242             if (Reg0.isVirtual()) {
243               // Try to find in the map.
244               if (unsigned PeepholeSrc = PeepholeMap.lookup(Reg0)) {
245                 // Change the 1st operand and, flip the opcode.
246                 MI.getOperand(0).setReg(PeepholeSrc);
247                 MRI->clearKillFlags(PeepholeSrc);
248                 int NewOp = QII->getInvertedPredicatedOpcode(MI.getOpcode());
249                 MI.setDesc(QII->get(NewOp));
250                 Done = true;
251               }
252             }
253           }
254         }
255 
256         if (!Done) {
257           // Handle special instructions.
258           unsigned Op = MI.getOpcode();
259           unsigned NewOp = 0;
260           unsigned PR = 1, S1 = 2, S2 = 3;   // Operand indices.
261 
262           switch (Op) {
263             case Hexagon::C2_mux:
264             case Hexagon::C2_muxii:
265               NewOp = Op;
266               break;
267             case Hexagon::C2_muxri:
268               NewOp = Hexagon::C2_muxir;
269               break;
270             case Hexagon::C2_muxir:
271               NewOp = Hexagon::C2_muxri;
272               break;
273           }
274           if (NewOp) {
275             Register PSrc = MI.getOperand(PR).getReg();
276             if (unsigned POrig = PeepholeMap.lookup(PSrc)) {
277               BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
278                       QII->get(NewOp), MI.getOperand(0).getReg())
279                 .addReg(POrig)
280                 .add(MI.getOperand(S2))
281                 .add(MI.getOperand(S1));
282               MRI->clearKillFlags(POrig);
283               MI.eraseFromParent();
284             }
285           } // if (NewOp)
286         } // if (!Done)
287 
288       } // if (!DisablePNotP)
289 
290     } // Instruction
291   } // Basic Block
292   return true;
293 }
294 
createHexagonPeephole()295 FunctionPass *llvm::createHexagonPeephole() {
296   return new HexagonPeephole();
297 }
298