xref: /aosp_15_r20/external/llvm/lib/CodeGen/PeepholeOptimizer.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // Perform peephole optimizations on the machine code:
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker // - Optimize Extensions
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker //     Optimization of sign / zero extension instructions. It may be extended to
15*9880d681SAndroid Build Coastguard Worker //     handle other instructions with similar properties.
16*9880d681SAndroid Build Coastguard Worker //
17*9880d681SAndroid Build Coastguard Worker //     On some targets, some instructions, e.g. X86 sign / zero extension, may
18*9880d681SAndroid Build Coastguard Worker //     leave the source value in the lower part of the result. This optimization
19*9880d681SAndroid Build Coastguard Worker //     will replace some uses of the pre-extension value with uses of the
20*9880d681SAndroid Build Coastguard Worker //     sub-register of the results.
21*9880d681SAndroid Build Coastguard Worker //
22*9880d681SAndroid Build Coastguard Worker // - Optimize Comparisons
23*9880d681SAndroid Build Coastguard Worker //
24*9880d681SAndroid Build Coastguard Worker //     Optimization of comparison instructions. For instance, in this code:
25*9880d681SAndroid Build Coastguard Worker //
26*9880d681SAndroid Build Coastguard Worker //       sub r1, 1
27*9880d681SAndroid Build Coastguard Worker //       cmp r1, 0
28*9880d681SAndroid Build Coastguard Worker //       bz  L1
29*9880d681SAndroid Build Coastguard Worker //
30*9880d681SAndroid Build Coastguard Worker //     If the "sub" instruction all ready sets (or could be modified to set) the
31*9880d681SAndroid Build Coastguard Worker //     same flag that the "cmp" instruction sets and that "bz" uses, then we can
32*9880d681SAndroid Build Coastguard Worker //     eliminate the "cmp" instruction.
33*9880d681SAndroid Build Coastguard Worker //
34*9880d681SAndroid Build Coastguard Worker //     Another instance, in this code:
35*9880d681SAndroid Build Coastguard Worker //
36*9880d681SAndroid Build Coastguard Worker //       sub r1, r3 | sub r1, imm
37*9880d681SAndroid Build Coastguard Worker //       cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38*9880d681SAndroid Build Coastguard Worker //       bge L1
39*9880d681SAndroid Build Coastguard Worker //
40*9880d681SAndroid Build Coastguard Worker //     If the branch instruction can use flag from "sub", then we can replace
41*9880d681SAndroid Build Coastguard Worker //     "sub" with "subs" and eliminate the "cmp" instruction.
42*9880d681SAndroid Build Coastguard Worker //
43*9880d681SAndroid Build Coastguard Worker // - Optimize Loads:
44*9880d681SAndroid Build Coastguard Worker //
45*9880d681SAndroid Build Coastguard Worker //     Loads that can be folded into a later instruction. A load is foldable
46*9880d681SAndroid Build Coastguard Worker //     if it loads to virtual registers and the virtual register defined has
47*9880d681SAndroid Build Coastguard Worker //     a single use.
48*9880d681SAndroid Build Coastguard Worker //
49*9880d681SAndroid Build Coastguard Worker // - Optimize Copies and Bitcast (more generally, target specific copies):
50*9880d681SAndroid Build Coastguard Worker //
51*9880d681SAndroid Build Coastguard Worker //     Rewrite copies and bitcasts to avoid cross register bank copies
52*9880d681SAndroid Build Coastguard Worker //     when possible.
53*9880d681SAndroid Build Coastguard Worker //     E.g., Consider the following example, where capital and lower
54*9880d681SAndroid Build Coastguard Worker //     letters denote different register file:
55*9880d681SAndroid Build Coastguard Worker //     b = copy A <-- cross-bank copy
56*9880d681SAndroid Build Coastguard Worker //     C = copy b <-- cross-bank copy
57*9880d681SAndroid Build Coastguard Worker //   =>
58*9880d681SAndroid Build Coastguard Worker //     b = copy A <-- cross-bank copy
59*9880d681SAndroid Build Coastguard Worker //     C = copy A <-- same-bank copy
60*9880d681SAndroid Build Coastguard Worker //
61*9880d681SAndroid Build Coastguard Worker //     E.g., for bitcast:
62*9880d681SAndroid Build Coastguard Worker //     b = bitcast A <-- cross-bank copy
63*9880d681SAndroid Build Coastguard Worker //     C = bitcast b <-- cross-bank copy
64*9880d681SAndroid Build Coastguard Worker //   =>
65*9880d681SAndroid Build Coastguard Worker //     b = bitcast A <-- cross-bank copy
66*9880d681SAndroid Build Coastguard Worker //     C = copy A    <-- same-bank copy
67*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
68*9880d681SAndroid Build Coastguard Worker 
69*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/Passes.h"
70*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
71*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
72*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
73*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
74*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineDominators.h"
75*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineInstrBuilder.h"
76*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineRegisterInfo.h"
77*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
78*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
79*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
80*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetInstrInfo.h"
81*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetRegisterInfo.h"
82*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetSubtargetInfo.h"
83*9880d681SAndroid Build Coastguard Worker #include <utility>
84*9880d681SAndroid Build Coastguard Worker using namespace llvm;
85*9880d681SAndroid Build Coastguard Worker 
86*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "peephole-opt"
87*9880d681SAndroid Build Coastguard Worker 
88*9880d681SAndroid Build Coastguard Worker // Optimize Extensions
89*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
90*9880d681SAndroid Build Coastguard Worker Aggressive("aggressive-ext-opt", cl::Hidden,
91*9880d681SAndroid Build Coastguard Worker            cl::desc("Aggressive extension optimization"));
92*9880d681SAndroid Build Coastguard Worker 
93*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
94*9880d681SAndroid Build Coastguard Worker DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95*9880d681SAndroid Build Coastguard Worker                 cl::desc("Disable the peephole optimizer"));
96*9880d681SAndroid Build Coastguard Worker 
97*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
98*9880d681SAndroid Build Coastguard Worker DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
99*9880d681SAndroid Build Coastguard Worker                   cl::desc("Disable advanced copy optimization"));
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableNAPhysCopyOpt(
102*9880d681SAndroid Build Coastguard Worker     "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
103*9880d681SAndroid Build Coastguard Worker     cl::desc("Disable non-allocatable physical register copy optimization"));
104*9880d681SAndroid Build Coastguard Worker 
105*9880d681SAndroid Build Coastguard Worker // Limit the number of PHI instructions to process
106*9880d681SAndroid Build Coastguard Worker // in PeepholeOptimizer::getNextSource.
107*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> RewritePHILimit(
108*9880d681SAndroid Build Coastguard Worker     "rewrite-phi-limit", cl::Hidden, cl::init(10),
109*9880d681SAndroid Build Coastguard Worker     cl::desc("Limit the length of PHI chains to lookup"));
110*9880d681SAndroid Build Coastguard Worker 
111*9880d681SAndroid Build Coastguard Worker STATISTIC(NumReuse,      "Number of extension results reused");
112*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCmps,       "Number of compares eliminated");
113*9880d681SAndroid Build Coastguard Worker STATISTIC(NumImmFold,    "Number of move immediate folded");
114*9880d681SAndroid Build Coastguard Worker STATISTIC(NumLoadFold,   "Number of loads folded");
115*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSelects,    "Number of selects optimized");
116*9880d681SAndroid Build Coastguard Worker STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
117*9880d681SAndroid Build Coastguard Worker STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
118*9880d681SAndroid Build Coastguard Worker STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
119*9880d681SAndroid Build Coastguard Worker 
120*9880d681SAndroid Build Coastguard Worker namespace {
121*9880d681SAndroid Build Coastguard Worker   class ValueTrackerResult;
122*9880d681SAndroid Build Coastguard Worker 
123*9880d681SAndroid Build Coastguard Worker   class PeepholeOptimizer : public MachineFunctionPass {
124*9880d681SAndroid Build Coastguard Worker     const TargetInstrInfo *TII;
125*9880d681SAndroid Build Coastguard Worker     const TargetRegisterInfo *TRI;
126*9880d681SAndroid Build Coastguard Worker     MachineRegisterInfo   *MRI;
127*9880d681SAndroid Build Coastguard Worker     MachineDominatorTree  *DT;  // Machine dominator tree
128*9880d681SAndroid Build Coastguard Worker 
129*9880d681SAndroid Build Coastguard Worker   public:
130*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass identification
PeepholeOptimizer()131*9880d681SAndroid Build Coastguard Worker     PeepholeOptimizer() : MachineFunctionPass(ID) {
132*9880d681SAndroid Build Coastguard Worker       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
133*9880d681SAndroid Build Coastguard Worker     }
134*9880d681SAndroid Build Coastguard Worker 
135*9880d681SAndroid Build Coastguard Worker     bool runOnMachineFunction(MachineFunction &MF) override;
136*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const137*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
138*9880d681SAndroid Build Coastguard Worker       AU.setPreservesCFG();
139*9880d681SAndroid Build Coastguard Worker       MachineFunctionPass::getAnalysisUsage(AU);
140*9880d681SAndroid Build Coastguard Worker       if (Aggressive) {
141*9880d681SAndroid Build Coastguard Worker         AU.addRequired<MachineDominatorTree>();
142*9880d681SAndroid Build Coastguard Worker         AU.addPreserved<MachineDominatorTree>();
143*9880d681SAndroid Build Coastguard Worker       }
144*9880d681SAndroid Build Coastguard Worker     }
145*9880d681SAndroid Build Coastguard Worker 
146*9880d681SAndroid Build Coastguard Worker     /// \brief Track Def -> Use info used for rewriting copies.
147*9880d681SAndroid Build Coastguard Worker     typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
148*9880d681SAndroid Build Coastguard Worker         RewriteMapTy;
149*9880d681SAndroid Build Coastguard Worker 
150*9880d681SAndroid Build Coastguard Worker   private:
151*9880d681SAndroid Build Coastguard Worker     bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
152*9880d681SAndroid Build Coastguard Worker     bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
153*9880d681SAndroid Build Coastguard Worker                           SmallPtrSetImpl<MachineInstr*> &LocalMIs);
154*9880d681SAndroid Build Coastguard Worker     bool optimizeSelect(MachineInstr *MI,
155*9880d681SAndroid Build Coastguard Worker                         SmallPtrSetImpl<MachineInstr *> &LocalMIs);
156*9880d681SAndroid Build Coastguard Worker     bool optimizeCondBranch(MachineInstr *MI);
157*9880d681SAndroid Build Coastguard Worker     bool optimizeCoalescableCopy(MachineInstr *MI);
158*9880d681SAndroid Build Coastguard Worker     bool optimizeUncoalescableCopy(MachineInstr *MI,
159*9880d681SAndroid Build Coastguard Worker                                    SmallPtrSetImpl<MachineInstr *> &LocalMIs);
160*9880d681SAndroid Build Coastguard Worker     bool findNextSource(unsigned Reg, unsigned SubReg,
161*9880d681SAndroid Build Coastguard Worker                         RewriteMapTy &RewriteMap);
162*9880d681SAndroid Build Coastguard Worker     bool isMoveImmediate(MachineInstr *MI,
163*9880d681SAndroid Build Coastguard Worker                          SmallSet<unsigned, 4> &ImmDefRegs,
164*9880d681SAndroid Build Coastguard Worker                          DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
165*9880d681SAndroid Build Coastguard Worker     bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
166*9880d681SAndroid Build Coastguard Worker                        SmallSet<unsigned, 4> &ImmDefRegs,
167*9880d681SAndroid Build Coastguard Worker                        DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
168*9880d681SAndroid Build Coastguard Worker 
169*9880d681SAndroid Build Coastguard Worker     /// \brief If copy instruction \p MI is a virtual register copy, track it in
170*9880d681SAndroid Build Coastguard Worker     /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
171*9880d681SAndroid Build Coastguard Worker     /// previously seen as a copy, replace the uses of this copy with the
172*9880d681SAndroid Build Coastguard Worker     /// previously seen copy's destination register.
173*9880d681SAndroid Build Coastguard Worker     bool foldRedundantCopy(MachineInstr *MI,
174*9880d681SAndroid Build Coastguard Worker                            SmallSet<unsigned, 4> &CopySrcRegs,
175*9880d681SAndroid Build Coastguard Worker                            DenseMap<unsigned, MachineInstr *> &CopyMIs);
176*9880d681SAndroid Build Coastguard Worker 
177*9880d681SAndroid Build Coastguard Worker     /// \brief Is the register \p Reg a non-allocatable physical register?
178*9880d681SAndroid Build Coastguard Worker     bool isNAPhysCopy(unsigned Reg);
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker     /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
181*9880d681SAndroid Build Coastguard Worker     /// register copy, track it in the \p NAPhysToVirtMIs map. If this
182*9880d681SAndroid Build Coastguard Worker     /// non-allocatable physical register was previously copied to a virtual
183*9880d681SAndroid Build Coastguard Worker     /// registered and hasn't been clobbered, the virt->phys copy can be
184*9880d681SAndroid Build Coastguard Worker     /// deleted.
185*9880d681SAndroid Build Coastguard Worker     bool foldRedundantNAPhysCopy(
186*9880d681SAndroid Build Coastguard Worker         MachineInstr *MI,
187*9880d681SAndroid Build Coastguard Worker         DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
188*9880d681SAndroid Build Coastguard Worker 
189*9880d681SAndroid Build Coastguard Worker     bool isLoadFoldable(MachineInstr *MI,
190*9880d681SAndroid Build Coastguard Worker                         SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
191*9880d681SAndroid Build Coastguard Worker 
192*9880d681SAndroid Build Coastguard Worker     /// \brief Check whether \p MI is understood by the register coalescer
193*9880d681SAndroid Build Coastguard Worker     /// but may require some rewriting.
isCoalescableCopy(const MachineInstr & MI)194*9880d681SAndroid Build Coastguard Worker     bool isCoalescableCopy(const MachineInstr &MI) {
195*9880d681SAndroid Build Coastguard Worker       // SubregToRegs are not interesting, because they are already register
196*9880d681SAndroid Build Coastguard Worker       // coalescer friendly.
197*9880d681SAndroid Build Coastguard Worker       return MI.isCopy() || (!DisableAdvCopyOpt &&
198*9880d681SAndroid Build Coastguard Worker                              (MI.isRegSequence() || MI.isInsertSubreg() ||
199*9880d681SAndroid Build Coastguard Worker                               MI.isExtractSubreg()));
200*9880d681SAndroid Build Coastguard Worker     }
201*9880d681SAndroid Build Coastguard Worker 
202*9880d681SAndroid Build Coastguard Worker     /// \brief Check whether \p MI is a copy like instruction that is
203*9880d681SAndroid Build Coastguard Worker     /// not recognized by the register coalescer.
isUncoalescableCopy(const MachineInstr & MI)204*9880d681SAndroid Build Coastguard Worker     bool isUncoalescableCopy(const MachineInstr &MI) {
205*9880d681SAndroid Build Coastguard Worker       return MI.isBitcast() ||
206*9880d681SAndroid Build Coastguard Worker              (!DisableAdvCopyOpt &&
207*9880d681SAndroid Build Coastguard Worker               (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
208*9880d681SAndroid Build Coastguard Worker                MI.isExtractSubregLike()));
209*9880d681SAndroid Build Coastguard Worker     }
210*9880d681SAndroid Build Coastguard Worker   };
211*9880d681SAndroid Build Coastguard Worker 
212*9880d681SAndroid Build Coastguard Worker   /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
213*9880d681SAndroid Build Coastguard Worker   /// returned sources for a given search and the instructions where the sources
214*9880d681SAndroid Build Coastguard Worker   /// were tracked from.
215*9880d681SAndroid Build Coastguard Worker   class ValueTrackerResult {
216*9880d681SAndroid Build Coastguard Worker   private:
217*9880d681SAndroid Build Coastguard Worker     /// Track all sources found by one ValueTracker query.
218*9880d681SAndroid Build Coastguard Worker     SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker     /// Instruction using the sources in 'RegSrcs'.
221*9880d681SAndroid Build Coastguard Worker     const MachineInstr *Inst;
222*9880d681SAndroid Build Coastguard Worker 
223*9880d681SAndroid Build Coastguard Worker   public:
ValueTrackerResult()224*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult() : Inst(nullptr) {}
ValueTrackerResult(unsigned Reg,unsigned SubReg)225*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
226*9880d681SAndroid Build Coastguard Worker       addSource(Reg, SubReg);
227*9880d681SAndroid Build Coastguard Worker     }
228*9880d681SAndroid Build Coastguard Worker 
isValid() const229*9880d681SAndroid Build Coastguard Worker     bool isValid() const { return getNumSources() > 0; }
230*9880d681SAndroid Build Coastguard Worker 
setInst(const MachineInstr * I)231*9880d681SAndroid Build Coastguard Worker     void setInst(const MachineInstr *I) { Inst = I; }
getInst() const232*9880d681SAndroid Build Coastguard Worker     const MachineInstr *getInst() const { return Inst; }
233*9880d681SAndroid Build Coastguard Worker 
clear()234*9880d681SAndroid Build Coastguard Worker     void clear() {
235*9880d681SAndroid Build Coastguard Worker       RegSrcs.clear();
236*9880d681SAndroid Build Coastguard Worker       Inst = nullptr;
237*9880d681SAndroid Build Coastguard Worker     }
238*9880d681SAndroid Build Coastguard Worker 
addSource(unsigned SrcReg,unsigned SrcSubReg)239*9880d681SAndroid Build Coastguard Worker     void addSource(unsigned SrcReg, unsigned SrcSubReg) {
240*9880d681SAndroid Build Coastguard Worker       RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
241*9880d681SAndroid Build Coastguard Worker     }
242*9880d681SAndroid Build Coastguard Worker 
setSource(int Idx,unsigned SrcReg,unsigned SrcSubReg)243*9880d681SAndroid Build Coastguard Worker     void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
244*9880d681SAndroid Build Coastguard Worker       assert(Idx < getNumSources() && "Reg pair source out of index");
245*9880d681SAndroid Build Coastguard Worker       RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
246*9880d681SAndroid Build Coastguard Worker     }
247*9880d681SAndroid Build Coastguard Worker 
getNumSources() const248*9880d681SAndroid Build Coastguard Worker     int getNumSources() const { return RegSrcs.size(); }
249*9880d681SAndroid Build Coastguard Worker 
getSrcReg(int Idx) const250*9880d681SAndroid Build Coastguard Worker     unsigned getSrcReg(int Idx) const {
251*9880d681SAndroid Build Coastguard Worker       assert(Idx < getNumSources() && "Reg source out of index");
252*9880d681SAndroid Build Coastguard Worker       return RegSrcs[Idx].Reg;
253*9880d681SAndroid Build Coastguard Worker     }
254*9880d681SAndroid Build Coastguard Worker 
getSrcSubReg(int Idx) const255*9880d681SAndroid Build Coastguard Worker     unsigned getSrcSubReg(int Idx) const {
256*9880d681SAndroid Build Coastguard Worker       assert(Idx < getNumSources() && "SubReg source out of index");
257*9880d681SAndroid Build Coastguard Worker       return RegSrcs[Idx].SubReg;
258*9880d681SAndroid Build Coastguard Worker     }
259*9880d681SAndroid Build Coastguard Worker 
operator ==(const ValueTrackerResult & Other)260*9880d681SAndroid Build Coastguard Worker     bool operator==(const ValueTrackerResult &Other) {
261*9880d681SAndroid Build Coastguard Worker       if (Other.getInst() != getInst())
262*9880d681SAndroid Build Coastguard Worker         return false;
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker       if (Other.getNumSources() != getNumSources())
265*9880d681SAndroid Build Coastguard Worker         return false;
266*9880d681SAndroid Build Coastguard Worker 
267*9880d681SAndroid Build Coastguard Worker       for (int i = 0, e = Other.getNumSources(); i != e; ++i)
268*9880d681SAndroid Build Coastguard Worker         if (Other.getSrcReg(i) != getSrcReg(i) ||
269*9880d681SAndroid Build Coastguard Worker             Other.getSrcSubReg(i) != getSrcSubReg(i))
270*9880d681SAndroid Build Coastguard Worker           return false;
271*9880d681SAndroid Build Coastguard Worker       return true;
272*9880d681SAndroid Build Coastguard Worker     }
273*9880d681SAndroid Build Coastguard Worker   };
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker   /// \brief Helper class to track the possible sources of a value defined by
276*9880d681SAndroid Build Coastguard Worker   /// a (chain of) copy related instructions.
277*9880d681SAndroid Build Coastguard Worker   /// Given a definition (instruction and definition index), this class
278*9880d681SAndroid Build Coastguard Worker   /// follows the use-def chain to find successive suitable sources.
279*9880d681SAndroid Build Coastguard Worker   /// The given source can be used to rewrite the definition into
280*9880d681SAndroid Build Coastguard Worker   /// def = COPY src.
281*9880d681SAndroid Build Coastguard Worker   ///
282*9880d681SAndroid Build Coastguard Worker   /// For instance, let us consider the following snippet:
283*9880d681SAndroid Build Coastguard Worker   /// v0 =
284*9880d681SAndroid Build Coastguard Worker   /// v2 = INSERT_SUBREG v1, v0, sub0
285*9880d681SAndroid Build Coastguard Worker   /// def = COPY v2.sub0
286*9880d681SAndroid Build Coastguard Worker   ///
287*9880d681SAndroid Build Coastguard Worker   /// Using a ValueTracker for def = COPY v2.sub0 will give the following
288*9880d681SAndroid Build Coastguard Worker   /// suitable sources:
289*9880d681SAndroid Build Coastguard Worker   /// v2.sub0 and v0.
290*9880d681SAndroid Build Coastguard Worker   /// Then, def can be rewritten into def = COPY v0.
291*9880d681SAndroid Build Coastguard Worker   class ValueTracker {
292*9880d681SAndroid Build Coastguard Worker   private:
293*9880d681SAndroid Build Coastguard Worker     /// The current point into the use-def chain.
294*9880d681SAndroid Build Coastguard Worker     const MachineInstr *Def;
295*9880d681SAndroid Build Coastguard Worker     /// The index of the definition in Def.
296*9880d681SAndroid Build Coastguard Worker     unsigned DefIdx;
297*9880d681SAndroid Build Coastguard Worker     /// The sub register index of the definition.
298*9880d681SAndroid Build Coastguard Worker     unsigned DefSubReg;
299*9880d681SAndroid Build Coastguard Worker     /// The register where the value can be found.
300*9880d681SAndroid Build Coastguard Worker     unsigned Reg;
301*9880d681SAndroid Build Coastguard Worker     /// Specifiy whether or not the value tracking looks through
302*9880d681SAndroid Build Coastguard Worker     /// complex instructions. When this is false, the value tracker
303*9880d681SAndroid Build Coastguard Worker     /// bails on everything that is not a copy or a bitcast.
304*9880d681SAndroid Build Coastguard Worker     ///
305*9880d681SAndroid Build Coastguard Worker     /// Note: This could have been implemented as a specialized version of
306*9880d681SAndroid Build Coastguard Worker     /// the ValueTracker class but that would have complicated the code of
307*9880d681SAndroid Build Coastguard Worker     /// the users of this class.
308*9880d681SAndroid Build Coastguard Worker     bool UseAdvancedTracking;
309*9880d681SAndroid Build Coastguard Worker     /// MachineRegisterInfo used to perform tracking.
310*9880d681SAndroid Build Coastguard Worker     const MachineRegisterInfo &MRI;
311*9880d681SAndroid Build Coastguard Worker     /// Optional TargetInstrInfo used to perform some complex
312*9880d681SAndroid Build Coastguard Worker     /// tracking.
313*9880d681SAndroid Build Coastguard Worker     const TargetInstrInfo *TII;
314*9880d681SAndroid Build Coastguard Worker 
315*9880d681SAndroid Build Coastguard Worker     /// \brief Dispatcher to the right underlying implementation of
316*9880d681SAndroid Build Coastguard Worker     /// getNextSource.
317*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceImpl();
318*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for Copy instructions.
319*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromCopy();
320*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for Bitcast instructions.
321*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromBitcast();
322*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for RegSequence
323*9880d681SAndroid Build Coastguard Worker     /// instructions.
324*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromRegSequence();
325*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for InsertSubreg
326*9880d681SAndroid Build Coastguard Worker     /// instructions.
327*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromInsertSubreg();
328*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for ExtractSubreg
329*9880d681SAndroid Build Coastguard Worker     /// instructions.
330*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromExtractSubreg();
331*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for SubregToReg
332*9880d681SAndroid Build Coastguard Worker     /// instructions.
333*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromSubregToReg();
334*9880d681SAndroid Build Coastguard Worker     /// \brief Specialized version of getNextSource for PHI instructions.
335*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSourceFromPHI();
336*9880d681SAndroid Build Coastguard Worker 
337*9880d681SAndroid Build Coastguard Worker   public:
338*9880d681SAndroid Build Coastguard Worker     /// \brief Create a ValueTracker instance for the value defined by \p Reg.
339*9880d681SAndroid Build Coastguard Worker     /// \p DefSubReg represents the sub register index the value tracker will
340*9880d681SAndroid Build Coastguard Worker     /// track. It does not need to match the sub register index used in the
341*9880d681SAndroid Build Coastguard Worker     /// definition of \p Reg.
342*9880d681SAndroid Build Coastguard Worker     /// \p UseAdvancedTracking specifies whether or not the value tracker looks
343*9880d681SAndroid Build Coastguard Worker     /// through complex instructions. By default (false), it handles only copy
344*9880d681SAndroid Build Coastguard Worker     /// and bitcast instructions.
345*9880d681SAndroid Build Coastguard Worker     /// If \p Reg is a physical register, a value tracker constructed with
346*9880d681SAndroid Build Coastguard Worker     /// this constructor will not find any alternative source.
347*9880d681SAndroid Build Coastguard Worker     /// Indeed, when \p Reg is a physical register that constructor does not
348*9880d681SAndroid Build Coastguard Worker     /// know which definition of \p Reg it should track.
349*9880d681SAndroid Build Coastguard Worker     /// Use the next constructor to track a physical register.
ValueTracker(unsigned Reg,unsigned DefSubReg,const MachineRegisterInfo & MRI,bool UseAdvancedTracking=false,const TargetInstrInfo * TII=nullptr)350*9880d681SAndroid Build Coastguard Worker     ValueTracker(unsigned Reg, unsigned DefSubReg,
351*9880d681SAndroid Build Coastguard Worker                  const MachineRegisterInfo &MRI,
352*9880d681SAndroid Build Coastguard Worker                  bool UseAdvancedTracking = false,
353*9880d681SAndroid Build Coastguard Worker                  const TargetInstrInfo *TII = nullptr)
354*9880d681SAndroid Build Coastguard Worker         : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
355*9880d681SAndroid Build Coastguard Worker           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
356*9880d681SAndroid Build Coastguard Worker       if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
357*9880d681SAndroid Build Coastguard Worker         Def = MRI.getVRegDef(Reg);
358*9880d681SAndroid Build Coastguard Worker         DefIdx = MRI.def_begin(Reg).getOperandNo();
359*9880d681SAndroid Build Coastguard Worker       }
360*9880d681SAndroid Build Coastguard Worker     }
361*9880d681SAndroid Build Coastguard Worker 
362*9880d681SAndroid Build Coastguard Worker     /// \brief Create a ValueTracker instance for the value defined by
363*9880d681SAndroid Build Coastguard Worker     /// the pair \p MI, \p DefIdx.
364*9880d681SAndroid Build Coastguard Worker     /// Unlike the other constructor, the value tracker produced by this one
365*9880d681SAndroid Build Coastguard Worker     /// may be able to find a new source when the definition is a physical
366*9880d681SAndroid Build Coastguard Worker     /// register.
367*9880d681SAndroid Build Coastguard Worker     /// This could be useful to rewrite target specific instructions into
368*9880d681SAndroid Build Coastguard Worker     /// generic copy instructions.
ValueTracker(const MachineInstr & MI,unsigned DefIdx,unsigned DefSubReg,const MachineRegisterInfo & MRI,bool UseAdvancedTracking=false,const TargetInstrInfo * TII=nullptr)369*9880d681SAndroid Build Coastguard Worker     ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
370*9880d681SAndroid Build Coastguard Worker                  const MachineRegisterInfo &MRI,
371*9880d681SAndroid Build Coastguard Worker                  bool UseAdvancedTracking = false,
372*9880d681SAndroid Build Coastguard Worker                  const TargetInstrInfo *TII = nullptr)
373*9880d681SAndroid Build Coastguard Worker         : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
374*9880d681SAndroid Build Coastguard Worker           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
375*9880d681SAndroid Build Coastguard Worker       assert(DefIdx < Def->getDesc().getNumDefs() &&
376*9880d681SAndroid Build Coastguard Worker              Def->getOperand(DefIdx).isReg() && "Invalid definition");
377*9880d681SAndroid Build Coastguard Worker       Reg = Def->getOperand(DefIdx).getReg();
378*9880d681SAndroid Build Coastguard Worker     }
379*9880d681SAndroid Build Coastguard Worker 
380*9880d681SAndroid Build Coastguard Worker     /// \brief Following the use-def chain, get the next available source
381*9880d681SAndroid Build Coastguard Worker     /// for the tracked value.
382*9880d681SAndroid Build Coastguard Worker     /// \return A ValueTrackerResult containing a set of registers
383*9880d681SAndroid Build Coastguard Worker     /// and sub registers with tracked values. A ValueTrackerResult with
384*9880d681SAndroid Build Coastguard Worker     /// an empty set of registers means no source was found.
385*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult getNextSource();
386*9880d681SAndroid Build Coastguard Worker 
387*9880d681SAndroid Build Coastguard Worker     /// \brief Get the last register where the initial value can be found.
388*9880d681SAndroid Build Coastguard Worker     /// Initially this is the register of the definition.
389*9880d681SAndroid Build Coastguard Worker     /// Then, after each successful call to getNextSource, this is the
390*9880d681SAndroid Build Coastguard Worker     /// register of the last source.
getReg() const391*9880d681SAndroid Build Coastguard Worker     unsigned getReg() const { return Reg; }
392*9880d681SAndroid Build Coastguard Worker   };
393*9880d681SAndroid Build Coastguard Worker }
394*9880d681SAndroid Build Coastguard Worker 
395*9880d681SAndroid Build Coastguard Worker char PeepholeOptimizer::ID = 0;
396*9880d681SAndroid Build Coastguard Worker char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
397*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
398*9880d681SAndroid Build Coastguard Worker                 "Peephole Optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)399*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
400*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
401*9880d681SAndroid Build Coastguard Worker                 "Peephole Optimizations", false, false)
402*9880d681SAndroid Build Coastguard Worker 
403*9880d681SAndroid Build Coastguard Worker /// If instruction is a copy-like instruction, i.e. it reads a single register
404*9880d681SAndroid Build Coastguard Worker /// and writes a single register and it does not modify the source, and if the
405*9880d681SAndroid Build Coastguard Worker /// source value is preserved as a sub-register of the result, then replace all
406*9880d681SAndroid Build Coastguard Worker /// reachable uses of the source with the subreg of the result.
407*9880d681SAndroid Build Coastguard Worker ///
408*9880d681SAndroid Build Coastguard Worker /// Do not generate an EXTRACT that is used only in a debug use, as this changes
409*9880d681SAndroid Build Coastguard Worker /// the code. Since this code does not currently share EXTRACTs, just ignore all
410*9880d681SAndroid Build Coastguard Worker /// debug uses.
411*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::
412*9880d681SAndroid Build Coastguard Worker optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
413*9880d681SAndroid Build Coastguard Worker                  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
414*9880d681SAndroid Build Coastguard Worker   unsigned SrcReg, DstReg, SubIdx;
415*9880d681SAndroid Build Coastguard Worker   if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
416*9880d681SAndroid Build Coastguard Worker     return false;
417*9880d681SAndroid Build Coastguard Worker 
418*9880d681SAndroid Build Coastguard Worker   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
419*9880d681SAndroid Build Coastguard Worker       TargetRegisterInfo::isPhysicalRegister(SrcReg))
420*9880d681SAndroid Build Coastguard Worker     return false;
421*9880d681SAndroid Build Coastguard Worker 
422*9880d681SAndroid Build Coastguard Worker   if (MRI->hasOneNonDBGUse(SrcReg))
423*9880d681SAndroid Build Coastguard Worker     // No other uses.
424*9880d681SAndroid Build Coastguard Worker     return false;
425*9880d681SAndroid Build Coastguard Worker 
426*9880d681SAndroid Build Coastguard Worker   // Ensure DstReg can get a register class that actually supports
427*9880d681SAndroid Build Coastguard Worker   // sub-registers. Don't change the class until we commit.
428*9880d681SAndroid Build Coastguard Worker   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
429*9880d681SAndroid Build Coastguard Worker   DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
430*9880d681SAndroid Build Coastguard Worker   if (!DstRC)
431*9880d681SAndroid Build Coastguard Worker     return false;
432*9880d681SAndroid Build Coastguard Worker 
433*9880d681SAndroid Build Coastguard Worker   // The ext instr may be operating on a sub-register of SrcReg as well.
434*9880d681SAndroid Build Coastguard Worker   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
435*9880d681SAndroid Build Coastguard Worker   // register.
436*9880d681SAndroid Build Coastguard Worker   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
437*9880d681SAndroid Build Coastguard Worker   // SrcReg:SubIdx should be replaced.
438*9880d681SAndroid Build Coastguard Worker   bool UseSrcSubIdx =
439*9880d681SAndroid Build Coastguard Worker       TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
440*9880d681SAndroid Build Coastguard Worker 
441*9880d681SAndroid Build Coastguard Worker   // The source has other uses. See if we can replace the other uses with use of
442*9880d681SAndroid Build Coastguard Worker   // the result of the extension.
443*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
444*9880d681SAndroid Build Coastguard Worker   for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
445*9880d681SAndroid Build Coastguard Worker     ReachedBBs.insert(UI.getParent());
446*9880d681SAndroid Build Coastguard Worker 
447*9880d681SAndroid Build Coastguard Worker   // Uses that are in the same BB of uses of the result of the instruction.
448*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand*, 8> Uses;
449*9880d681SAndroid Build Coastguard Worker 
450*9880d681SAndroid Build Coastguard Worker   // Uses that the result of the instruction can reach.
451*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand*, 8> ExtendedUses;
452*9880d681SAndroid Build Coastguard Worker 
453*9880d681SAndroid Build Coastguard Worker   bool ExtendLife = true;
454*9880d681SAndroid Build Coastguard Worker   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
455*9880d681SAndroid Build Coastguard Worker     MachineInstr *UseMI = UseMO.getParent();
456*9880d681SAndroid Build Coastguard Worker     if (UseMI == MI)
457*9880d681SAndroid Build Coastguard Worker       continue;
458*9880d681SAndroid Build Coastguard Worker 
459*9880d681SAndroid Build Coastguard Worker     if (UseMI->isPHI()) {
460*9880d681SAndroid Build Coastguard Worker       ExtendLife = false;
461*9880d681SAndroid Build Coastguard Worker       continue;
462*9880d681SAndroid Build Coastguard Worker     }
463*9880d681SAndroid Build Coastguard Worker 
464*9880d681SAndroid Build Coastguard Worker     // Only accept uses of SrcReg:SubIdx.
465*9880d681SAndroid Build Coastguard Worker     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
466*9880d681SAndroid Build Coastguard Worker       continue;
467*9880d681SAndroid Build Coastguard Worker 
468*9880d681SAndroid Build Coastguard Worker     // It's an error to translate this:
469*9880d681SAndroid Build Coastguard Worker     //
470*9880d681SAndroid Build Coastguard Worker     //    %reg1025 = <sext> %reg1024
471*9880d681SAndroid Build Coastguard Worker     //     ...
472*9880d681SAndroid Build Coastguard Worker     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
473*9880d681SAndroid Build Coastguard Worker     //
474*9880d681SAndroid Build Coastguard Worker     // into this:
475*9880d681SAndroid Build Coastguard Worker     //
476*9880d681SAndroid Build Coastguard Worker     //    %reg1025 = <sext> %reg1024
477*9880d681SAndroid Build Coastguard Worker     //     ...
478*9880d681SAndroid Build Coastguard Worker     //    %reg1027 = COPY %reg1025:4
479*9880d681SAndroid Build Coastguard Worker     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
480*9880d681SAndroid Build Coastguard Worker     //
481*9880d681SAndroid Build Coastguard Worker     // The problem here is that SUBREG_TO_REG is there to assert that an
482*9880d681SAndroid Build Coastguard Worker     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
483*9880d681SAndroid Build Coastguard Worker     // the COPY here, it will give us the value after the <sext>, not the
484*9880d681SAndroid Build Coastguard Worker     // original value of %reg1024 before <sext>.
485*9880d681SAndroid Build Coastguard Worker     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
486*9880d681SAndroid Build Coastguard Worker       continue;
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *UseMBB = UseMI->getParent();
489*9880d681SAndroid Build Coastguard Worker     if (UseMBB == MBB) {
490*9880d681SAndroid Build Coastguard Worker       // Local uses that come after the extension.
491*9880d681SAndroid Build Coastguard Worker       if (!LocalMIs.count(UseMI))
492*9880d681SAndroid Build Coastguard Worker         Uses.push_back(&UseMO);
493*9880d681SAndroid Build Coastguard Worker     } else if (ReachedBBs.count(UseMBB)) {
494*9880d681SAndroid Build Coastguard Worker       // Non-local uses where the result of the extension is used. Always
495*9880d681SAndroid Build Coastguard Worker       // replace these unless it's a PHI.
496*9880d681SAndroid Build Coastguard Worker       Uses.push_back(&UseMO);
497*9880d681SAndroid Build Coastguard Worker     } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
498*9880d681SAndroid Build Coastguard Worker       // We may want to extend the live range of the extension result in order
499*9880d681SAndroid Build Coastguard Worker       // to replace these uses.
500*9880d681SAndroid Build Coastguard Worker       ExtendedUses.push_back(&UseMO);
501*9880d681SAndroid Build Coastguard Worker     } else {
502*9880d681SAndroid Build Coastguard Worker       // Both will be live out of the def MBB anyway. Don't extend live range of
503*9880d681SAndroid Build Coastguard Worker       // the extension result.
504*9880d681SAndroid Build Coastguard Worker       ExtendLife = false;
505*9880d681SAndroid Build Coastguard Worker       break;
506*9880d681SAndroid Build Coastguard Worker     }
507*9880d681SAndroid Build Coastguard Worker   }
508*9880d681SAndroid Build Coastguard Worker 
509*9880d681SAndroid Build Coastguard Worker   if (ExtendLife && !ExtendedUses.empty())
510*9880d681SAndroid Build Coastguard Worker     // Extend the liveness of the extension result.
511*9880d681SAndroid Build Coastguard Worker     Uses.append(ExtendedUses.begin(), ExtendedUses.end());
512*9880d681SAndroid Build Coastguard Worker 
513*9880d681SAndroid Build Coastguard Worker   // Now replace all uses.
514*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
515*9880d681SAndroid Build Coastguard Worker   if (!Uses.empty()) {
516*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
517*9880d681SAndroid Build Coastguard Worker 
518*9880d681SAndroid Build Coastguard Worker     // Look for PHI uses of the extended result, we don't want to extend the
519*9880d681SAndroid Build Coastguard Worker     // liveness of a PHI input. It breaks all kinds of assumptions down
520*9880d681SAndroid Build Coastguard Worker     // stream. A PHI use is expected to be the kill of its source values.
521*9880d681SAndroid Build Coastguard Worker     for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
522*9880d681SAndroid Build Coastguard Worker       if (UI.isPHI())
523*9880d681SAndroid Build Coastguard Worker         PHIBBs.insert(UI.getParent());
524*9880d681SAndroid Build Coastguard Worker 
525*9880d681SAndroid Build Coastguard Worker     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
526*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
527*9880d681SAndroid Build Coastguard Worker       MachineOperand *UseMO = Uses[i];
528*9880d681SAndroid Build Coastguard Worker       MachineInstr *UseMI = UseMO->getParent();
529*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock *UseMBB = UseMI->getParent();
530*9880d681SAndroid Build Coastguard Worker       if (PHIBBs.count(UseMBB))
531*9880d681SAndroid Build Coastguard Worker         continue;
532*9880d681SAndroid Build Coastguard Worker 
533*9880d681SAndroid Build Coastguard Worker       // About to add uses of DstReg, clear DstReg's kill flags.
534*9880d681SAndroid Build Coastguard Worker       if (!Changed) {
535*9880d681SAndroid Build Coastguard Worker         MRI->clearKillFlags(DstReg);
536*9880d681SAndroid Build Coastguard Worker         MRI->constrainRegClass(DstReg, DstRC);
537*9880d681SAndroid Build Coastguard Worker       }
538*9880d681SAndroid Build Coastguard Worker 
539*9880d681SAndroid Build Coastguard Worker       unsigned NewVR = MRI->createVirtualRegister(RC);
540*9880d681SAndroid Build Coastguard Worker       MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
541*9880d681SAndroid Build Coastguard Worker                                    TII->get(TargetOpcode::COPY), NewVR)
542*9880d681SAndroid Build Coastguard Worker         .addReg(DstReg, 0, SubIdx);
543*9880d681SAndroid Build Coastguard Worker       // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
544*9880d681SAndroid Build Coastguard Worker       if (UseSrcSubIdx) {
545*9880d681SAndroid Build Coastguard Worker         Copy->getOperand(0).setSubReg(SubIdx);
546*9880d681SAndroid Build Coastguard Worker         Copy->getOperand(0).setIsUndef();
547*9880d681SAndroid Build Coastguard Worker       }
548*9880d681SAndroid Build Coastguard Worker       UseMO->setReg(NewVR);
549*9880d681SAndroid Build Coastguard Worker       ++NumReuse;
550*9880d681SAndroid Build Coastguard Worker       Changed = true;
551*9880d681SAndroid Build Coastguard Worker     }
552*9880d681SAndroid Build Coastguard Worker   }
553*9880d681SAndroid Build Coastguard Worker 
554*9880d681SAndroid Build Coastguard Worker   return Changed;
555*9880d681SAndroid Build Coastguard Worker }
556*9880d681SAndroid Build Coastguard Worker 
557*9880d681SAndroid Build Coastguard Worker /// If the instruction is a compare and the previous instruction it's comparing
558*9880d681SAndroid Build Coastguard Worker /// against already sets (or could be modified to set) the same flag as the
559*9880d681SAndroid Build Coastguard Worker /// compare, then we can remove the comparison and use the flag from the
560*9880d681SAndroid Build Coastguard Worker /// previous instruction.
optimizeCmpInstr(MachineInstr * MI,MachineBasicBlock * MBB)561*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
562*9880d681SAndroid Build Coastguard Worker                                          MachineBasicBlock *MBB) {
563*9880d681SAndroid Build Coastguard Worker   // If this instruction is a comparison against zero and isn't comparing a
564*9880d681SAndroid Build Coastguard Worker   // physical register, we can try to optimize it.
565*9880d681SAndroid Build Coastguard Worker   unsigned SrcReg, SrcReg2;
566*9880d681SAndroid Build Coastguard Worker   int CmpMask, CmpValue;
567*9880d681SAndroid Build Coastguard Worker   if (!TII->analyzeCompare(*MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
568*9880d681SAndroid Build Coastguard Worker       TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
569*9880d681SAndroid Build Coastguard Worker       (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
570*9880d681SAndroid Build Coastguard Worker     return false;
571*9880d681SAndroid Build Coastguard Worker 
572*9880d681SAndroid Build Coastguard Worker   // Attempt to optimize the comparison instruction.
573*9880d681SAndroid Build Coastguard Worker   if (TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
574*9880d681SAndroid Build Coastguard Worker     ++NumCmps;
575*9880d681SAndroid Build Coastguard Worker     return true;
576*9880d681SAndroid Build Coastguard Worker   }
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker   return false;
579*9880d681SAndroid Build Coastguard Worker }
580*9880d681SAndroid Build Coastguard Worker 
581*9880d681SAndroid Build Coastguard Worker /// Optimize a select instruction.
optimizeSelect(MachineInstr * MI,SmallPtrSetImpl<MachineInstr * > & LocalMIs)582*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
583*9880d681SAndroid Build Coastguard Worker                             SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
584*9880d681SAndroid Build Coastguard Worker   unsigned TrueOp = 0;
585*9880d681SAndroid Build Coastguard Worker   unsigned FalseOp = 0;
586*9880d681SAndroid Build Coastguard Worker   bool Optimizable = false;
587*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> Cond;
588*9880d681SAndroid Build Coastguard Worker   if (TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable))
589*9880d681SAndroid Build Coastguard Worker     return false;
590*9880d681SAndroid Build Coastguard Worker   if (!Optimizable)
591*9880d681SAndroid Build Coastguard Worker     return false;
592*9880d681SAndroid Build Coastguard Worker   if (!TII->optimizeSelect(*MI, LocalMIs))
593*9880d681SAndroid Build Coastguard Worker     return false;
594*9880d681SAndroid Build Coastguard Worker   MI->eraseFromParent();
595*9880d681SAndroid Build Coastguard Worker   ++NumSelects;
596*9880d681SAndroid Build Coastguard Worker   return true;
597*9880d681SAndroid Build Coastguard Worker }
598*9880d681SAndroid Build Coastguard Worker 
599*9880d681SAndroid Build Coastguard Worker /// \brief Check if a simpler conditional branch can be
600*9880d681SAndroid Build Coastguard Worker // generated
optimizeCondBranch(MachineInstr * MI)601*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
602*9880d681SAndroid Build Coastguard Worker   return TII->optimizeCondBranch(*MI);
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker 
605*9880d681SAndroid Build Coastguard Worker /// \brief Try to find the next source that share the same register file
606*9880d681SAndroid Build Coastguard Worker /// for the value defined by \p Reg and \p SubReg.
607*9880d681SAndroid Build Coastguard Worker /// When true is returned, the \p RewriteMap can be used by the client to
608*9880d681SAndroid Build Coastguard Worker /// retrieve all Def -> Use along the way up to the next source. Any found
609*9880d681SAndroid Build Coastguard Worker /// Use that is not itself a key for another entry, is the next source to
610*9880d681SAndroid Build Coastguard Worker /// use. During the search for the next source, multiple sources can be found
611*9880d681SAndroid Build Coastguard Worker /// given multiple incoming sources of a PHI instruction. In this case, we
612*9880d681SAndroid Build Coastguard Worker /// look in each PHI source for the next source; all found next sources must
613*9880d681SAndroid Build Coastguard Worker /// share the same register file as \p Reg and \p SubReg. The client should
614*9880d681SAndroid Build Coastguard Worker /// then be capable to rewrite all intermediate PHIs to get the next source.
615*9880d681SAndroid Build Coastguard Worker /// \return False if no alternative sources are available. True otherwise.
findNextSource(unsigned Reg,unsigned SubReg,RewriteMapTy & RewriteMap)616*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
617*9880d681SAndroid Build Coastguard Worker                                        RewriteMapTy &RewriteMap) {
618*9880d681SAndroid Build Coastguard Worker   // Do not try to find a new source for a physical register.
619*9880d681SAndroid Build Coastguard Worker   // So far we do not have any motivating example for doing that.
620*9880d681SAndroid Build Coastguard Worker   // Thus, instead of maintaining untested code, we will revisit that if
621*9880d681SAndroid Build Coastguard Worker   // that changes at some point.
622*9880d681SAndroid Build Coastguard Worker   if (TargetRegisterInfo::isPhysicalRegister(Reg))
623*9880d681SAndroid Build Coastguard Worker     return false;
624*9880d681SAndroid Build Coastguard Worker   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
625*9880d681SAndroid Build Coastguard Worker 
626*9880d681SAndroid Build Coastguard Worker   SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
627*9880d681SAndroid Build Coastguard Worker   TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
628*9880d681SAndroid Build Coastguard Worker   SrcToLook.push_back(CurSrcPair);
629*9880d681SAndroid Build Coastguard Worker 
630*9880d681SAndroid Build Coastguard Worker   unsigned PHICount = 0;
631*9880d681SAndroid Build Coastguard Worker   while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
632*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
633*9880d681SAndroid Build Coastguard Worker     // As explained above, do not handle physical registers
634*9880d681SAndroid Build Coastguard Worker     if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
635*9880d681SAndroid Build Coastguard Worker       return false;
636*9880d681SAndroid Build Coastguard Worker 
637*9880d681SAndroid Build Coastguard Worker     CurSrcPair = Pair;
638*9880d681SAndroid Build Coastguard Worker     ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
639*9880d681SAndroid Build Coastguard Worker                             !DisableAdvCopyOpt, TII);
640*9880d681SAndroid Build Coastguard Worker     ValueTrackerResult Res;
641*9880d681SAndroid Build Coastguard Worker     bool ShouldRewrite = false;
642*9880d681SAndroid Build Coastguard Worker 
643*9880d681SAndroid Build Coastguard Worker     do {
644*9880d681SAndroid Build Coastguard Worker       // Follow the chain of copies until we reach the top of the use-def chain
645*9880d681SAndroid Build Coastguard Worker       // or find a more suitable source.
646*9880d681SAndroid Build Coastguard Worker       Res = ValTracker.getNextSource();
647*9880d681SAndroid Build Coastguard Worker       if (!Res.isValid())
648*9880d681SAndroid Build Coastguard Worker         break;
649*9880d681SAndroid Build Coastguard Worker 
650*9880d681SAndroid Build Coastguard Worker       // Insert the Def -> Use entry for the recently found source.
651*9880d681SAndroid Build Coastguard Worker       ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
652*9880d681SAndroid Build Coastguard Worker       if (CurSrcRes.isValid()) {
653*9880d681SAndroid Build Coastguard Worker         assert(CurSrcRes == Res && "ValueTrackerResult found must match");
654*9880d681SAndroid Build Coastguard Worker         // An existent entry with multiple sources is a PHI cycle we must avoid.
655*9880d681SAndroid Build Coastguard Worker         // Otherwise it's an entry with a valid next source we already found.
656*9880d681SAndroid Build Coastguard Worker         if (CurSrcRes.getNumSources() > 1) {
657*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
658*9880d681SAndroid Build Coastguard Worker           return false;
659*9880d681SAndroid Build Coastguard Worker         }
660*9880d681SAndroid Build Coastguard Worker         break;
661*9880d681SAndroid Build Coastguard Worker       }
662*9880d681SAndroid Build Coastguard Worker       RewriteMap.insert(std::make_pair(CurSrcPair, Res));
663*9880d681SAndroid Build Coastguard Worker 
664*9880d681SAndroid Build Coastguard Worker       // ValueTrackerResult usually have one source unless it's the result from
665*9880d681SAndroid Build Coastguard Worker       // a PHI instruction. Add the found PHI edges to be looked up further.
666*9880d681SAndroid Build Coastguard Worker       unsigned NumSrcs = Res.getNumSources();
667*9880d681SAndroid Build Coastguard Worker       if (NumSrcs > 1) {
668*9880d681SAndroid Build Coastguard Worker         PHICount++;
669*9880d681SAndroid Build Coastguard Worker         for (unsigned i = 0; i < NumSrcs; ++i)
670*9880d681SAndroid Build Coastguard Worker           SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
671*9880d681SAndroid Build Coastguard Worker               Res.getSrcReg(i), Res.getSrcSubReg(i)));
672*9880d681SAndroid Build Coastguard Worker         break;
673*9880d681SAndroid Build Coastguard Worker       }
674*9880d681SAndroid Build Coastguard Worker 
675*9880d681SAndroid Build Coastguard Worker       CurSrcPair.Reg = Res.getSrcReg(0);
676*9880d681SAndroid Build Coastguard Worker       CurSrcPair.SubReg = Res.getSrcSubReg(0);
677*9880d681SAndroid Build Coastguard Worker       // Do not extend the live-ranges of physical registers as they add
678*9880d681SAndroid Build Coastguard Worker       // constraints to the register allocator. Moreover, if we want to extend
679*9880d681SAndroid Build Coastguard Worker       // the live-range of a physical register, unlike SSA virtual register,
680*9880d681SAndroid Build Coastguard Worker       // we will have to check that they aren't redefine before the related use.
681*9880d681SAndroid Build Coastguard Worker       if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
682*9880d681SAndroid Build Coastguard Worker         return false;
683*9880d681SAndroid Build Coastguard Worker 
684*9880d681SAndroid Build Coastguard Worker       const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
685*9880d681SAndroid Build Coastguard Worker       ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
686*9880d681SAndroid Build Coastguard Worker                                                 CurSrcPair.SubReg);
687*9880d681SAndroid Build Coastguard Worker     } while (!ShouldRewrite);
688*9880d681SAndroid Build Coastguard Worker 
689*9880d681SAndroid Build Coastguard Worker     // Continue looking for new sources...
690*9880d681SAndroid Build Coastguard Worker     if (Res.isValid())
691*9880d681SAndroid Build Coastguard Worker       continue;
692*9880d681SAndroid Build Coastguard Worker 
693*9880d681SAndroid Build Coastguard Worker     // Do not continue searching for a new source if the there's at least
694*9880d681SAndroid Build Coastguard Worker     // one use-def which cannot be rewritten.
695*9880d681SAndroid Build Coastguard Worker     if (!ShouldRewrite)
696*9880d681SAndroid Build Coastguard Worker       return false;
697*9880d681SAndroid Build Coastguard Worker   }
698*9880d681SAndroid Build Coastguard Worker 
699*9880d681SAndroid Build Coastguard Worker   if (PHICount >= RewritePHILimit) {
700*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
701*9880d681SAndroid Build Coastguard Worker     return false;
702*9880d681SAndroid Build Coastguard Worker   }
703*9880d681SAndroid Build Coastguard Worker 
704*9880d681SAndroid Build Coastguard Worker   // If we did not find a more suitable source, there is nothing to optimize.
705*9880d681SAndroid Build Coastguard Worker   return CurSrcPair.Reg != Reg;
706*9880d681SAndroid Build Coastguard Worker }
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
709*9880d681SAndroid Build Coastguard Worker /// guaranteed to have the same register class. This is necessary whenever we
710*9880d681SAndroid Build Coastguard Worker /// successfully traverse a PHI instruction and find suitable sources coming
711*9880d681SAndroid Build Coastguard Worker /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
712*9880d681SAndroid Build Coastguard Worker /// suitable to be used in a new COPY instruction.
713*9880d681SAndroid Build Coastguard Worker static MachineInstr *
insertPHI(MachineRegisterInfo * MRI,const TargetInstrInfo * TII,const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> & SrcRegs,MachineInstr * OrigPHI)714*9880d681SAndroid Build Coastguard Worker insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
715*9880d681SAndroid Build Coastguard Worker           const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
716*9880d681SAndroid Build Coastguard Worker           MachineInstr *OrigPHI) {
717*9880d681SAndroid Build Coastguard Worker   assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
718*9880d681SAndroid Build Coastguard Worker 
719*9880d681SAndroid Build Coastguard Worker   const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
720*9880d681SAndroid Build Coastguard Worker   unsigned NewVR = MRI->createVirtualRegister(NewRC);
721*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *MBB = OrigPHI->getParent();
722*9880d681SAndroid Build Coastguard Worker   MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
723*9880d681SAndroid Build Coastguard Worker                                     TII->get(TargetOpcode::PHI), NewVR);
724*9880d681SAndroid Build Coastguard Worker 
725*9880d681SAndroid Build Coastguard Worker   unsigned MBBOpIdx = 2;
726*9880d681SAndroid Build Coastguard Worker   for (auto RegPair : SrcRegs) {
727*9880d681SAndroid Build Coastguard Worker     MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
728*9880d681SAndroid Build Coastguard Worker     MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
729*9880d681SAndroid Build Coastguard Worker     // Since we're extended the lifetime of RegPair.Reg, clear the
730*9880d681SAndroid Build Coastguard Worker     // kill flags to account for that and make RegPair.Reg reaches
731*9880d681SAndroid Build Coastguard Worker     // the new PHI.
732*9880d681SAndroid Build Coastguard Worker     MRI->clearKillFlags(RegPair.Reg);
733*9880d681SAndroid Build Coastguard Worker     MBBOpIdx += 2;
734*9880d681SAndroid Build Coastguard Worker   }
735*9880d681SAndroid Build Coastguard Worker 
736*9880d681SAndroid Build Coastguard Worker   return MIB;
737*9880d681SAndroid Build Coastguard Worker }
738*9880d681SAndroid Build Coastguard Worker 
739*9880d681SAndroid Build Coastguard Worker namespace {
740*9880d681SAndroid Build Coastguard Worker /// \brief Helper class to rewrite the arguments of a copy-like instruction.
741*9880d681SAndroid Build Coastguard Worker class CopyRewriter {
742*9880d681SAndroid Build Coastguard Worker protected:
743*9880d681SAndroid Build Coastguard Worker   /// The copy-like instruction.
744*9880d681SAndroid Build Coastguard Worker   MachineInstr &CopyLike;
745*9880d681SAndroid Build Coastguard Worker   /// The index of the source being rewritten.
746*9880d681SAndroid Build Coastguard Worker   unsigned CurrentSrcIdx;
747*9880d681SAndroid Build Coastguard Worker 
748*9880d681SAndroid Build Coastguard Worker public:
CopyRewriter(MachineInstr & MI)749*9880d681SAndroid Build Coastguard Worker   CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
750*9880d681SAndroid Build Coastguard Worker 
~CopyRewriter()751*9880d681SAndroid Build Coastguard Worker   virtual ~CopyRewriter() {}
752*9880d681SAndroid Build Coastguard Worker 
753*9880d681SAndroid Build Coastguard Worker   /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
754*9880d681SAndroid Build Coastguard Worker   /// the related value that it affects (TrackReg, TrackSubReg).
755*9880d681SAndroid Build Coastguard Worker   /// A source is considered rewritable if its register class and the
756*9880d681SAndroid Build Coastguard Worker   /// register class of the related TrackReg may not be register
757*9880d681SAndroid Build Coastguard Worker   /// coalescer friendly. In other words, given a copy-like instruction
758*9880d681SAndroid Build Coastguard Worker   /// not all the arguments may be returned at rewritable source, since
759*9880d681SAndroid Build Coastguard Worker   /// some arguments are none to be register coalescer friendly.
760*9880d681SAndroid Build Coastguard Worker   ///
761*9880d681SAndroid Build Coastguard Worker   /// Each call of this method moves the current source to the next
762*9880d681SAndroid Build Coastguard Worker   /// rewritable source.
763*9880d681SAndroid Build Coastguard Worker   /// For instance, let CopyLike be the instruction to rewrite.
764*9880d681SAndroid Build Coastguard Worker   /// CopyLike has one definition and one source:
765*9880d681SAndroid Build Coastguard Worker   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
766*9880d681SAndroid Build Coastguard Worker   ///
767*9880d681SAndroid Build Coastguard Worker   /// The first call will give the first rewritable source, i.e.,
768*9880d681SAndroid Build Coastguard Worker   /// the only source this instruction has:
769*9880d681SAndroid Build Coastguard Worker   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
770*9880d681SAndroid Build Coastguard Worker   /// This source defines the whole definition, i.e.,
771*9880d681SAndroid Build Coastguard Worker   /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
772*9880d681SAndroid Build Coastguard Worker   ///
773*9880d681SAndroid Build Coastguard Worker   /// The second and subsequent calls will return false, as there is only one
774*9880d681SAndroid Build Coastguard Worker   /// rewritable source.
775*9880d681SAndroid Build Coastguard Worker   ///
776*9880d681SAndroid Build Coastguard Worker   /// \return True if a rewritable source has been found, false otherwise.
777*9880d681SAndroid Build Coastguard Worker   /// The output arguments are valid if and only if true is returned.
getNextRewritableSource(unsigned & SrcReg,unsigned & SrcSubReg,unsigned & TrackReg,unsigned & TrackSubReg)778*9880d681SAndroid Build Coastguard Worker   virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
779*9880d681SAndroid Build Coastguard Worker                                        unsigned &TrackReg,
780*9880d681SAndroid Build Coastguard Worker                                        unsigned &TrackSubReg) {
781*9880d681SAndroid Build Coastguard Worker     // If CurrentSrcIdx == 1, this means this function has already been called
782*9880d681SAndroid Build Coastguard Worker     // once. CopyLike has one definition and one argument, thus, there is
783*9880d681SAndroid Build Coastguard Worker     // nothing else to rewrite.
784*9880d681SAndroid Build Coastguard Worker     if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
785*9880d681SAndroid Build Coastguard Worker       return false;
786*9880d681SAndroid Build Coastguard Worker     // This is the first call to getNextRewritableSource.
787*9880d681SAndroid Build Coastguard Worker     // Move the CurrentSrcIdx to remember that we made that call.
788*9880d681SAndroid Build Coastguard Worker     CurrentSrcIdx = 1;
789*9880d681SAndroid Build Coastguard Worker     // The rewritable source is the argument.
790*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MOSrc = CopyLike.getOperand(1);
791*9880d681SAndroid Build Coastguard Worker     SrcReg = MOSrc.getReg();
792*9880d681SAndroid Build Coastguard Worker     SrcSubReg = MOSrc.getSubReg();
793*9880d681SAndroid Build Coastguard Worker     // What we track are the alternative sources of the definition.
794*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MODef = CopyLike.getOperand(0);
795*9880d681SAndroid Build Coastguard Worker     TrackReg = MODef.getReg();
796*9880d681SAndroid Build Coastguard Worker     TrackSubReg = MODef.getSubReg();
797*9880d681SAndroid Build Coastguard Worker     return true;
798*9880d681SAndroid Build Coastguard Worker   }
799*9880d681SAndroid Build Coastguard Worker 
800*9880d681SAndroid Build Coastguard Worker   /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
801*9880d681SAndroid Build Coastguard Worker   /// if possible.
802*9880d681SAndroid Build Coastguard Worker   /// \return True if the rewriting was possible, false otherwise.
RewriteCurrentSource(unsigned NewReg,unsigned NewSubReg)803*9880d681SAndroid Build Coastguard Worker   virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
804*9880d681SAndroid Build Coastguard Worker     if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
805*9880d681SAndroid Build Coastguard Worker       return false;
806*9880d681SAndroid Build Coastguard Worker     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
807*9880d681SAndroid Build Coastguard Worker     MOSrc.setReg(NewReg);
808*9880d681SAndroid Build Coastguard Worker     MOSrc.setSubReg(NewSubReg);
809*9880d681SAndroid Build Coastguard Worker     return true;
810*9880d681SAndroid Build Coastguard Worker   }
811*9880d681SAndroid Build Coastguard Worker 
812*9880d681SAndroid Build Coastguard Worker   /// \brief Given a \p Def.Reg and Def.SubReg  pair, use \p RewriteMap to find
813*9880d681SAndroid Build Coastguard Worker   /// the new source to use for rewrite. If \p HandleMultipleSources is true and
814*9880d681SAndroid Build Coastguard Worker   /// multiple sources for a given \p Def are found along the way, we found a
815*9880d681SAndroid Build Coastguard Worker   /// PHI instructions that needs to be rewritten.
816*9880d681SAndroid Build Coastguard Worker   /// TODO: HandleMultipleSources should be removed once we test PHI handling
817*9880d681SAndroid Build Coastguard Worker   /// with coalescable copies.
818*9880d681SAndroid Build Coastguard Worker   TargetInstrInfo::RegSubRegPair
getNewSource(MachineRegisterInfo * MRI,const TargetInstrInfo * TII,TargetInstrInfo::RegSubRegPair Def,PeepholeOptimizer::RewriteMapTy & RewriteMap,bool HandleMultipleSources=true)819*9880d681SAndroid Build Coastguard Worker   getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
820*9880d681SAndroid Build Coastguard Worker                TargetInstrInfo::RegSubRegPair Def,
821*9880d681SAndroid Build Coastguard Worker                PeepholeOptimizer::RewriteMapTy &RewriteMap,
822*9880d681SAndroid Build Coastguard Worker                bool HandleMultipleSources = true) {
823*9880d681SAndroid Build Coastguard Worker 
824*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
825*9880d681SAndroid Build Coastguard Worker     do {
826*9880d681SAndroid Build Coastguard Worker       ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
827*9880d681SAndroid Build Coastguard Worker       // If there are no entries on the map, LookupSrc is the new source.
828*9880d681SAndroid Build Coastguard Worker       if (!Res.isValid())
829*9880d681SAndroid Build Coastguard Worker         return LookupSrc;
830*9880d681SAndroid Build Coastguard Worker 
831*9880d681SAndroid Build Coastguard Worker       // There's only one source for this definition, keep searching...
832*9880d681SAndroid Build Coastguard Worker       unsigned NumSrcs = Res.getNumSources();
833*9880d681SAndroid Build Coastguard Worker       if (NumSrcs == 1) {
834*9880d681SAndroid Build Coastguard Worker         LookupSrc.Reg = Res.getSrcReg(0);
835*9880d681SAndroid Build Coastguard Worker         LookupSrc.SubReg = Res.getSrcSubReg(0);
836*9880d681SAndroid Build Coastguard Worker         continue;
837*9880d681SAndroid Build Coastguard Worker       }
838*9880d681SAndroid Build Coastguard Worker 
839*9880d681SAndroid Build Coastguard Worker       // TODO: Remove once multiple srcs w/ coalescable copies are supported.
840*9880d681SAndroid Build Coastguard Worker       if (!HandleMultipleSources)
841*9880d681SAndroid Build Coastguard Worker         break;
842*9880d681SAndroid Build Coastguard Worker 
843*9880d681SAndroid Build Coastguard Worker       // Multiple sources, recurse into each source to find a new source
844*9880d681SAndroid Build Coastguard Worker       // for it. Then, rewrite the PHI accordingly to its new edges.
845*9880d681SAndroid Build Coastguard Worker       SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
846*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0; i < NumSrcs; ++i) {
847*9880d681SAndroid Build Coastguard Worker         TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
848*9880d681SAndroid Build Coastguard Worker                                               Res.getSrcSubReg(i));
849*9880d681SAndroid Build Coastguard Worker         NewPHISrcs.push_back(
850*9880d681SAndroid Build Coastguard Worker             getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
851*9880d681SAndroid Build Coastguard Worker       }
852*9880d681SAndroid Build Coastguard Worker 
853*9880d681SAndroid Build Coastguard Worker       // Build the new PHI node and return its def register as the new source.
854*9880d681SAndroid Build Coastguard Worker       MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
855*9880d681SAndroid Build Coastguard Worker       MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
856*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "-- getNewSource\n");
857*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "   Replacing: " << *OrigPHI);
858*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "        With: " << *NewPHI);
859*9880d681SAndroid Build Coastguard Worker       const MachineOperand &MODef = NewPHI->getOperand(0);
860*9880d681SAndroid Build Coastguard Worker       return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
861*9880d681SAndroid Build Coastguard Worker 
862*9880d681SAndroid Build Coastguard Worker     } while (1);
863*9880d681SAndroid Build Coastguard Worker 
864*9880d681SAndroid Build Coastguard Worker     return TargetInstrInfo::RegSubRegPair(0, 0);
865*9880d681SAndroid Build Coastguard Worker   }
866*9880d681SAndroid Build Coastguard Worker 
867*9880d681SAndroid Build Coastguard Worker   /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
868*9880d681SAndroid Build Coastguard Worker   /// and create a new COPY instruction. More info about RewriteMap in
869*9880d681SAndroid Build Coastguard Worker   /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
870*9880d681SAndroid Build Coastguard Worker   /// Uncoalescable copies, since they are copy like instructions that aren't
871*9880d681SAndroid Build Coastguard Worker   /// recognized by the register allocator.
872*9880d681SAndroid Build Coastguard Worker   virtual MachineInstr *
RewriteSource(TargetInstrInfo::RegSubRegPair Def,PeepholeOptimizer::RewriteMapTy & RewriteMap)873*9880d681SAndroid Build Coastguard Worker   RewriteSource(TargetInstrInfo::RegSubRegPair Def,
874*9880d681SAndroid Build Coastguard Worker                 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
875*9880d681SAndroid Build Coastguard Worker     return nullptr;
876*9880d681SAndroid Build Coastguard Worker   }
877*9880d681SAndroid Build Coastguard Worker };
878*9880d681SAndroid Build Coastguard Worker 
879*9880d681SAndroid Build Coastguard Worker /// \brief Helper class to rewrite uncoalescable copy like instructions
880*9880d681SAndroid Build Coastguard Worker /// into new COPY (coalescable friendly) instructions.
881*9880d681SAndroid Build Coastguard Worker class UncoalescableRewriter : public CopyRewriter {
882*9880d681SAndroid Build Coastguard Worker protected:
883*9880d681SAndroid Build Coastguard Worker   const TargetInstrInfo &TII;
884*9880d681SAndroid Build Coastguard Worker   MachineRegisterInfo   &MRI;
885*9880d681SAndroid Build Coastguard Worker   /// The number of defs in the bitcast
886*9880d681SAndroid Build Coastguard Worker   unsigned NumDefs;
887*9880d681SAndroid Build Coastguard Worker 
888*9880d681SAndroid Build Coastguard Worker public:
UncoalescableRewriter(MachineInstr & MI,const TargetInstrInfo & TII,MachineRegisterInfo & MRI)889*9880d681SAndroid Build Coastguard Worker   UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
890*9880d681SAndroid Build Coastguard Worker                          MachineRegisterInfo &MRI)
891*9880d681SAndroid Build Coastguard Worker       : CopyRewriter(MI), TII(TII), MRI(MRI) {
892*9880d681SAndroid Build Coastguard Worker     NumDefs = MI.getDesc().getNumDefs();
893*9880d681SAndroid Build Coastguard Worker   }
894*9880d681SAndroid Build Coastguard Worker 
895*9880d681SAndroid Build Coastguard Worker   /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
896*9880d681SAndroid Build Coastguard Worker   /// All such sources need to be considered rewritable in order to
897*9880d681SAndroid Build Coastguard Worker   /// rewrite a uncoalescable copy-like instruction. This method return
898*9880d681SAndroid Build Coastguard Worker   /// each definition that must be checked if rewritable.
899*9880d681SAndroid Build Coastguard Worker   ///
getNextRewritableSource(unsigned & SrcReg,unsigned & SrcSubReg,unsigned & TrackReg,unsigned & TrackSubReg)900*9880d681SAndroid Build Coastguard Worker   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
901*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackReg,
902*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackSubReg) override {
903*9880d681SAndroid Build Coastguard Worker     // Find the next non-dead definition and continue from there.
904*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx == NumDefs)
905*9880d681SAndroid Build Coastguard Worker       return false;
906*9880d681SAndroid Build Coastguard Worker 
907*9880d681SAndroid Build Coastguard Worker     while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
908*9880d681SAndroid Build Coastguard Worker       ++CurrentSrcIdx;
909*9880d681SAndroid Build Coastguard Worker       if (CurrentSrcIdx == NumDefs)
910*9880d681SAndroid Build Coastguard Worker         return false;
911*9880d681SAndroid Build Coastguard Worker     }
912*9880d681SAndroid Build Coastguard Worker 
913*9880d681SAndroid Build Coastguard Worker     // What we track are the alternative sources of the definition.
914*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
915*9880d681SAndroid Build Coastguard Worker     TrackReg = MODef.getReg();
916*9880d681SAndroid Build Coastguard Worker     TrackSubReg = MODef.getSubReg();
917*9880d681SAndroid Build Coastguard Worker 
918*9880d681SAndroid Build Coastguard Worker     CurrentSrcIdx++;
919*9880d681SAndroid Build Coastguard Worker     return true;
920*9880d681SAndroid Build Coastguard Worker   }
921*9880d681SAndroid Build Coastguard Worker 
922*9880d681SAndroid Build Coastguard Worker   /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
923*9880d681SAndroid Build Coastguard Worker   /// and create a new COPY instruction. More info about RewriteMap in
924*9880d681SAndroid Build Coastguard Worker   /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
925*9880d681SAndroid Build Coastguard Worker   /// Uncoalescable copies, since they are copy like instructions that aren't
926*9880d681SAndroid Build Coastguard Worker   /// recognized by the register allocator.
927*9880d681SAndroid Build Coastguard Worker   MachineInstr *
RewriteSource(TargetInstrInfo::RegSubRegPair Def,PeepholeOptimizer::RewriteMapTy & RewriteMap)928*9880d681SAndroid Build Coastguard Worker   RewriteSource(TargetInstrInfo::RegSubRegPair Def,
929*9880d681SAndroid Build Coastguard Worker                 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
930*9880d681SAndroid Build Coastguard Worker     assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
931*9880d681SAndroid Build Coastguard Worker            "We do not rewrite physical registers");
932*9880d681SAndroid Build Coastguard Worker 
933*9880d681SAndroid Build Coastguard Worker     // Find the new source to use in the COPY rewrite.
934*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair NewSrc =
935*9880d681SAndroid Build Coastguard Worker         getNewSource(&MRI, &TII, Def, RewriteMap);
936*9880d681SAndroid Build Coastguard Worker 
937*9880d681SAndroid Build Coastguard Worker     // Insert the COPY.
938*9880d681SAndroid Build Coastguard Worker     const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
939*9880d681SAndroid Build Coastguard Worker     unsigned NewVR = MRI.createVirtualRegister(DefRC);
940*9880d681SAndroid Build Coastguard Worker 
941*9880d681SAndroid Build Coastguard Worker     MachineInstr *NewCopy =
942*9880d681SAndroid Build Coastguard Worker         BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
943*9880d681SAndroid Build Coastguard Worker                 TII.get(TargetOpcode::COPY), NewVR)
944*9880d681SAndroid Build Coastguard Worker             .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
945*9880d681SAndroid Build Coastguard Worker 
946*9880d681SAndroid Build Coastguard Worker     NewCopy->getOperand(0).setSubReg(Def.SubReg);
947*9880d681SAndroid Build Coastguard Worker     if (Def.SubReg)
948*9880d681SAndroid Build Coastguard Worker       NewCopy->getOperand(0).setIsUndef();
949*9880d681SAndroid Build Coastguard Worker 
950*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "-- RewriteSource\n");
951*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "   Replacing: " << CopyLike);
952*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "        With: " << *NewCopy);
953*9880d681SAndroid Build Coastguard Worker     MRI.replaceRegWith(Def.Reg, NewVR);
954*9880d681SAndroid Build Coastguard Worker     MRI.clearKillFlags(NewVR);
955*9880d681SAndroid Build Coastguard Worker 
956*9880d681SAndroid Build Coastguard Worker     // We extended the lifetime of NewSrc.Reg, clear the kill flags to
957*9880d681SAndroid Build Coastguard Worker     // account for that.
958*9880d681SAndroid Build Coastguard Worker     MRI.clearKillFlags(NewSrc.Reg);
959*9880d681SAndroid Build Coastguard Worker 
960*9880d681SAndroid Build Coastguard Worker     return NewCopy;
961*9880d681SAndroid Build Coastguard Worker   }
962*9880d681SAndroid Build Coastguard Worker };
963*9880d681SAndroid Build Coastguard Worker 
964*9880d681SAndroid Build Coastguard Worker /// \brief Specialized rewriter for INSERT_SUBREG instruction.
965*9880d681SAndroid Build Coastguard Worker class InsertSubregRewriter : public CopyRewriter {
966*9880d681SAndroid Build Coastguard Worker public:
InsertSubregRewriter(MachineInstr & MI)967*9880d681SAndroid Build Coastguard Worker   InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
968*9880d681SAndroid Build Coastguard Worker     assert(MI.isInsertSubreg() && "Invalid instruction");
969*9880d681SAndroid Build Coastguard Worker   }
970*9880d681SAndroid Build Coastguard Worker 
971*9880d681SAndroid Build Coastguard Worker   /// \brief See CopyRewriter::getNextRewritableSource.
972*9880d681SAndroid Build Coastguard Worker   /// Here CopyLike has the following form:
973*9880d681SAndroid Build Coastguard Worker   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
974*9880d681SAndroid Build Coastguard Worker   /// Src1 has the same register class has dst, hence, there is
975*9880d681SAndroid Build Coastguard Worker   /// nothing to rewrite.
976*9880d681SAndroid Build Coastguard Worker   /// Src2.src2SubIdx, may not be register coalescer friendly.
977*9880d681SAndroid Build Coastguard Worker   /// Therefore, the first call to this method returns:
978*9880d681SAndroid Build Coastguard Worker   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
979*9880d681SAndroid Build Coastguard Worker   /// (TrackReg, TrackSubReg) = (dst, subIdx).
980*9880d681SAndroid Build Coastguard Worker   ///
981*9880d681SAndroid Build Coastguard Worker   /// Subsequence calls will return false.
getNextRewritableSource(unsigned & SrcReg,unsigned & SrcSubReg,unsigned & TrackReg,unsigned & TrackSubReg)982*9880d681SAndroid Build Coastguard Worker   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
983*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackReg,
984*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackSubReg) override {
985*9880d681SAndroid Build Coastguard Worker     // If we already get the only source we can rewrite, return false.
986*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx == 2)
987*9880d681SAndroid Build Coastguard Worker       return false;
988*9880d681SAndroid Build Coastguard Worker     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
989*9880d681SAndroid Build Coastguard Worker     CurrentSrcIdx = 2;
990*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
991*9880d681SAndroid Build Coastguard Worker     SrcReg = MOInsertedReg.getReg();
992*9880d681SAndroid Build Coastguard Worker     SrcSubReg = MOInsertedReg.getSubReg();
993*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MODef = CopyLike.getOperand(0);
994*9880d681SAndroid Build Coastguard Worker 
995*9880d681SAndroid Build Coastguard Worker     // We want to track something that is compatible with the
996*9880d681SAndroid Build Coastguard Worker     // partial definition.
997*9880d681SAndroid Build Coastguard Worker     TrackReg = MODef.getReg();
998*9880d681SAndroid Build Coastguard Worker     if (MODef.getSubReg())
999*9880d681SAndroid Build Coastguard Worker       // Bail if we have to compose sub-register indices.
1000*9880d681SAndroid Build Coastguard Worker       return false;
1001*9880d681SAndroid Build Coastguard Worker     TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1002*9880d681SAndroid Build Coastguard Worker     return true;
1003*9880d681SAndroid Build Coastguard Worker   }
RewriteCurrentSource(unsigned NewReg,unsigned NewSubReg)1004*9880d681SAndroid Build Coastguard Worker   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1005*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx != 2)
1006*9880d681SAndroid Build Coastguard Worker       return false;
1007*9880d681SAndroid Build Coastguard Worker     // We are rewriting the inserted reg.
1008*9880d681SAndroid Build Coastguard Worker     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1009*9880d681SAndroid Build Coastguard Worker     MO.setReg(NewReg);
1010*9880d681SAndroid Build Coastguard Worker     MO.setSubReg(NewSubReg);
1011*9880d681SAndroid Build Coastguard Worker     return true;
1012*9880d681SAndroid Build Coastguard Worker   }
1013*9880d681SAndroid Build Coastguard Worker };
1014*9880d681SAndroid Build Coastguard Worker 
1015*9880d681SAndroid Build Coastguard Worker /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1016*9880d681SAndroid Build Coastguard Worker class ExtractSubregRewriter : public CopyRewriter {
1017*9880d681SAndroid Build Coastguard Worker   const TargetInstrInfo &TII;
1018*9880d681SAndroid Build Coastguard Worker 
1019*9880d681SAndroid Build Coastguard Worker public:
ExtractSubregRewriter(MachineInstr & MI,const TargetInstrInfo & TII)1020*9880d681SAndroid Build Coastguard Worker   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1021*9880d681SAndroid Build Coastguard Worker       : CopyRewriter(MI), TII(TII) {
1022*9880d681SAndroid Build Coastguard Worker     assert(MI.isExtractSubreg() && "Invalid instruction");
1023*9880d681SAndroid Build Coastguard Worker   }
1024*9880d681SAndroid Build Coastguard Worker 
1025*9880d681SAndroid Build Coastguard Worker   /// \brief See CopyRewriter::getNextRewritableSource.
1026*9880d681SAndroid Build Coastguard Worker   /// Here CopyLike has the following form:
1027*9880d681SAndroid Build Coastguard Worker   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1028*9880d681SAndroid Build Coastguard Worker   /// There is only one rewritable source: Src.subIdx,
1029*9880d681SAndroid Build Coastguard Worker   /// which defines dst.dstSubIdx.
getNextRewritableSource(unsigned & SrcReg,unsigned & SrcSubReg,unsigned & TrackReg,unsigned & TrackSubReg)1030*9880d681SAndroid Build Coastguard Worker   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1031*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackReg,
1032*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackSubReg) override {
1033*9880d681SAndroid Build Coastguard Worker     // If we already get the only source we can rewrite, return false.
1034*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx == 1)
1035*9880d681SAndroid Build Coastguard Worker       return false;
1036*9880d681SAndroid Build Coastguard Worker     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1037*9880d681SAndroid Build Coastguard Worker     CurrentSrcIdx = 1;
1038*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1039*9880d681SAndroid Build Coastguard Worker     SrcReg = MOExtractedReg.getReg();
1040*9880d681SAndroid Build Coastguard Worker     // If we have to compose sub-register indices, bail out.
1041*9880d681SAndroid Build Coastguard Worker     if (MOExtractedReg.getSubReg())
1042*9880d681SAndroid Build Coastguard Worker       return false;
1043*9880d681SAndroid Build Coastguard Worker 
1044*9880d681SAndroid Build Coastguard Worker     SrcSubReg = CopyLike.getOperand(2).getImm();
1045*9880d681SAndroid Build Coastguard Worker 
1046*9880d681SAndroid Build Coastguard Worker     // We want to track something that is compatible with the definition.
1047*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MODef = CopyLike.getOperand(0);
1048*9880d681SAndroid Build Coastguard Worker     TrackReg = MODef.getReg();
1049*9880d681SAndroid Build Coastguard Worker     TrackSubReg = MODef.getSubReg();
1050*9880d681SAndroid Build Coastguard Worker     return true;
1051*9880d681SAndroid Build Coastguard Worker   }
1052*9880d681SAndroid Build Coastguard Worker 
RewriteCurrentSource(unsigned NewReg,unsigned NewSubReg)1053*9880d681SAndroid Build Coastguard Worker   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1054*9880d681SAndroid Build Coastguard Worker     // The only source we can rewrite is the input register.
1055*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx != 1)
1056*9880d681SAndroid Build Coastguard Worker       return false;
1057*9880d681SAndroid Build Coastguard Worker 
1058*9880d681SAndroid Build Coastguard Worker     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1059*9880d681SAndroid Build Coastguard Worker 
1060*9880d681SAndroid Build Coastguard Worker     // If we find a source that does not require to extract something,
1061*9880d681SAndroid Build Coastguard Worker     // rewrite the operation with a copy.
1062*9880d681SAndroid Build Coastguard Worker     if (!NewSubReg) {
1063*9880d681SAndroid Build Coastguard Worker       // Move the current index to an invalid position.
1064*9880d681SAndroid Build Coastguard Worker       // We do not want another call to this method to be able
1065*9880d681SAndroid Build Coastguard Worker       // to do any change.
1066*9880d681SAndroid Build Coastguard Worker       CurrentSrcIdx = -1;
1067*9880d681SAndroid Build Coastguard Worker       // Rewrite the operation as a COPY.
1068*9880d681SAndroid Build Coastguard Worker       // Get rid of the sub-register index.
1069*9880d681SAndroid Build Coastguard Worker       CopyLike.RemoveOperand(2);
1070*9880d681SAndroid Build Coastguard Worker       // Morph the operation into a COPY.
1071*9880d681SAndroid Build Coastguard Worker       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1072*9880d681SAndroid Build Coastguard Worker       return true;
1073*9880d681SAndroid Build Coastguard Worker     }
1074*9880d681SAndroid Build Coastguard Worker     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1075*9880d681SAndroid Build Coastguard Worker     return true;
1076*9880d681SAndroid Build Coastguard Worker   }
1077*9880d681SAndroid Build Coastguard Worker };
1078*9880d681SAndroid Build Coastguard Worker 
1079*9880d681SAndroid Build Coastguard Worker /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1080*9880d681SAndroid Build Coastguard Worker class RegSequenceRewriter : public CopyRewriter {
1081*9880d681SAndroid Build Coastguard Worker public:
RegSequenceRewriter(MachineInstr & MI)1082*9880d681SAndroid Build Coastguard Worker   RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1083*9880d681SAndroid Build Coastguard Worker     assert(MI.isRegSequence() && "Invalid instruction");
1084*9880d681SAndroid Build Coastguard Worker   }
1085*9880d681SAndroid Build Coastguard Worker 
1086*9880d681SAndroid Build Coastguard Worker   /// \brief See CopyRewriter::getNextRewritableSource.
1087*9880d681SAndroid Build Coastguard Worker   /// Here CopyLike has the following form:
1088*9880d681SAndroid Build Coastguard Worker   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1089*9880d681SAndroid Build Coastguard Worker   /// Each call will return a different source, walking all the available
1090*9880d681SAndroid Build Coastguard Worker   /// source.
1091*9880d681SAndroid Build Coastguard Worker   ///
1092*9880d681SAndroid Build Coastguard Worker   /// The first call returns:
1093*9880d681SAndroid Build Coastguard Worker   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1094*9880d681SAndroid Build Coastguard Worker   /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1095*9880d681SAndroid Build Coastguard Worker   ///
1096*9880d681SAndroid Build Coastguard Worker   /// The second call returns:
1097*9880d681SAndroid Build Coastguard Worker   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1098*9880d681SAndroid Build Coastguard Worker   /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1099*9880d681SAndroid Build Coastguard Worker   ///
1100*9880d681SAndroid Build Coastguard Worker   /// And so on, until all the sources have been traversed, then
1101*9880d681SAndroid Build Coastguard Worker   /// it returns false.
getNextRewritableSource(unsigned & SrcReg,unsigned & SrcSubReg,unsigned & TrackReg,unsigned & TrackSubReg)1102*9880d681SAndroid Build Coastguard Worker   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1103*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackReg,
1104*9880d681SAndroid Build Coastguard Worker                                unsigned &TrackSubReg) override {
1105*9880d681SAndroid Build Coastguard Worker     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1106*9880d681SAndroid Build Coastguard Worker 
1107*9880d681SAndroid Build Coastguard Worker     // If this is the first call, move to the first argument.
1108*9880d681SAndroid Build Coastguard Worker     if (CurrentSrcIdx == 0) {
1109*9880d681SAndroid Build Coastguard Worker       CurrentSrcIdx = 1;
1110*9880d681SAndroid Build Coastguard Worker     } else {
1111*9880d681SAndroid Build Coastguard Worker       // Otherwise, move to the next argument and check that it is valid.
1112*9880d681SAndroid Build Coastguard Worker       CurrentSrcIdx += 2;
1113*9880d681SAndroid Build Coastguard Worker       if (CurrentSrcIdx >= CopyLike.getNumOperands())
1114*9880d681SAndroid Build Coastguard Worker         return false;
1115*9880d681SAndroid Build Coastguard Worker     }
1116*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1117*9880d681SAndroid Build Coastguard Worker     SrcReg = MOInsertedReg.getReg();
1118*9880d681SAndroid Build Coastguard Worker     // If we have to compose sub-register indices, bail out.
1119*9880d681SAndroid Build Coastguard Worker     if ((SrcSubReg = MOInsertedReg.getSubReg()))
1120*9880d681SAndroid Build Coastguard Worker       return false;
1121*9880d681SAndroid Build Coastguard Worker 
1122*9880d681SAndroid Build Coastguard Worker     // We want to track something that is compatible with the related
1123*9880d681SAndroid Build Coastguard Worker     // partial definition.
1124*9880d681SAndroid Build Coastguard Worker     TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1125*9880d681SAndroid Build Coastguard Worker 
1126*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MODef = CopyLike.getOperand(0);
1127*9880d681SAndroid Build Coastguard Worker     TrackReg = MODef.getReg();
1128*9880d681SAndroid Build Coastguard Worker     // If we have to compose sub-registers, bail.
1129*9880d681SAndroid Build Coastguard Worker     return MODef.getSubReg() == 0;
1130*9880d681SAndroid Build Coastguard Worker   }
1131*9880d681SAndroid Build Coastguard Worker 
RewriteCurrentSource(unsigned NewReg,unsigned NewSubReg)1132*9880d681SAndroid Build Coastguard Worker   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1133*9880d681SAndroid Build Coastguard Worker     // We cannot rewrite out of bound operands.
1134*9880d681SAndroid Build Coastguard Worker     // Moreover, rewritable sources are at odd positions.
1135*9880d681SAndroid Build Coastguard Worker     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1136*9880d681SAndroid Build Coastguard Worker       return false;
1137*9880d681SAndroid Build Coastguard Worker 
1138*9880d681SAndroid Build Coastguard Worker     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1139*9880d681SAndroid Build Coastguard Worker     MO.setReg(NewReg);
1140*9880d681SAndroid Build Coastguard Worker     MO.setSubReg(NewSubReg);
1141*9880d681SAndroid Build Coastguard Worker     return true;
1142*9880d681SAndroid Build Coastguard Worker   }
1143*9880d681SAndroid Build Coastguard Worker };
1144*9880d681SAndroid Build Coastguard Worker } // End namespace.
1145*9880d681SAndroid Build Coastguard Worker 
1146*9880d681SAndroid Build Coastguard Worker /// \brief Get the appropriated CopyRewriter for \p MI.
1147*9880d681SAndroid Build Coastguard Worker /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1148*9880d681SAndroid Build Coastguard Worker /// if no rewriter works for \p MI.
getCopyRewriter(MachineInstr & MI,const TargetInstrInfo & TII,MachineRegisterInfo & MRI)1149*9880d681SAndroid Build Coastguard Worker static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1150*9880d681SAndroid Build Coastguard Worker                                      const TargetInstrInfo &TII,
1151*9880d681SAndroid Build Coastguard Worker                                      MachineRegisterInfo &MRI) {
1152*9880d681SAndroid Build Coastguard Worker   // Handle uncoalescable copy-like instructions.
1153*9880d681SAndroid Build Coastguard Worker   if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1154*9880d681SAndroid Build Coastguard Worker                          MI.isExtractSubregLike()))
1155*9880d681SAndroid Build Coastguard Worker     return new UncoalescableRewriter(MI, TII, MRI);
1156*9880d681SAndroid Build Coastguard Worker 
1157*9880d681SAndroid Build Coastguard Worker   switch (MI.getOpcode()) {
1158*9880d681SAndroid Build Coastguard Worker   default:
1159*9880d681SAndroid Build Coastguard Worker     return nullptr;
1160*9880d681SAndroid Build Coastguard Worker   case TargetOpcode::COPY:
1161*9880d681SAndroid Build Coastguard Worker     return new CopyRewriter(MI);
1162*9880d681SAndroid Build Coastguard Worker   case TargetOpcode::INSERT_SUBREG:
1163*9880d681SAndroid Build Coastguard Worker     return new InsertSubregRewriter(MI);
1164*9880d681SAndroid Build Coastguard Worker   case TargetOpcode::EXTRACT_SUBREG:
1165*9880d681SAndroid Build Coastguard Worker     return new ExtractSubregRewriter(MI, TII);
1166*9880d681SAndroid Build Coastguard Worker   case TargetOpcode::REG_SEQUENCE:
1167*9880d681SAndroid Build Coastguard Worker     return new RegSequenceRewriter(MI);
1168*9880d681SAndroid Build Coastguard Worker   }
1169*9880d681SAndroid Build Coastguard Worker   llvm_unreachable(nullptr);
1170*9880d681SAndroid Build Coastguard Worker }
1171*9880d681SAndroid Build Coastguard Worker 
1172*9880d681SAndroid Build Coastguard Worker /// \brief Optimize generic copy instructions to avoid cross
1173*9880d681SAndroid Build Coastguard Worker /// register bank copy. The optimization looks through a chain of
1174*9880d681SAndroid Build Coastguard Worker /// copies and tries to find a source that has a compatible register
1175*9880d681SAndroid Build Coastguard Worker /// class.
1176*9880d681SAndroid Build Coastguard Worker /// Two register classes are considered to be compatible if they share
1177*9880d681SAndroid Build Coastguard Worker /// the same register bank.
1178*9880d681SAndroid Build Coastguard Worker /// New copies issued by this optimization are register allocator
1179*9880d681SAndroid Build Coastguard Worker /// friendly. This optimization does not remove any copy as it may
1180*9880d681SAndroid Build Coastguard Worker /// overconstrain the register allocator, but replaces some operands
1181*9880d681SAndroid Build Coastguard Worker /// when possible.
1182*9880d681SAndroid Build Coastguard Worker /// \pre isCoalescableCopy(*MI) is true.
1183*9880d681SAndroid Build Coastguard Worker /// \return True, when \p MI has been rewritten. False otherwise.
optimizeCoalescableCopy(MachineInstr * MI)1184*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1185*9880d681SAndroid Build Coastguard Worker   assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1186*9880d681SAndroid Build Coastguard Worker   assert(MI->getDesc().getNumDefs() == 1 &&
1187*9880d681SAndroid Build Coastguard Worker          "Coalescer can understand multiple defs?!");
1188*9880d681SAndroid Build Coastguard Worker   const MachineOperand &MODef = MI->getOperand(0);
1189*9880d681SAndroid Build Coastguard Worker   // Do not rewrite physical definitions.
1190*9880d681SAndroid Build Coastguard Worker   if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1191*9880d681SAndroid Build Coastguard Worker     return false;
1192*9880d681SAndroid Build Coastguard Worker 
1193*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
1194*9880d681SAndroid Build Coastguard Worker   // Get the right rewriter for the current copy.
1195*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1196*9880d681SAndroid Build Coastguard Worker   // If none exists, bail out.
1197*9880d681SAndroid Build Coastguard Worker   if (!CpyRewriter)
1198*9880d681SAndroid Build Coastguard Worker     return false;
1199*9880d681SAndroid Build Coastguard Worker   // Rewrite each rewritable source.
1200*9880d681SAndroid Build Coastguard Worker   unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1201*9880d681SAndroid Build Coastguard Worker   while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1202*9880d681SAndroid Build Coastguard Worker                                               TrackSubReg)) {
1203*9880d681SAndroid Build Coastguard Worker     // Keep track of PHI nodes and its incoming edges when looking for sources.
1204*9880d681SAndroid Build Coastguard Worker     RewriteMapTy RewriteMap;
1205*9880d681SAndroid Build Coastguard Worker     // Try to find a more suitable source. If we failed to do so, or get the
1206*9880d681SAndroid Build Coastguard Worker     // actual source, move to the next source.
1207*9880d681SAndroid Build Coastguard Worker     if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1208*9880d681SAndroid Build Coastguard Worker       continue;
1209*9880d681SAndroid Build Coastguard Worker 
1210*9880d681SAndroid Build Coastguard Worker     // Get the new source to rewrite. TODO: Only enable handling of multiple
1211*9880d681SAndroid Build Coastguard Worker     // sources (PHIs) once we have a motivating example and testcases for it.
1212*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1213*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1214*9880d681SAndroid Build Coastguard Worker         MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1215*9880d681SAndroid Build Coastguard Worker     if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1216*9880d681SAndroid Build Coastguard Worker       continue;
1217*9880d681SAndroid Build Coastguard Worker 
1218*9880d681SAndroid Build Coastguard Worker     // Rewrite source.
1219*9880d681SAndroid Build Coastguard Worker     if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1220*9880d681SAndroid Build Coastguard Worker       // We may have extended the live-range of NewSrc, account for that.
1221*9880d681SAndroid Build Coastguard Worker       MRI->clearKillFlags(NewSrc.Reg);
1222*9880d681SAndroid Build Coastguard Worker       Changed = true;
1223*9880d681SAndroid Build Coastguard Worker     }
1224*9880d681SAndroid Build Coastguard Worker   }
1225*9880d681SAndroid Build Coastguard Worker   // TODO: We could have a clean-up method to tidy the instruction.
1226*9880d681SAndroid Build Coastguard Worker   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1227*9880d681SAndroid Build Coastguard Worker   // => v0 = COPY v1
1228*9880d681SAndroid Build Coastguard Worker   // Currently we haven't seen motivating example for that and we
1229*9880d681SAndroid Build Coastguard Worker   // want to avoid untested code.
1230*9880d681SAndroid Build Coastguard Worker   NumRewrittenCopies += Changed;
1231*9880d681SAndroid Build Coastguard Worker   return Changed;
1232*9880d681SAndroid Build Coastguard Worker }
1233*9880d681SAndroid Build Coastguard Worker 
1234*9880d681SAndroid Build Coastguard Worker /// \brief Optimize copy-like instructions to create
1235*9880d681SAndroid Build Coastguard Worker /// register coalescer friendly instruction.
1236*9880d681SAndroid Build Coastguard Worker /// The optimization tries to kill-off the \p MI by looking
1237*9880d681SAndroid Build Coastguard Worker /// through a chain of copies to find a source that has a compatible
1238*9880d681SAndroid Build Coastguard Worker /// register class.
1239*9880d681SAndroid Build Coastguard Worker /// If such a source is found, it replace \p MI by a generic COPY
1240*9880d681SAndroid Build Coastguard Worker /// operation.
1241*9880d681SAndroid Build Coastguard Worker /// \pre isUncoalescableCopy(*MI) is true.
1242*9880d681SAndroid Build Coastguard Worker /// \return True, when \p MI has been optimized. In that case, \p MI has
1243*9880d681SAndroid Build Coastguard Worker /// been removed from its parent.
1244*9880d681SAndroid Build Coastguard Worker /// All COPY instructions created, are inserted in \p LocalMIs.
optimizeUncoalescableCopy(MachineInstr * MI,SmallPtrSetImpl<MachineInstr * > & LocalMIs)1245*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::optimizeUncoalescableCopy(
1246*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1247*9880d681SAndroid Build Coastguard Worker   assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1248*9880d681SAndroid Build Coastguard Worker 
1249*9880d681SAndroid Build Coastguard Worker   // Check if we can rewrite all the values defined by this instruction.
1250*9880d681SAndroid Build Coastguard Worker   SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1251*9880d681SAndroid Build Coastguard Worker   // Get the right rewriter for the current copy.
1252*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1253*9880d681SAndroid Build Coastguard Worker   // If none exists, bail out.
1254*9880d681SAndroid Build Coastguard Worker   if (!CpyRewriter)
1255*9880d681SAndroid Build Coastguard Worker     return false;
1256*9880d681SAndroid Build Coastguard Worker 
1257*9880d681SAndroid Build Coastguard Worker   // Rewrite each rewritable source by generating new COPYs. This works
1258*9880d681SAndroid Build Coastguard Worker   // differently from optimizeCoalescableCopy since it first makes sure that all
1259*9880d681SAndroid Build Coastguard Worker   // definitions can be rewritten.
1260*9880d681SAndroid Build Coastguard Worker   RewriteMapTy RewriteMap;
1261*9880d681SAndroid Build Coastguard Worker   unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1262*9880d681SAndroid Build Coastguard Worker   while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1263*9880d681SAndroid Build Coastguard Worker                                               CopyDefSubReg)) {
1264*9880d681SAndroid Build Coastguard Worker     // If a physical register is here, this is probably for a good reason.
1265*9880d681SAndroid Build Coastguard Worker     // Do not rewrite that.
1266*9880d681SAndroid Build Coastguard Worker     if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1267*9880d681SAndroid Build Coastguard Worker       return false;
1268*9880d681SAndroid Build Coastguard Worker 
1269*9880d681SAndroid Build Coastguard Worker     // If we do not know how to rewrite this definition, there is no point
1270*9880d681SAndroid Build Coastguard Worker     // in trying to kill this instruction.
1271*9880d681SAndroid Build Coastguard Worker     TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1272*9880d681SAndroid Build Coastguard Worker     if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1273*9880d681SAndroid Build Coastguard Worker       return false;
1274*9880d681SAndroid Build Coastguard Worker 
1275*9880d681SAndroid Build Coastguard Worker     RewritePairs.push_back(Def);
1276*9880d681SAndroid Build Coastguard Worker   }
1277*9880d681SAndroid Build Coastguard Worker 
1278*9880d681SAndroid Build Coastguard Worker   // The change is possible for all defs, do it.
1279*9880d681SAndroid Build Coastguard Worker   for (const auto &Def : RewritePairs) {
1280*9880d681SAndroid Build Coastguard Worker     // Rewrite the "copy" in a way the register coalescer understands.
1281*9880d681SAndroid Build Coastguard Worker     MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1282*9880d681SAndroid Build Coastguard Worker     assert(NewCopy && "Should be able to always generate a new copy");
1283*9880d681SAndroid Build Coastguard Worker     LocalMIs.insert(NewCopy);
1284*9880d681SAndroid Build Coastguard Worker   }
1285*9880d681SAndroid Build Coastguard Worker 
1286*9880d681SAndroid Build Coastguard Worker   // MI is now dead.
1287*9880d681SAndroid Build Coastguard Worker   MI->eraseFromParent();
1288*9880d681SAndroid Build Coastguard Worker   ++NumUncoalescableCopies;
1289*9880d681SAndroid Build Coastguard Worker   return true;
1290*9880d681SAndroid Build Coastguard Worker }
1291*9880d681SAndroid Build Coastguard Worker 
1292*9880d681SAndroid Build Coastguard Worker /// Check whether MI is a candidate for folding into a later instruction.
1293*9880d681SAndroid Build Coastguard Worker /// We only fold loads to virtual registers and the virtual register defined
1294*9880d681SAndroid Build Coastguard Worker /// has a single use.
isLoadFoldable(MachineInstr * MI,SmallSet<unsigned,16> & FoldAsLoadDefCandidates)1295*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::isLoadFoldable(
1296*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1297*9880d681SAndroid Build Coastguard Worker   if (!MI->canFoldAsLoad() || !MI->mayLoad())
1298*9880d681SAndroid Build Coastguard Worker     return false;
1299*9880d681SAndroid Build Coastguard Worker   const MCInstrDesc &MCID = MI->getDesc();
1300*9880d681SAndroid Build Coastguard Worker   if (MCID.getNumDefs() != 1)
1301*9880d681SAndroid Build Coastguard Worker     return false;
1302*9880d681SAndroid Build Coastguard Worker 
1303*9880d681SAndroid Build Coastguard Worker   unsigned Reg = MI->getOperand(0).getReg();
1304*9880d681SAndroid Build Coastguard Worker   // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1305*9880d681SAndroid Build Coastguard Worker   // loads. It should be checked when processing uses of the load, since
1306*9880d681SAndroid Build Coastguard Worker   // uses can be removed during peephole.
1307*9880d681SAndroid Build Coastguard Worker   if (!MI->getOperand(0).getSubReg() &&
1308*9880d681SAndroid Build Coastguard Worker       TargetRegisterInfo::isVirtualRegister(Reg) &&
1309*9880d681SAndroid Build Coastguard Worker       MRI->hasOneNonDBGUse(Reg)) {
1310*9880d681SAndroid Build Coastguard Worker     FoldAsLoadDefCandidates.insert(Reg);
1311*9880d681SAndroid Build Coastguard Worker     return true;
1312*9880d681SAndroid Build Coastguard Worker   }
1313*9880d681SAndroid Build Coastguard Worker   return false;
1314*9880d681SAndroid Build Coastguard Worker }
1315*9880d681SAndroid Build Coastguard Worker 
isMoveImmediate(MachineInstr * MI,SmallSet<unsigned,4> & ImmDefRegs,DenseMap<unsigned,MachineInstr * > & ImmDefMIs)1316*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::isMoveImmediate(
1317*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, SmallSet<unsigned, 4> &ImmDefRegs,
1318*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1319*9880d681SAndroid Build Coastguard Worker   const MCInstrDesc &MCID = MI->getDesc();
1320*9880d681SAndroid Build Coastguard Worker   if (!MI->isMoveImmediate())
1321*9880d681SAndroid Build Coastguard Worker     return false;
1322*9880d681SAndroid Build Coastguard Worker   if (MCID.getNumDefs() != 1)
1323*9880d681SAndroid Build Coastguard Worker     return false;
1324*9880d681SAndroid Build Coastguard Worker   unsigned Reg = MI->getOperand(0).getReg();
1325*9880d681SAndroid Build Coastguard Worker   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1326*9880d681SAndroid Build Coastguard Worker     ImmDefMIs.insert(std::make_pair(Reg, MI));
1327*9880d681SAndroid Build Coastguard Worker     ImmDefRegs.insert(Reg);
1328*9880d681SAndroid Build Coastguard Worker     return true;
1329*9880d681SAndroid Build Coastguard Worker   }
1330*9880d681SAndroid Build Coastguard Worker 
1331*9880d681SAndroid Build Coastguard Worker   return false;
1332*9880d681SAndroid Build Coastguard Worker }
1333*9880d681SAndroid Build Coastguard Worker 
1334*9880d681SAndroid Build Coastguard Worker /// Try folding register operands that are defined by move immediate
1335*9880d681SAndroid Build Coastguard Worker /// instructions, i.e. a trivial constant folding optimization, if
1336*9880d681SAndroid Build Coastguard Worker /// and only if the def and use are in the same BB.
foldImmediate(MachineInstr * MI,MachineBasicBlock * MBB,SmallSet<unsigned,4> & ImmDefRegs,DenseMap<unsigned,MachineInstr * > & ImmDefMIs)1337*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::foldImmediate(
1338*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, MachineBasicBlock *MBB, SmallSet<unsigned, 4> &ImmDefRegs,
1339*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1340*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1341*9880d681SAndroid Build Coastguard Worker     MachineOperand &MO = MI->getOperand(i);
1342*9880d681SAndroid Build Coastguard Worker     if (!MO.isReg() || MO.isDef())
1343*9880d681SAndroid Build Coastguard Worker       continue;
1344*9880d681SAndroid Build Coastguard Worker     // Ignore dead implicit defs.
1345*9880d681SAndroid Build Coastguard Worker     if (MO.isImplicit() && MO.isDead())
1346*9880d681SAndroid Build Coastguard Worker       continue;
1347*9880d681SAndroid Build Coastguard Worker     unsigned Reg = MO.getReg();
1348*9880d681SAndroid Build Coastguard Worker     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1349*9880d681SAndroid Build Coastguard Worker       continue;
1350*9880d681SAndroid Build Coastguard Worker     if (ImmDefRegs.count(Reg) == 0)
1351*9880d681SAndroid Build Coastguard Worker       continue;
1352*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1353*9880d681SAndroid Build Coastguard Worker     assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1354*9880d681SAndroid Build Coastguard Worker     if (TII->FoldImmediate(*MI, *II->second, Reg, MRI)) {
1355*9880d681SAndroid Build Coastguard Worker       ++NumImmFold;
1356*9880d681SAndroid Build Coastguard Worker       return true;
1357*9880d681SAndroid Build Coastguard Worker     }
1358*9880d681SAndroid Build Coastguard Worker   }
1359*9880d681SAndroid Build Coastguard Worker   return false;
1360*9880d681SAndroid Build Coastguard Worker }
1361*9880d681SAndroid Build Coastguard Worker 
1362*9880d681SAndroid Build Coastguard Worker // FIXME: This is very simple and misses some cases which should be handled when
1363*9880d681SAndroid Build Coastguard Worker // motivating examples are found.
1364*9880d681SAndroid Build Coastguard Worker //
1365*9880d681SAndroid Build Coastguard Worker // The copy rewriting logic should look at uses as well as defs and be able to
1366*9880d681SAndroid Build Coastguard Worker // eliminate copies across blocks.
1367*9880d681SAndroid Build Coastguard Worker //
1368*9880d681SAndroid Build Coastguard Worker // Later copies that are subregister extracts will also not be eliminated since
1369*9880d681SAndroid Build Coastguard Worker // only the first copy is considered.
1370*9880d681SAndroid Build Coastguard Worker //
1371*9880d681SAndroid Build Coastguard Worker // e.g.
1372*9880d681SAndroid Build Coastguard Worker // %vreg1 = COPY %vreg0
1373*9880d681SAndroid Build Coastguard Worker // %vreg2 = COPY %vreg0:sub1
1374*9880d681SAndroid Build Coastguard Worker //
1375*9880d681SAndroid Build Coastguard Worker // Should replace %vreg2 uses with %vreg1:sub1
foldRedundantCopy(MachineInstr * MI,SmallSet<unsigned,4> & CopySrcRegs,DenseMap<unsigned,MachineInstr * > & CopyMIs)1376*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::foldRedundantCopy(
1377*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, SmallSet<unsigned, 4> &CopySrcRegs,
1378*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1379*9880d681SAndroid Build Coastguard Worker   assert(MI->isCopy() && "expected a COPY machine instruction");
1380*9880d681SAndroid Build Coastguard Worker 
1381*9880d681SAndroid Build Coastguard Worker   unsigned SrcReg = MI->getOperand(1).getReg();
1382*9880d681SAndroid Build Coastguard Worker   if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1383*9880d681SAndroid Build Coastguard Worker     return false;
1384*9880d681SAndroid Build Coastguard Worker 
1385*9880d681SAndroid Build Coastguard Worker   unsigned DstReg = MI->getOperand(0).getReg();
1386*9880d681SAndroid Build Coastguard Worker   if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1387*9880d681SAndroid Build Coastguard Worker     return false;
1388*9880d681SAndroid Build Coastguard Worker 
1389*9880d681SAndroid Build Coastguard Worker   if (CopySrcRegs.insert(SrcReg).second) {
1390*9880d681SAndroid Build Coastguard Worker     // First copy of this reg seen.
1391*9880d681SAndroid Build Coastguard Worker     CopyMIs.insert(std::make_pair(SrcReg, MI));
1392*9880d681SAndroid Build Coastguard Worker     return false;
1393*9880d681SAndroid Build Coastguard Worker   }
1394*9880d681SAndroid Build Coastguard Worker 
1395*9880d681SAndroid Build Coastguard Worker   MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1396*9880d681SAndroid Build Coastguard Worker 
1397*9880d681SAndroid Build Coastguard Worker   unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1398*9880d681SAndroid Build Coastguard Worker   unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1399*9880d681SAndroid Build Coastguard Worker 
1400*9880d681SAndroid Build Coastguard Worker   // Can't replace different subregister extracts.
1401*9880d681SAndroid Build Coastguard Worker   if (SrcSubReg != PrevSrcSubReg)
1402*9880d681SAndroid Build Coastguard Worker     return false;
1403*9880d681SAndroid Build Coastguard Worker 
1404*9880d681SAndroid Build Coastguard Worker   unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1405*9880d681SAndroid Build Coastguard Worker 
1406*9880d681SAndroid Build Coastguard Worker   // Only replace if the copy register class is the same.
1407*9880d681SAndroid Build Coastguard Worker   //
1408*9880d681SAndroid Build Coastguard Worker   // TODO: If we have multiple copies to different register classes, we may want
1409*9880d681SAndroid Build Coastguard Worker   // to track multiple copies of the same source register.
1410*9880d681SAndroid Build Coastguard Worker   if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1411*9880d681SAndroid Build Coastguard Worker     return false;
1412*9880d681SAndroid Build Coastguard Worker 
1413*9880d681SAndroid Build Coastguard Worker   MRI->replaceRegWith(DstReg, PrevDstReg);
1414*9880d681SAndroid Build Coastguard Worker 
1415*9880d681SAndroid Build Coastguard Worker   // Lifetime of the previous copy has been extended.
1416*9880d681SAndroid Build Coastguard Worker   MRI->clearKillFlags(PrevDstReg);
1417*9880d681SAndroid Build Coastguard Worker   return true;
1418*9880d681SAndroid Build Coastguard Worker }
1419*9880d681SAndroid Build Coastguard Worker 
isNAPhysCopy(unsigned Reg)1420*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1421*9880d681SAndroid Build Coastguard Worker   return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1422*9880d681SAndroid Build Coastguard Worker          !MRI->isAllocatable(Reg);
1423*9880d681SAndroid Build Coastguard Worker }
1424*9880d681SAndroid Build Coastguard Worker 
foldRedundantNAPhysCopy(MachineInstr * MI,DenseMap<unsigned,MachineInstr * > & NAPhysToVirtMIs)1425*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1426*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1427*9880d681SAndroid Build Coastguard Worker   assert(MI->isCopy() && "expected a COPY machine instruction");
1428*9880d681SAndroid Build Coastguard Worker 
1429*9880d681SAndroid Build Coastguard Worker   if (DisableNAPhysCopyOpt)
1430*9880d681SAndroid Build Coastguard Worker     return false;
1431*9880d681SAndroid Build Coastguard Worker 
1432*9880d681SAndroid Build Coastguard Worker   unsigned DstReg = MI->getOperand(0).getReg();
1433*9880d681SAndroid Build Coastguard Worker   unsigned SrcReg = MI->getOperand(1).getReg();
1434*9880d681SAndroid Build Coastguard Worker   if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1435*9880d681SAndroid Build Coastguard Worker     // %vreg = COPY %PHYSREG
1436*9880d681SAndroid Build Coastguard Worker     // Avoid using a datastructure which can track multiple live non-allocatable
1437*9880d681SAndroid Build Coastguard Worker     // phys->virt copies since LLVM doesn't seem to do this.
1438*9880d681SAndroid Build Coastguard Worker     NAPhysToVirtMIs.insert({SrcReg, MI});
1439*9880d681SAndroid Build Coastguard Worker     return false;
1440*9880d681SAndroid Build Coastguard Worker   }
1441*9880d681SAndroid Build Coastguard Worker 
1442*9880d681SAndroid Build Coastguard Worker   if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1443*9880d681SAndroid Build Coastguard Worker     return false;
1444*9880d681SAndroid Build Coastguard Worker 
1445*9880d681SAndroid Build Coastguard Worker   // %PHYSREG = COPY %vreg
1446*9880d681SAndroid Build Coastguard Worker   auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1447*9880d681SAndroid Build Coastguard Worker   if (PrevCopy == NAPhysToVirtMIs.end()) {
1448*9880d681SAndroid Build Coastguard Worker     // We can't remove the copy: there was an intervening clobber of the
1449*9880d681SAndroid Build Coastguard Worker     // non-allocatable physical register after the copy to virtual.
1450*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI
1451*9880d681SAndroid Build Coastguard Worker                  << '\n');
1452*9880d681SAndroid Build Coastguard Worker     return false;
1453*9880d681SAndroid Build Coastguard Worker   }
1454*9880d681SAndroid Build Coastguard Worker 
1455*9880d681SAndroid Build Coastguard Worker   unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1456*9880d681SAndroid Build Coastguard Worker   if (PrevDstReg == SrcReg) {
1457*9880d681SAndroid Build Coastguard Worker     // Remove the virt->phys copy: we saw the virtual register definition, and
1458*9880d681SAndroid Build Coastguard Worker     // the non-allocatable physical register's state hasn't changed since then.
1459*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n');
1460*9880d681SAndroid Build Coastguard Worker     ++NumNAPhysCopies;
1461*9880d681SAndroid Build Coastguard Worker     return true;
1462*9880d681SAndroid Build Coastguard Worker   }
1463*9880d681SAndroid Build Coastguard Worker 
1464*9880d681SAndroid Build Coastguard Worker   // Potential missed optimization opportunity: we saw a different virtual
1465*9880d681SAndroid Build Coastguard Worker   // register get a copy of the non-allocatable physical register, and we only
1466*9880d681SAndroid Build Coastguard Worker   // track one such copy. Avoid getting confused by this new non-allocatable
1467*9880d681SAndroid Build Coastguard Worker   // physical register definition, and remove it from the tracked copies.
1468*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n');
1469*9880d681SAndroid Build Coastguard Worker   NAPhysToVirtMIs.erase(PrevCopy);
1470*9880d681SAndroid Build Coastguard Worker   return false;
1471*9880d681SAndroid Build Coastguard Worker }
1472*9880d681SAndroid Build Coastguard Worker 
runOnMachineFunction(MachineFunction & MF)1473*9880d681SAndroid Build Coastguard Worker bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1474*9880d681SAndroid Build Coastguard Worker   if (skipFunction(*MF.getFunction()))
1475*9880d681SAndroid Build Coastguard Worker     return false;
1476*9880d681SAndroid Build Coastguard Worker 
1477*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1478*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1479*9880d681SAndroid Build Coastguard Worker 
1480*9880d681SAndroid Build Coastguard Worker   if (DisablePeephole)
1481*9880d681SAndroid Build Coastguard Worker     return false;
1482*9880d681SAndroid Build Coastguard Worker 
1483*9880d681SAndroid Build Coastguard Worker   TII = MF.getSubtarget().getInstrInfo();
1484*9880d681SAndroid Build Coastguard Worker   TRI = MF.getSubtarget().getRegisterInfo();
1485*9880d681SAndroid Build Coastguard Worker   MRI = &MF.getRegInfo();
1486*9880d681SAndroid Build Coastguard Worker   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1487*9880d681SAndroid Build Coastguard Worker 
1488*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
1489*9880d681SAndroid Build Coastguard Worker 
1490*9880d681SAndroid Build Coastguard Worker   for (MachineBasicBlock &MBB : MF) {
1491*9880d681SAndroid Build Coastguard Worker     bool SeenMoveImm = false;
1492*9880d681SAndroid Build Coastguard Worker 
1493*9880d681SAndroid Build Coastguard Worker     // During this forward scan, at some point it needs to answer the question
1494*9880d681SAndroid Build Coastguard Worker     // "given a pointer to an MI in the current BB, is it located before or
1495*9880d681SAndroid Build Coastguard Worker     // after the current instruction".
1496*9880d681SAndroid Build Coastguard Worker     // To perform this, the following set keeps track of the MIs already seen
1497*9880d681SAndroid Build Coastguard Worker     // during the scan, if a MI is not in the set, it is assumed to be located
1498*9880d681SAndroid Build Coastguard Worker     // after. Newly created MIs have to be inserted in the set as well.
1499*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<MachineInstr*, 16> LocalMIs;
1500*9880d681SAndroid Build Coastguard Worker     SmallSet<unsigned, 4> ImmDefRegs;
1501*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1502*9880d681SAndroid Build Coastguard Worker     SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1503*9880d681SAndroid Build Coastguard Worker 
1504*9880d681SAndroid Build Coastguard Worker     // Track when a non-allocatable physical register is copied to a virtual
1505*9880d681SAndroid Build Coastguard Worker     // register so that useless moves can be removed.
1506*9880d681SAndroid Build Coastguard Worker     //
1507*9880d681SAndroid Build Coastguard Worker     // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG`
1508*9880d681SAndroid Build Coastguard Worker     // without any intervening re-definition of %PHYSREG.
1509*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1510*9880d681SAndroid Build Coastguard Worker 
1511*9880d681SAndroid Build Coastguard Worker     // Set of virtual registers that are copied from.
1512*9880d681SAndroid Build Coastguard Worker     SmallSet<unsigned, 4> CopySrcRegs;
1513*9880d681SAndroid Build Coastguard Worker     DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1514*9880d681SAndroid Build Coastguard Worker 
1515*9880d681SAndroid Build Coastguard Worker     for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1516*9880d681SAndroid Build Coastguard Worker          MII != MIE; ) {
1517*9880d681SAndroid Build Coastguard Worker       MachineInstr *MI = &*MII;
1518*9880d681SAndroid Build Coastguard Worker       // We may be erasing MI below, increment MII now.
1519*9880d681SAndroid Build Coastguard Worker       ++MII;
1520*9880d681SAndroid Build Coastguard Worker       LocalMIs.insert(MI);
1521*9880d681SAndroid Build Coastguard Worker 
1522*9880d681SAndroid Build Coastguard Worker       // Skip debug values. They should not affect this peephole optimization.
1523*9880d681SAndroid Build Coastguard Worker       if (MI->isDebugValue())
1524*9880d681SAndroid Build Coastguard Worker           continue;
1525*9880d681SAndroid Build Coastguard Worker 
1526*9880d681SAndroid Build Coastguard Worker       // If we run into an instruction we can't fold across, discard
1527*9880d681SAndroid Build Coastguard Worker       // the load candidates.
1528*9880d681SAndroid Build Coastguard Worker       if (MI->isLoadFoldBarrier())
1529*9880d681SAndroid Build Coastguard Worker         FoldAsLoadDefCandidates.clear();
1530*9880d681SAndroid Build Coastguard Worker 
1531*9880d681SAndroid Build Coastguard Worker       if (MI->isPosition() || MI->isPHI())
1532*9880d681SAndroid Build Coastguard Worker         continue;
1533*9880d681SAndroid Build Coastguard Worker 
1534*9880d681SAndroid Build Coastguard Worker       if (!MI->isCopy()) {
1535*9880d681SAndroid Build Coastguard Worker         for (const auto &Op : MI->operands()) {
1536*9880d681SAndroid Build Coastguard Worker           // Visit all operands: definitions can be implicit or explicit.
1537*9880d681SAndroid Build Coastguard Worker           if (Op.isReg()) {
1538*9880d681SAndroid Build Coastguard Worker             unsigned Reg = Op.getReg();
1539*9880d681SAndroid Build Coastguard Worker             if (Op.isDef() && isNAPhysCopy(Reg)) {
1540*9880d681SAndroid Build Coastguard Worker               const auto &Def = NAPhysToVirtMIs.find(Reg);
1541*9880d681SAndroid Build Coastguard Worker               if (Def != NAPhysToVirtMIs.end()) {
1542*9880d681SAndroid Build Coastguard Worker                 // A new definition of the non-allocatable physical register
1543*9880d681SAndroid Build Coastguard Worker                 // invalidates previous copies.
1544*9880d681SAndroid Build Coastguard Worker                 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1545*9880d681SAndroid Build Coastguard Worker                              << '\n');
1546*9880d681SAndroid Build Coastguard Worker                 NAPhysToVirtMIs.erase(Def);
1547*9880d681SAndroid Build Coastguard Worker               }
1548*9880d681SAndroid Build Coastguard Worker             }
1549*9880d681SAndroid Build Coastguard Worker           } else if (Op.isRegMask()) {
1550*9880d681SAndroid Build Coastguard Worker             const uint32_t *RegMask = Op.getRegMask();
1551*9880d681SAndroid Build Coastguard Worker             for (auto &RegMI : NAPhysToVirtMIs) {
1552*9880d681SAndroid Build Coastguard Worker               unsigned Def = RegMI.first;
1553*9880d681SAndroid Build Coastguard Worker               if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1554*9880d681SAndroid Build Coastguard Worker                 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1555*9880d681SAndroid Build Coastguard Worker                              << '\n');
1556*9880d681SAndroid Build Coastguard Worker                 NAPhysToVirtMIs.erase(Def);
1557*9880d681SAndroid Build Coastguard Worker               }
1558*9880d681SAndroid Build Coastguard Worker             }
1559*9880d681SAndroid Build Coastguard Worker           }
1560*9880d681SAndroid Build Coastguard Worker         }
1561*9880d681SAndroid Build Coastguard Worker       }
1562*9880d681SAndroid Build Coastguard Worker 
1563*9880d681SAndroid Build Coastguard Worker       if (MI->isImplicitDef() || MI->isKill())
1564*9880d681SAndroid Build Coastguard Worker         continue;
1565*9880d681SAndroid Build Coastguard Worker 
1566*9880d681SAndroid Build Coastguard Worker       if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1567*9880d681SAndroid Build Coastguard Worker         // Blow away all non-allocatable physical registers knowledge since we
1568*9880d681SAndroid Build Coastguard Worker         // don't know what's correct anymore.
1569*9880d681SAndroid Build Coastguard Worker         //
1570*9880d681SAndroid Build Coastguard Worker         // FIXME: handle explicit asm clobbers.
1571*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI
1572*9880d681SAndroid Build Coastguard Worker                      << '\n');
1573*9880d681SAndroid Build Coastguard Worker         NAPhysToVirtMIs.clear();
1574*9880d681SAndroid Build Coastguard Worker         continue;
1575*9880d681SAndroid Build Coastguard Worker       }
1576*9880d681SAndroid Build Coastguard Worker 
1577*9880d681SAndroid Build Coastguard Worker       if ((isUncoalescableCopy(*MI) &&
1578*9880d681SAndroid Build Coastguard Worker            optimizeUncoalescableCopy(MI, LocalMIs)) ||
1579*9880d681SAndroid Build Coastguard Worker           (MI->isCompare() && optimizeCmpInstr(MI, &MBB)) ||
1580*9880d681SAndroid Build Coastguard Worker           (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1581*9880d681SAndroid Build Coastguard Worker         // MI is deleted.
1582*9880d681SAndroid Build Coastguard Worker         LocalMIs.erase(MI);
1583*9880d681SAndroid Build Coastguard Worker         Changed = true;
1584*9880d681SAndroid Build Coastguard Worker         continue;
1585*9880d681SAndroid Build Coastguard Worker       }
1586*9880d681SAndroid Build Coastguard Worker 
1587*9880d681SAndroid Build Coastguard Worker       if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1588*9880d681SAndroid Build Coastguard Worker         Changed = true;
1589*9880d681SAndroid Build Coastguard Worker         continue;
1590*9880d681SAndroid Build Coastguard Worker       }
1591*9880d681SAndroid Build Coastguard Worker 
1592*9880d681SAndroid Build Coastguard Worker       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1593*9880d681SAndroid Build Coastguard Worker         // MI is just rewritten.
1594*9880d681SAndroid Build Coastguard Worker         Changed = true;
1595*9880d681SAndroid Build Coastguard Worker         continue;
1596*9880d681SAndroid Build Coastguard Worker       }
1597*9880d681SAndroid Build Coastguard Worker 
1598*9880d681SAndroid Build Coastguard Worker       if (MI->isCopy() &&
1599*9880d681SAndroid Build Coastguard Worker           (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1600*9880d681SAndroid Build Coastguard Worker            foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
1601*9880d681SAndroid Build Coastguard Worker         LocalMIs.erase(MI);
1602*9880d681SAndroid Build Coastguard Worker         MI->eraseFromParent();
1603*9880d681SAndroid Build Coastguard Worker         Changed = true;
1604*9880d681SAndroid Build Coastguard Worker         continue;
1605*9880d681SAndroid Build Coastguard Worker       }
1606*9880d681SAndroid Build Coastguard Worker 
1607*9880d681SAndroid Build Coastguard Worker       if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1608*9880d681SAndroid Build Coastguard Worker         SeenMoveImm = true;
1609*9880d681SAndroid Build Coastguard Worker       } else {
1610*9880d681SAndroid Build Coastguard Worker         Changed |= optimizeExtInstr(MI, &MBB, LocalMIs);
1611*9880d681SAndroid Build Coastguard Worker         // optimizeExtInstr might have created new instructions after MI
1612*9880d681SAndroid Build Coastguard Worker         // and before the already incremented MII. Adjust MII so that the
1613*9880d681SAndroid Build Coastguard Worker         // next iteration sees the new instructions.
1614*9880d681SAndroid Build Coastguard Worker         MII = MI;
1615*9880d681SAndroid Build Coastguard Worker         ++MII;
1616*9880d681SAndroid Build Coastguard Worker         if (SeenMoveImm)
1617*9880d681SAndroid Build Coastguard Worker           Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs);
1618*9880d681SAndroid Build Coastguard Worker       }
1619*9880d681SAndroid Build Coastguard Worker 
1620*9880d681SAndroid Build Coastguard Worker       // Check whether MI is a load candidate for folding into a later
1621*9880d681SAndroid Build Coastguard Worker       // instruction. If MI is not a candidate, check whether we can fold an
1622*9880d681SAndroid Build Coastguard Worker       // earlier load into MI.
1623*9880d681SAndroid Build Coastguard Worker       if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1624*9880d681SAndroid Build Coastguard Worker           !FoldAsLoadDefCandidates.empty()) {
1625*9880d681SAndroid Build Coastguard Worker         const MCInstrDesc &MIDesc = MI->getDesc();
1626*9880d681SAndroid Build Coastguard Worker         for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1627*9880d681SAndroid Build Coastguard Worker              ++i) {
1628*9880d681SAndroid Build Coastguard Worker           const MachineOperand &MOp = MI->getOperand(i);
1629*9880d681SAndroid Build Coastguard Worker           if (!MOp.isReg())
1630*9880d681SAndroid Build Coastguard Worker             continue;
1631*9880d681SAndroid Build Coastguard Worker           unsigned FoldAsLoadDefReg = MOp.getReg();
1632*9880d681SAndroid Build Coastguard Worker           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1633*9880d681SAndroid Build Coastguard Worker             // We need to fold load after optimizeCmpInstr, since
1634*9880d681SAndroid Build Coastguard Worker             // optimizeCmpInstr can enable folding by converting SUB to CMP.
1635*9880d681SAndroid Build Coastguard Worker             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1636*9880d681SAndroid Build Coastguard Worker             // we need it for markUsesInDebugValueAsUndef().
1637*9880d681SAndroid Build Coastguard Worker             unsigned FoldedReg = FoldAsLoadDefReg;
1638*9880d681SAndroid Build Coastguard Worker             MachineInstr *DefMI = nullptr;
1639*9880d681SAndroid Build Coastguard Worker             if (MachineInstr *FoldMI =
1640*9880d681SAndroid Build Coastguard Worker                     TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
1641*9880d681SAndroid Build Coastguard Worker               // Update LocalMIs since we replaced MI with FoldMI and deleted
1642*9880d681SAndroid Build Coastguard Worker               // DefMI.
1643*9880d681SAndroid Build Coastguard Worker               DEBUG(dbgs() << "Replacing: " << *MI);
1644*9880d681SAndroid Build Coastguard Worker               DEBUG(dbgs() << "     With: " << *FoldMI);
1645*9880d681SAndroid Build Coastguard Worker               LocalMIs.erase(MI);
1646*9880d681SAndroid Build Coastguard Worker               LocalMIs.erase(DefMI);
1647*9880d681SAndroid Build Coastguard Worker               LocalMIs.insert(FoldMI);
1648*9880d681SAndroid Build Coastguard Worker               MI->eraseFromParent();
1649*9880d681SAndroid Build Coastguard Worker               DefMI->eraseFromParent();
1650*9880d681SAndroid Build Coastguard Worker               MRI->markUsesInDebugValueAsUndef(FoldedReg);
1651*9880d681SAndroid Build Coastguard Worker               FoldAsLoadDefCandidates.erase(FoldedReg);
1652*9880d681SAndroid Build Coastguard Worker               ++NumLoadFold;
1653*9880d681SAndroid Build Coastguard Worker               // MI is replaced with FoldMI.
1654*9880d681SAndroid Build Coastguard Worker               Changed = true;
1655*9880d681SAndroid Build Coastguard Worker               break;
1656*9880d681SAndroid Build Coastguard Worker             }
1657*9880d681SAndroid Build Coastguard Worker           }
1658*9880d681SAndroid Build Coastguard Worker         }
1659*9880d681SAndroid Build Coastguard Worker       }
1660*9880d681SAndroid Build Coastguard Worker     }
1661*9880d681SAndroid Build Coastguard Worker   }
1662*9880d681SAndroid Build Coastguard Worker 
1663*9880d681SAndroid Build Coastguard Worker   return Changed;
1664*9880d681SAndroid Build Coastguard Worker }
1665*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromCopy()1666*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1667*9880d681SAndroid Build Coastguard Worker   assert(Def->isCopy() && "Invalid definition");
1668*9880d681SAndroid Build Coastguard Worker   // Copy instruction are supposed to be: Def = Src.
1669*9880d681SAndroid Build Coastguard Worker   // If someone breaks this assumption, bad things will happen everywhere.
1670*9880d681SAndroid Build Coastguard Worker   assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1671*9880d681SAndroid Build Coastguard Worker 
1672*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1673*9880d681SAndroid Build Coastguard Worker     // If we look for a different subreg, it means we want a subreg of src.
1674*9880d681SAndroid Build Coastguard Worker     // Bails as we do not support composing subregs yet.
1675*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1676*9880d681SAndroid Build Coastguard Worker   // Otherwise, we want the whole source.
1677*9880d681SAndroid Build Coastguard Worker   const MachineOperand &Src = Def->getOperand(1);
1678*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1679*9880d681SAndroid Build Coastguard Worker }
1680*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromBitcast()1681*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1682*9880d681SAndroid Build Coastguard Worker   assert(Def->isBitcast() && "Invalid definition");
1683*9880d681SAndroid Build Coastguard Worker 
1684*9880d681SAndroid Build Coastguard Worker   // Bail if there are effects that a plain copy will not expose.
1685*9880d681SAndroid Build Coastguard Worker   if (Def->hasUnmodeledSideEffects())
1686*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1687*9880d681SAndroid Build Coastguard Worker 
1688*9880d681SAndroid Build Coastguard Worker   // Bitcasts with more than one def are not supported.
1689*9880d681SAndroid Build Coastguard Worker   if (Def->getDesc().getNumDefs() != 1)
1690*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1691*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1692*9880d681SAndroid Build Coastguard Worker     // If we look for a different subreg, it means we want a subreg of the src.
1693*9880d681SAndroid Build Coastguard Worker     // Bails as we do not support composing subregs yet.
1694*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1695*9880d681SAndroid Build Coastguard Worker 
1696*9880d681SAndroid Build Coastguard Worker   unsigned SrcIdx = Def->getNumOperands();
1697*9880d681SAndroid Build Coastguard Worker   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1698*9880d681SAndroid Build Coastguard Worker        ++OpIdx) {
1699*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MO = Def->getOperand(OpIdx);
1700*9880d681SAndroid Build Coastguard Worker     if (!MO.isReg() || !MO.getReg())
1701*9880d681SAndroid Build Coastguard Worker       continue;
1702*9880d681SAndroid Build Coastguard Worker     // Ignore dead implicit defs.
1703*9880d681SAndroid Build Coastguard Worker     if (MO.isImplicit() && MO.isDead())
1704*9880d681SAndroid Build Coastguard Worker       continue;
1705*9880d681SAndroid Build Coastguard Worker     assert(!MO.isDef() && "We should have skipped all the definitions by now");
1706*9880d681SAndroid Build Coastguard Worker     if (SrcIdx != EndOpIdx)
1707*9880d681SAndroid Build Coastguard Worker       // Multiple sources?
1708*9880d681SAndroid Build Coastguard Worker       return ValueTrackerResult();
1709*9880d681SAndroid Build Coastguard Worker     SrcIdx = OpIdx;
1710*9880d681SAndroid Build Coastguard Worker   }
1711*9880d681SAndroid Build Coastguard Worker   const MachineOperand &Src = Def->getOperand(SrcIdx);
1712*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1713*9880d681SAndroid Build Coastguard Worker }
1714*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromRegSequence()1715*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1716*9880d681SAndroid Build Coastguard Worker   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1717*9880d681SAndroid Build Coastguard Worker          "Invalid definition");
1718*9880d681SAndroid Build Coastguard Worker 
1719*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(DefIdx).getSubReg())
1720*9880d681SAndroid Build Coastguard Worker     // If we are composing subregs, bail out.
1721*9880d681SAndroid Build Coastguard Worker     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1722*9880d681SAndroid Build Coastguard Worker     // This should almost never happen as the SSA property is tracked at
1723*9880d681SAndroid Build Coastguard Worker     // the register level (as opposed to the subreg level).
1724*9880d681SAndroid Build Coastguard Worker     // I.e.,
1725*9880d681SAndroid Build Coastguard Worker     // Def.sub0 =
1726*9880d681SAndroid Build Coastguard Worker     // Def.sub1 =
1727*9880d681SAndroid Build Coastguard Worker     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1728*9880d681SAndroid Build Coastguard Worker     // Def. Thus, it must not be generated.
1729*9880d681SAndroid Build Coastguard Worker     // However, some code could theoretically generates a single
1730*9880d681SAndroid Build Coastguard Worker     // Def.sub0 (i.e, not defining the other subregs) and we would
1731*9880d681SAndroid Build Coastguard Worker     // have this case.
1732*9880d681SAndroid Build Coastguard Worker     // If we can ascertain (or force) that this never happens, we could
1733*9880d681SAndroid Build Coastguard Worker     // turn that into an assertion.
1734*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1735*9880d681SAndroid Build Coastguard Worker 
1736*9880d681SAndroid Build Coastguard Worker   if (!TII)
1737*9880d681SAndroid Build Coastguard Worker     // We could handle the REG_SEQUENCE here, but we do not want to
1738*9880d681SAndroid Build Coastguard Worker     // duplicate the code from the generic TII.
1739*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1740*9880d681SAndroid Build Coastguard Worker 
1741*9880d681SAndroid Build Coastguard Worker   SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1742*9880d681SAndroid Build Coastguard Worker   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1743*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1744*9880d681SAndroid Build Coastguard Worker 
1745*9880d681SAndroid Build Coastguard Worker   // We are looking at:
1746*9880d681SAndroid Build Coastguard Worker   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1747*9880d681SAndroid Build Coastguard Worker   // Check if one of the operand defines the subreg we are interested in.
1748*9880d681SAndroid Build Coastguard Worker   for (auto &RegSeqInput : RegSeqInputRegs) {
1749*9880d681SAndroid Build Coastguard Worker     if (RegSeqInput.SubIdx == DefSubReg) {
1750*9880d681SAndroid Build Coastguard Worker       if (RegSeqInput.SubReg)
1751*9880d681SAndroid Build Coastguard Worker         // Bail if we have to compose sub registers.
1752*9880d681SAndroid Build Coastguard Worker         return ValueTrackerResult();
1753*9880d681SAndroid Build Coastguard Worker 
1754*9880d681SAndroid Build Coastguard Worker       return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1755*9880d681SAndroid Build Coastguard Worker     }
1756*9880d681SAndroid Build Coastguard Worker   }
1757*9880d681SAndroid Build Coastguard Worker 
1758*9880d681SAndroid Build Coastguard Worker   // If the subreg we are tracking is super-defined by another subreg,
1759*9880d681SAndroid Build Coastguard Worker   // we could follow this value. However, this would require to compose
1760*9880d681SAndroid Build Coastguard Worker   // the subreg and we do not do that for now.
1761*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult();
1762*9880d681SAndroid Build Coastguard Worker }
1763*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromInsertSubreg()1764*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1765*9880d681SAndroid Build Coastguard Worker   assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1766*9880d681SAndroid Build Coastguard Worker          "Invalid definition");
1767*9880d681SAndroid Build Coastguard Worker 
1768*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(DefIdx).getSubReg())
1769*9880d681SAndroid Build Coastguard Worker     // If we are composing subreg, bail out.
1770*9880d681SAndroid Build Coastguard Worker     // Same remark as getNextSourceFromRegSequence.
1771*9880d681SAndroid Build Coastguard Worker     // I.e., this may be turned into an assert.
1772*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1773*9880d681SAndroid Build Coastguard Worker 
1774*9880d681SAndroid Build Coastguard Worker   if (!TII)
1775*9880d681SAndroid Build Coastguard Worker     // We could handle the REG_SEQUENCE here, but we do not want to
1776*9880d681SAndroid Build Coastguard Worker     // duplicate the code from the generic TII.
1777*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1778*9880d681SAndroid Build Coastguard Worker 
1779*9880d681SAndroid Build Coastguard Worker   TargetInstrInfo::RegSubRegPair BaseReg;
1780*9880d681SAndroid Build Coastguard Worker   TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1781*9880d681SAndroid Build Coastguard Worker   if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1782*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1783*9880d681SAndroid Build Coastguard Worker 
1784*9880d681SAndroid Build Coastguard Worker   // We are looking at:
1785*9880d681SAndroid Build Coastguard Worker   // Def = INSERT_SUBREG v0, v1, sub1
1786*9880d681SAndroid Build Coastguard Worker   // There are two cases:
1787*9880d681SAndroid Build Coastguard Worker   // 1. DefSubReg == sub1, get v1.
1788*9880d681SAndroid Build Coastguard Worker   // 2. DefSubReg != sub1, the value may be available through v0.
1789*9880d681SAndroid Build Coastguard Worker 
1790*9880d681SAndroid Build Coastguard Worker   // #1 Check if the inserted register matches the required sub index.
1791*9880d681SAndroid Build Coastguard Worker   if (InsertedReg.SubIdx == DefSubReg) {
1792*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1793*9880d681SAndroid Build Coastguard Worker   }
1794*9880d681SAndroid Build Coastguard Worker   // #2 Otherwise, if the sub register we are looking for is not partial
1795*9880d681SAndroid Build Coastguard Worker   // defined by the inserted element, we can look through the main
1796*9880d681SAndroid Build Coastguard Worker   // register (v0).
1797*9880d681SAndroid Build Coastguard Worker   const MachineOperand &MODef = Def->getOperand(DefIdx);
1798*9880d681SAndroid Build Coastguard Worker   // If the result register (Def) and the base register (v0) do not
1799*9880d681SAndroid Build Coastguard Worker   // have the same register class or if we have to compose
1800*9880d681SAndroid Build Coastguard Worker   // subregisters, bail out.
1801*9880d681SAndroid Build Coastguard Worker   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1802*9880d681SAndroid Build Coastguard Worker       BaseReg.SubReg)
1803*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1804*9880d681SAndroid Build Coastguard Worker 
1805*9880d681SAndroid Build Coastguard Worker   // Get the TRI and check if the inserted sub-register overlaps with the
1806*9880d681SAndroid Build Coastguard Worker   // sub-register we are tracking.
1807*9880d681SAndroid Build Coastguard Worker   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1808*9880d681SAndroid Build Coastguard Worker   if (!TRI ||
1809*9880d681SAndroid Build Coastguard Worker       (TRI->getSubRegIndexLaneMask(DefSubReg) &
1810*9880d681SAndroid Build Coastguard Worker        TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1811*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1812*9880d681SAndroid Build Coastguard Worker   // At this point, the value is available in v0 via the same subreg
1813*9880d681SAndroid Build Coastguard Worker   // we used for Def.
1814*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1815*9880d681SAndroid Build Coastguard Worker }
1816*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromExtractSubreg()1817*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1818*9880d681SAndroid Build Coastguard Worker   assert((Def->isExtractSubreg() ||
1819*9880d681SAndroid Build Coastguard Worker           Def->isExtractSubregLike()) && "Invalid definition");
1820*9880d681SAndroid Build Coastguard Worker   // We are looking at:
1821*9880d681SAndroid Build Coastguard Worker   // Def = EXTRACT_SUBREG v0, sub0
1822*9880d681SAndroid Build Coastguard Worker 
1823*9880d681SAndroid Build Coastguard Worker   // Bail if we have to compose sub registers.
1824*9880d681SAndroid Build Coastguard Worker   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1825*9880d681SAndroid Build Coastguard Worker   if (DefSubReg)
1826*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1827*9880d681SAndroid Build Coastguard Worker 
1828*9880d681SAndroid Build Coastguard Worker   if (!TII)
1829*9880d681SAndroid Build Coastguard Worker     // We could handle the EXTRACT_SUBREG here, but we do not want to
1830*9880d681SAndroid Build Coastguard Worker     // duplicate the code from the generic TII.
1831*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1832*9880d681SAndroid Build Coastguard Worker 
1833*9880d681SAndroid Build Coastguard Worker   TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1834*9880d681SAndroid Build Coastguard Worker   if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1835*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1836*9880d681SAndroid Build Coastguard Worker 
1837*9880d681SAndroid Build Coastguard Worker   // Bail if we have to compose sub registers.
1838*9880d681SAndroid Build Coastguard Worker   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1839*9880d681SAndroid Build Coastguard Worker   if (ExtractSubregInputReg.SubReg)
1840*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1841*9880d681SAndroid Build Coastguard Worker   // Otherwise, the value is available in the v0.sub0.
1842*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult(ExtractSubregInputReg.Reg,
1843*9880d681SAndroid Build Coastguard Worker                             ExtractSubregInputReg.SubIdx);
1844*9880d681SAndroid Build Coastguard Worker }
1845*9880d681SAndroid Build Coastguard Worker 
getNextSourceFromSubregToReg()1846*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
1847*9880d681SAndroid Build Coastguard Worker   assert(Def->isSubregToReg() && "Invalid definition");
1848*9880d681SAndroid Build Coastguard Worker   // We are looking at:
1849*9880d681SAndroid Build Coastguard Worker   // Def = SUBREG_TO_REG Imm, v0, sub0
1850*9880d681SAndroid Build Coastguard Worker 
1851*9880d681SAndroid Build Coastguard Worker   // Bail if we have to compose sub registers.
1852*9880d681SAndroid Build Coastguard Worker   // If DefSubReg != sub0, we would have to check that all the bits
1853*9880d681SAndroid Build Coastguard Worker   // we track are included in sub0 and if yes, we would have to
1854*9880d681SAndroid Build Coastguard Worker   // determine the right subreg in v0.
1855*9880d681SAndroid Build Coastguard Worker   if (DefSubReg != Def->getOperand(3).getImm())
1856*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1857*9880d681SAndroid Build Coastguard Worker   // Bail if we have to compose sub registers.
1858*9880d681SAndroid Build Coastguard Worker   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1859*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(2).getSubReg())
1860*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1861*9880d681SAndroid Build Coastguard Worker 
1862*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult(Def->getOperand(2).getReg(),
1863*9880d681SAndroid Build Coastguard Worker                             Def->getOperand(3).getImm());
1864*9880d681SAndroid Build Coastguard Worker }
1865*9880d681SAndroid Build Coastguard Worker 
1866*9880d681SAndroid Build Coastguard Worker /// \brief Explore each PHI incoming operand and return its sources
getNextSourceFromPHI()1867*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1868*9880d681SAndroid Build Coastguard Worker   assert(Def->isPHI() && "Invalid definition");
1869*9880d681SAndroid Build Coastguard Worker   ValueTrackerResult Res;
1870*9880d681SAndroid Build Coastguard Worker 
1871*9880d681SAndroid Build Coastguard Worker   // If we look for a different subreg, bail as we do not support composing
1872*9880d681SAndroid Build Coastguard Worker   // subregs yet.
1873*9880d681SAndroid Build Coastguard Worker   if (Def->getOperand(0).getSubReg() != DefSubReg)
1874*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1875*9880d681SAndroid Build Coastguard Worker 
1876*9880d681SAndroid Build Coastguard Worker   // Return all register sources for PHI instructions.
1877*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1878*9880d681SAndroid Build Coastguard Worker     auto &MO = Def->getOperand(i);
1879*9880d681SAndroid Build Coastguard Worker     assert(MO.isReg() && "Invalid PHI instruction");
1880*9880d681SAndroid Build Coastguard Worker     Res.addSource(MO.getReg(), MO.getSubReg());
1881*9880d681SAndroid Build Coastguard Worker   }
1882*9880d681SAndroid Build Coastguard Worker 
1883*9880d681SAndroid Build Coastguard Worker   return Res;
1884*9880d681SAndroid Build Coastguard Worker }
1885*9880d681SAndroid Build Coastguard Worker 
getNextSourceImpl()1886*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSourceImpl() {
1887*9880d681SAndroid Build Coastguard Worker   assert(Def && "This method needs a valid definition");
1888*9880d681SAndroid Build Coastguard Worker 
1889*9880d681SAndroid Build Coastguard Worker   assert(((Def->getOperand(DefIdx).isDef() &&
1890*9880d681SAndroid Build Coastguard Worker            (DefIdx < Def->getDesc().getNumDefs() ||
1891*9880d681SAndroid Build Coastguard Worker             Def->getDesc().isVariadic())) ||
1892*9880d681SAndroid Build Coastguard Worker           Def->getOperand(DefIdx).isImplicit()) &&
1893*9880d681SAndroid Build Coastguard Worker          "Invalid DefIdx");
1894*9880d681SAndroid Build Coastguard Worker   if (Def->isCopy())
1895*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromCopy();
1896*9880d681SAndroid Build Coastguard Worker   if (Def->isBitcast())
1897*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromBitcast();
1898*9880d681SAndroid Build Coastguard Worker   // All the remaining cases involve "complex" instructions.
1899*9880d681SAndroid Build Coastguard Worker   // Bail if we did not ask for the advanced tracking.
1900*9880d681SAndroid Build Coastguard Worker   if (!UseAdvancedTracking)
1901*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1902*9880d681SAndroid Build Coastguard Worker   if (Def->isRegSequence() || Def->isRegSequenceLike())
1903*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromRegSequence();
1904*9880d681SAndroid Build Coastguard Worker   if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1905*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromInsertSubreg();
1906*9880d681SAndroid Build Coastguard Worker   if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1907*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromExtractSubreg();
1908*9880d681SAndroid Build Coastguard Worker   if (Def->isSubregToReg())
1909*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromSubregToReg();
1910*9880d681SAndroid Build Coastguard Worker   if (Def->isPHI())
1911*9880d681SAndroid Build Coastguard Worker     return getNextSourceFromPHI();
1912*9880d681SAndroid Build Coastguard Worker   return ValueTrackerResult();
1913*9880d681SAndroid Build Coastguard Worker }
1914*9880d681SAndroid Build Coastguard Worker 
getNextSource()1915*9880d681SAndroid Build Coastguard Worker ValueTrackerResult ValueTracker::getNextSource() {
1916*9880d681SAndroid Build Coastguard Worker   // If we reach a point where we cannot move up in the use-def chain,
1917*9880d681SAndroid Build Coastguard Worker   // there is nothing we can get.
1918*9880d681SAndroid Build Coastguard Worker   if (!Def)
1919*9880d681SAndroid Build Coastguard Worker     return ValueTrackerResult();
1920*9880d681SAndroid Build Coastguard Worker 
1921*9880d681SAndroid Build Coastguard Worker   ValueTrackerResult Res = getNextSourceImpl();
1922*9880d681SAndroid Build Coastguard Worker   if (Res.isValid()) {
1923*9880d681SAndroid Build Coastguard Worker     // Update definition, definition index, and subregister for the
1924*9880d681SAndroid Build Coastguard Worker     // next call of getNextSource.
1925*9880d681SAndroid Build Coastguard Worker     // Update the current register.
1926*9880d681SAndroid Build Coastguard Worker     bool OneRegSrc = Res.getNumSources() == 1;
1927*9880d681SAndroid Build Coastguard Worker     if (OneRegSrc)
1928*9880d681SAndroid Build Coastguard Worker       Reg = Res.getSrcReg(0);
1929*9880d681SAndroid Build Coastguard Worker     // Update the result before moving up in the use-def chain
1930*9880d681SAndroid Build Coastguard Worker     // with the instruction containing the last found sources.
1931*9880d681SAndroid Build Coastguard Worker     Res.setInst(Def);
1932*9880d681SAndroid Build Coastguard Worker 
1933*9880d681SAndroid Build Coastguard Worker     // If we can still move up in the use-def chain, move to the next
1934*9880d681SAndroid Build Coastguard Worker     // definition.
1935*9880d681SAndroid Build Coastguard Worker     if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
1936*9880d681SAndroid Build Coastguard Worker       Def = MRI.getVRegDef(Reg);
1937*9880d681SAndroid Build Coastguard Worker       DefIdx = MRI.def_begin(Reg).getOperandNo();
1938*9880d681SAndroid Build Coastguard Worker       DefSubReg = Res.getSrcSubReg(0);
1939*9880d681SAndroid Build Coastguard Worker       return Res;
1940*9880d681SAndroid Build Coastguard Worker     }
1941*9880d681SAndroid Build Coastguard Worker   }
1942*9880d681SAndroid Build Coastguard Worker   // If we end up here, this means we will not be able to find another source
1943*9880d681SAndroid Build Coastguard Worker   // for the next iteration. Make sure any new call to getNextSource bails out
1944*9880d681SAndroid Build Coastguard Worker   // early by cutting the use-def chain.
1945*9880d681SAndroid Build Coastguard Worker   Def = nullptr;
1946*9880d681SAndroid Build Coastguard Worker   return Res;
1947*9880d681SAndroid Build Coastguard Worker }
1948