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