4ad7041d329ff7da447b65fbbedd7dcd80fef2bf
[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 Try to find the next source that share the same register file
581 /// for the value defined by \p Reg and \p SubReg.
582 /// When true is returned, the \p RewriteMap can be used by the client to
583 /// retrieve all Def -> Use along the way up to the next source. Any found
584 /// Use that is not itself a key for another entry, is the next source to
585 /// use. During the search for the next source, multiple sources can be found
586 /// given multiple incoming sources of a PHI instruction. In this case, we
587 /// look in each PHI source for the next source; all found next sources must
588 /// share the same register file as \p Reg and \p SubReg. The client should
589 /// then be capable to rewrite all intermediate PHIs to get the next source.
590 /// \return False if no alternative sources are available. True otherwise.
591 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
592                                        RewriteMapTy &RewriteMap) {
593   // Do not try to find a new source for a physical register.
594   // So far we do not have any motivating example for doing that.
595   // Thus, instead of maintaining untested code, we will revisit that if
596   // that changes at some point.
597   if (TargetRegisterInfo::isPhysicalRegister(Reg))
598     return false;
599   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
600
601   SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
602   TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
603   SrcToLook.push_back(CurSrcPair);
604
605   unsigned PHICount = 0;
606   while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
607     TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
608     // As explained above, do not handle physical registers
609     if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
610       return false;
611
612     CurSrcPair = Pair;
613     ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
614                             !DisableAdvCopyOpt, TII);
615     ValueTrackerResult Res;
616     bool ShouldRewrite = false;
617
618     do {
619       // Follow the chain of copies until we reach the top of the use-def chain
620       // or find a more suitable source.
621       Res = ValTracker.getNextSource();
622       if (!Res.isValid())
623         break;
624
625       // Insert the Def -> Use entry for the recently found source.
626       ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
627       if (CurSrcRes.isValid()) {
628         assert(CurSrcRes == Res && "ValueTrackerResult found must match");
629         // An existent entry with multiple sources is a PHI cycle we must avoid.
630         // Otherwise it's an entry with a valid next source we already found.
631         if (CurSrcRes.getNumSources() > 1) {
632           DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
633           return false;
634         }
635         break;
636       }
637       RewriteMap.insert(std::make_pair(CurSrcPair, Res));
638
639       // ValueTrackerResult usually have one source unless it's the result from
640       // a PHI instruction. Add the found PHI edges to be looked up further.
641       unsigned NumSrcs = Res.getNumSources();
642       if (NumSrcs > 1) {
643         PHICount++;
644         for (unsigned i = 0; i < NumSrcs; ++i)
645           SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
646               Res.getSrcReg(i), Res.getSrcSubReg(i)));
647         break;
648       }
649
650       CurSrcPair.Reg = Res.getSrcReg(0);
651       CurSrcPair.SubReg = Res.getSrcSubReg(0);
652       // Do not extend the live-ranges of physical registers as they add
653       // constraints to the register allocator. Moreover, if we want to extend
654       // the live-range of a physical register, unlike SSA virtual register,
655       // we will have to check that they aren't redefine before the related use.
656       if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
657         return false;
658
659       const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
660       ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
661                                                 CurSrcPair.SubReg);
662     } while (!ShouldRewrite);
663
664     // Continue looking for new sources...
665     if (Res.isValid())
666       continue;
667
668     // Do not continue searching for a new source if the there's at least
669     // one use-def which cannot be rewritten.
670     if (!ShouldRewrite)
671       return false;
672   }
673
674   if (PHICount >= RewritePHILimit) {
675     DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
676     return false;
677   }
678
679   // If we did not find a more suitable source, there is nothing to optimize.
680   if (CurSrcPair.Reg == Reg)
681     return false;
682
683   return true;
684 }
685
686 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
687 /// guaranteed to have the same register class. This is necessary whenever we
688 /// successfully traverse a PHI instruction and find suitable sources coming
689 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
690 /// suitable to be used in a new COPY instruction.
691 static MachineInstr *
692 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
693           const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
694           MachineInstr *OrigPHI) {
695   assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
696
697   const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
698   unsigned NewVR = MRI->createVirtualRegister(NewRC);
699   MachineBasicBlock *MBB = OrigPHI->getParent();
700   MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
701                                     TII->get(TargetOpcode::PHI), NewVR);
702
703   unsigned MBBOpIdx = 2;
704   for (auto RegPair : SrcRegs) {
705     MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
706     MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
707     // Since we're extended the lifetime of RegPair.Reg, clear the
708     // kill flags to account for that and make RegPair.Reg reaches
709     // the new PHI.
710     MRI->clearKillFlags(RegPair.Reg);
711     MBBOpIdx += 2;
712   }
713
714   return MIB;
715 }
716
717 namespace {
718 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
719 class CopyRewriter {
720 protected:
721   /// The copy-like instruction.
722   MachineInstr &CopyLike;
723   /// The index of the source being rewritten.
724   unsigned CurrentSrcIdx;
725
726 public:
727   CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
728
729   virtual ~CopyRewriter() {}
730
731   /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
732   /// the related value that it affects (TrackReg, TrackSubReg).
733   /// A source is considered rewritable if its register class and the
734   /// register class of the related TrackReg may not be register
735   /// coalescer friendly. In other words, given a copy-like instruction
736   /// not all the arguments may be returned at rewritable source, since
737   /// some arguments are none to be register coalescer friendly.
738   ///
739   /// Each call of this method moves the current source to the next
740   /// rewritable source.
741   /// For instance, let CopyLike be the instruction to rewrite.
742   /// CopyLike has one definition and one source:
743   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
744   ///
745   /// The first call will give the first rewritable source, i.e.,
746   /// the only source this instruction has:
747   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
748   /// This source defines the whole definition, i.e.,
749   /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
750   ///
751   /// The second and subsequent calls will return false, as there is only one
752   /// rewritable source.
753   ///
754   /// \return True if a rewritable source has been found, false otherwise.
755   /// The output arguments are valid if and only if true is returned.
756   virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
757                                        unsigned &TrackReg,
758                                        unsigned &TrackSubReg) {
759     // If CurrentSrcIdx == 1, this means this function has already been called
760     // once. CopyLike has one definition and one argument, thus, there is
761     // nothing else to rewrite.
762     if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
763       return false;
764     // This is the first call to getNextRewritableSource.
765     // Move the CurrentSrcIdx to remember that we made that call.
766     CurrentSrcIdx = 1;
767     // The rewritable source is the argument.
768     const MachineOperand &MOSrc = CopyLike.getOperand(1);
769     SrcReg = MOSrc.getReg();
770     SrcSubReg = MOSrc.getSubReg();
771     // What we track are the alternative sources of the definition.
772     const MachineOperand &MODef = CopyLike.getOperand(0);
773     TrackReg = MODef.getReg();
774     TrackSubReg = MODef.getSubReg();
775     return true;
776   }
777
778   /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
779   /// if possible.
780   /// \return True if the rewriting was possible, false otherwise.
781   virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
782     if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
783       return false;
784     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
785     MOSrc.setReg(NewReg);
786     MOSrc.setSubReg(NewSubReg);
787     return true;
788   }
789
790   /// \brief Given a \p Def.Reg and Def.SubReg  pair, use \p RewriteMap to find
791   /// the new source to use for rewrite. If \p HandleMultipleSources is true and
792   /// multiple sources for a given \p Def are found along the way, we found a
793   /// PHI instructions that needs to be rewritten.
794   /// TODO: HandleMultipleSources should be removed once we test PHI handling
795   /// with coalescable copies.
796   TargetInstrInfo::RegSubRegPair
797   getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
798                TargetInstrInfo::RegSubRegPair Def,
799                PeepholeOptimizer::RewriteMapTy &RewriteMap,
800                bool HandleMultipleSources = true) {
801
802     TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
803     do {
804       ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
805       // If there are no entries on the map, LookupSrc is the new source.
806       if (!Res.isValid())
807         return LookupSrc;
808
809       // There's only one source for this definition, keep searching...
810       unsigned NumSrcs = Res.getNumSources();
811       if (NumSrcs == 1) {
812         LookupSrc.Reg = Res.getSrcReg(0);
813         LookupSrc.SubReg = Res.getSrcSubReg(0);
814         continue;
815       }
816
817       // TODO: Remove once multiple srcs w/ coalescable copies are supported.
818       if (!HandleMultipleSources)
819         break;
820
821       // Multiple sources, recurse into each source to find a new source
822       // for it. Then, rewrite the PHI accordingly to its new edges.
823       SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
824       for (unsigned i = 0; i < NumSrcs; ++i) {
825         TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
826                                               Res.getSrcSubReg(i));
827         NewPHISrcs.push_back(
828             getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
829       }
830
831       // Build the new PHI node and return its def register as the new source.
832       MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
833       MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
834       DEBUG(dbgs() << "-- getNewSource\n");
835       DEBUG(dbgs() << "   Replacing: " << *OrigPHI);
836       DEBUG(dbgs() << "        With: " << *NewPHI);
837       const MachineOperand &MODef = NewPHI->getOperand(0);
838       return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
839
840     } while (1);
841
842     return TargetInstrInfo::RegSubRegPair(0, 0);
843   }
844
845   /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
846   /// and create a new COPY instruction. More info about RewriteMap in
847   /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
848   /// Uncoalescable copies, since they are copy like instructions that aren't
849   /// recognized by the register allocator.
850   virtual MachineInstr *
851   RewriteSource(TargetInstrInfo::RegSubRegPair Def,
852                 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
853     return nullptr;
854   }
855 };
856
857 /// \brief Helper class to rewrite uncoalescable copy like instructions
858 /// into new COPY (coalescable friendly) instructions.
859 class UncoalescableRewriter : public CopyRewriter {
860 protected:
861   const TargetInstrInfo &TII;
862   MachineRegisterInfo   &MRI;
863   /// The number of defs in the bitcast
864   unsigned NumDefs;
865
866 public:
867   UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
868                          MachineRegisterInfo &MRI)
869       : CopyRewriter(MI), TII(TII), MRI(MRI) {
870     NumDefs = MI.getDesc().getNumDefs();
871   }
872
873   /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
874   /// All such sources need to be considered rewritable in order to
875   /// rewrite a uncoalescable copy-like instruction. This method return
876   /// each definition that must be checked if rewritable.
877   ///
878   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
879                                unsigned &TrackReg,
880                                unsigned &TrackSubReg) override {
881     // Find the next non-dead definition and continue from there.
882     if (CurrentSrcIdx == NumDefs)
883       return false;
884
885     while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
886       ++CurrentSrcIdx;
887       if (CurrentSrcIdx == NumDefs)
888         return false;
889     }
890
891     // What we track are the alternative sources of the definition.
892     const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
893     TrackReg = MODef.getReg();
894     TrackSubReg = MODef.getSubReg();
895
896     CurrentSrcIdx++;
897     return true;
898   }
899
900   /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
901   /// and create a new COPY instruction. More info about RewriteMap in
902   /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
903   /// Uncoalescable copies, since they are copy like instructions that aren't
904   /// recognized by the register allocator.
905   MachineInstr *
906   RewriteSource(TargetInstrInfo::RegSubRegPair Def,
907                 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
908     assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
909            "We do not rewrite physical registers");
910
911     // Find the new source to use in the COPY rewrite.
912     TargetInstrInfo::RegSubRegPair NewSrc =
913         getNewSource(&MRI, &TII, Def, RewriteMap);
914
915     // Insert the COPY.
916     const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
917     unsigned NewVR = MRI.createVirtualRegister(DefRC);
918
919     MachineInstr *NewCopy =
920         BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
921                 TII.get(TargetOpcode::COPY), NewVR)
922             .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
923
924     NewCopy->getOperand(0).setSubReg(Def.SubReg);
925     if (Def.SubReg)
926       NewCopy->getOperand(0).setIsUndef();
927
928     DEBUG(dbgs() << "-- RewriteSource\n");
929     DEBUG(dbgs() << "   Replacing: " << CopyLike);
930     DEBUG(dbgs() << "        With: " << *NewCopy);
931     MRI.replaceRegWith(Def.Reg, NewVR);
932     MRI.clearKillFlags(NewVR);
933
934     // We extended the lifetime of NewSrc.Reg, clear the kill flags to
935     // account for that.
936     MRI.clearKillFlags(NewSrc.Reg);
937
938     return NewCopy;
939   }
940 };
941
942 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
943 class InsertSubregRewriter : public CopyRewriter {
944 public:
945   InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
946     assert(MI.isInsertSubreg() && "Invalid instruction");
947   }
948
949   /// \brief See CopyRewriter::getNextRewritableSource.
950   /// Here CopyLike has the following form:
951   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
952   /// Src1 has the same register class has dst, hence, there is
953   /// nothing to rewrite.
954   /// Src2.src2SubIdx, may not be register coalescer friendly.
955   /// Therefore, the first call to this method returns:
956   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
957   /// (TrackReg, TrackSubReg) = (dst, subIdx).
958   ///
959   /// Subsequence calls will return false.
960   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
961                                unsigned &TrackReg,
962                                unsigned &TrackSubReg) override {
963     // If we already get the only source we can rewrite, return false.
964     if (CurrentSrcIdx == 2)
965       return false;
966     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
967     CurrentSrcIdx = 2;
968     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
969     SrcReg = MOInsertedReg.getReg();
970     SrcSubReg = MOInsertedReg.getSubReg();
971     const MachineOperand &MODef = CopyLike.getOperand(0);
972
973     // We want to track something that is compatible with the
974     // partial definition.
975     TrackReg = MODef.getReg();
976     if (MODef.getSubReg())
977       // Bail if we have to compose sub-register indices.
978       return false;
979     TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
980     return true;
981   }
982   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
983     if (CurrentSrcIdx != 2)
984       return false;
985     // We are rewriting the inserted reg.
986     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
987     MO.setReg(NewReg);
988     MO.setSubReg(NewSubReg);
989     return true;
990   }
991 };
992
993 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
994 class ExtractSubregRewriter : public CopyRewriter {
995   const TargetInstrInfo &TII;
996
997 public:
998   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
999       : CopyRewriter(MI), TII(TII) {
1000     assert(MI.isExtractSubreg() && "Invalid instruction");
1001   }
1002
1003   /// \brief See CopyRewriter::getNextRewritableSource.
1004   /// Here CopyLike has the following form:
1005   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1006   /// There is only one rewritable source: Src.subIdx,
1007   /// which defines dst.dstSubIdx.
1008   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1009                                unsigned &TrackReg,
1010                                unsigned &TrackSubReg) override {
1011     // If we already get the only source we can rewrite, return false.
1012     if (CurrentSrcIdx == 1)
1013       return false;
1014     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1015     CurrentSrcIdx = 1;
1016     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1017     SrcReg = MOExtractedReg.getReg();
1018     // If we have to compose sub-register indices, bail out.
1019     if (MOExtractedReg.getSubReg())
1020       return false;
1021
1022     SrcSubReg = CopyLike.getOperand(2).getImm();
1023
1024     // We want to track something that is compatible with the definition.
1025     const MachineOperand &MODef = CopyLike.getOperand(0);
1026     TrackReg = MODef.getReg();
1027     TrackSubReg = MODef.getSubReg();
1028     return true;
1029   }
1030
1031   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1032     // The only source we can rewrite is the input register.
1033     if (CurrentSrcIdx != 1)
1034       return false;
1035
1036     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1037
1038     // If we find a source that does not require to extract something,
1039     // rewrite the operation with a copy.
1040     if (!NewSubReg) {
1041       // Move the current index to an invalid position.
1042       // We do not want another call to this method to be able
1043       // to do any change.
1044       CurrentSrcIdx = -1;
1045       // Rewrite the operation as a COPY.
1046       // Get rid of the sub-register index.
1047       CopyLike.RemoveOperand(2);
1048       // Morph the operation into a COPY.
1049       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1050       return true;
1051     }
1052     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1053     return true;
1054   }
1055 };
1056
1057 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1058 class RegSequenceRewriter : public CopyRewriter {
1059 public:
1060   RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1061     assert(MI.isRegSequence() && "Invalid instruction");
1062   }
1063
1064   /// \brief See CopyRewriter::getNextRewritableSource.
1065   /// Here CopyLike has the following form:
1066   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1067   /// Each call will return a different source, walking all the available
1068   /// source.
1069   ///
1070   /// The first call returns:
1071   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1072   /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1073   ///
1074   /// The second call returns:
1075   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1076   /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1077   ///
1078   /// And so on, until all the sources have been traversed, then
1079   /// it returns false.
1080   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1081                                unsigned &TrackReg,
1082                                unsigned &TrackSubReg) override {
1083     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1084
1085     // If this is the first call, move to the first argument.
1086     if (CurrentSrcIdx == 0) {
1087       CurrentSrcIdx = 1;
1088     } else {
1089       // Otherwise, move to the next argument and check that it is valid.
1090       CurrentSrcIdx += 2;
1091       if (CurrentSrcIdx >= CopyLike.getNumOperands())
1092         return false;
1093     }
1094     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1095     SrcReg = MOInsertedReg.getReg();
1096     // If we have to compose sub-register indices, bail out.
1097     if ((SrcSubReg = MOInsertedReg.getSubReg()))
1098       return false;
1099
1100     // We want to track something that is compatible with the related
1101     // partial definition.
1102     TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1103
1104     const MachineOperand &MODef = CopyLike.getOperand(0);
1105     TrackReg = MODef.getReg();
1106     // If we have to compose sub-registers, bail.
1107     return MODef.getSubReg() == 0;
1108   }
1109
1110   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1111     // We cannot rewrite out of bound operands.
1112     // Moreover, rewritable sources are at odd positions.
1113     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1114       return false;
1115
1116     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1117     MO.setReg(NewReg);
1118     MO.setSubReg(NewSubReg);
1119     return true;
1120   }
1121 };
1122 } // End namespace.
1123
1124 /// \brief Get the appropriated CopyRewriter for \p MI.
1125 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1126 /// if no rewriter works for \p MI.
1127 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1128                                      const TargetInstrInfo &TII,
1129                                      MachineRegisterInfo &MRI) {
1130   // Handle uncoalescable copy-like instructions.
1131   if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1132                          MI.isExtractSubregLike()))
1133     return new UncoalescableRewriter(MI, TII, MRI);
1134
1135   switch (MI.getOpcode()) {
1136   default:
1137     return nullptr;
1138   case TargetOpcode::COPY:
1139     return new CopyRewriter(MI);
1140   case TargetOpcode::INSERT_SUBREG:
1141     return new InsertSubregRewriter(MI);
1142   case TargetOpcode::EXTRACT_SUBREG:
1143     return new ExtractSubregRewriter(MI, TII);
1144   case TargetOpcode::REG_SEQUENCE:
1145     return new RegSequenceRewriter(MI);
1146   }
1147   llvm_unreachable(nullptr);
1148 }
1149
1150 /// \brief Optimize generic copy instructions to avoid cross
1151 /// register bank copy. The optimization looks through a chain of
1152 /// copies and tries to find a source that has a compatible register
1153 /// class.
1154 /// Two register classes are considered to be compatible if they share
1155 /// the same register bank.
1156 /// New copies issued by this optimization are register allocator
1157 /// friendly. This optimization does not remove any copy as it may
1158 /// overconstrain the register allocator, but replaces some operands
1159 /// when possible.
1160 /// \pre isCoalescableCopy(*MI) is true.
1161 /// \return True, when \p MI has been rewritten. False otherwise.
1162 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1163   assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1164   assert(MI->getDesc().getNumDefs() == 1 &&
1165          "Coalescer can understand multiple defs?!");
1166   const MachineOperand &MODef = MI->getOperand(0);
1167   // Do not rewrite physical definitions.
1168   if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1169     return false;
1170
1171   bool Changed = false;
1172   // Get the right rewriter for the current copy.
1173   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1174   // If none exists, bail out.
1175   if (!CpyRewriter)
1176     return false;
1177   // Rewrite each rewritable source.
1178   unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1179   while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1180                                               TrackSubReg)) {
1181     // Keep track of PHI nodes and its incoming edges when looking for sources.
1182     RewriteMapTy RewriteMap;
1183     // Try to find a more suitable source. If we failed to do so, or get the
1184     // actual source, move to the next source.
1185     if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1186       continue;
1187
1188     // Get the new source to rewrite. TODO: Only enable handling of multiple
1189     // sources (PHIs) once we have a motivating example and testcases for it.
1190     TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1191     TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1192         MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1193     if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1194       continue;
1195
1196     // Rewrite source.
1197     if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1198       // We may have extended the live-range of NewSrc, account for that.
1199       MRI->clearKillFlags(NewSrc.Reg);
1200       Changed = true;
1201     }
1202   }
1203   // TODO: We could have a clean-up method to tidy the instruction.
1204   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1205   // => v0 = COPY v1
1206   // Currently we haven't seen motivating example for that and we
1207   // want to avoid untested code.
1208   NumRewrittenCopies += Changed;
1209   return Changed;
1210 }
1211
1212 /// \brief Optimize copy-like instructions to create
1213 /// register coalescer friendly instruction.
1214 /// The optimization tries to kill-off the \p MI by looking
1215 /// through a chain of copies to find a source that has a compatible
1216 /// register class.
1217 /// If such a source is found, it replace \p MI by a generic COPY
1218 /// operation.
1219 /// \pre isUncoalescableCopy(*MI) is true.
1220 /// \return True, when \p MI has been optimized. In that case, \p MI has
1221 /// been removed from its parent.
1222 /// All COPY instructions created, are inserted in \p LocalMIs.
1223 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1224     MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1225   assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1226
1227   // Check if we can rewrite all the values defined by this instruction.
1228   SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1229   // Get the right rewriter for the current copy.
1230   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1231   // If none exists, bail out.
1232   if (!CpyRewriter)
1233     return false;
1234
1235   // Rewrite each rewritable source by generating new COPYs. This works
1236   // differently from optimizeCoalescableCopy since it first makes sure that all
1237   // definitions can be rewritten.
1238   RewriteMapTy RewriteMap;
1239   unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1240   while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1241                                               CopyDefSubReg)) {
1242     // If a physical register is here, this is probably for a good reason.
1243     // Do not rewrite that.
1244     if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1245       return false;
1246
1247     // If we do not know how to rewrite this definition, there is no point
1248     // in trying to kill this instruction.
1249     TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1250     if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1251       return false;
1252
1253     RewritePairs.push_back(Def);
1254   }
1255
1256   // The change is possible for all defs, do it.
1257   for (const auto &Def : RewritePairs) {
1258     // Rewrite the "copy" in a way the register coalescer understands.
1259     MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1260     assert(NewCopy && "Should be able to always generate a new copy");
1261     LocalMIs.insert(NewCopy);
1262   }
1263
1264   // MI is now dead.
1265   MI->eraseFromParent();
1266   ++NumUncoalescableCopies;
1267   return true;
1268 }
1269
1270 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
1271 /// instruction. We only fold loads to virtual registers and the virtual
1272 /// register defined has a single use.
1273 bool PeepholeOptimizer::isLoadFoldable(
1274                               MachineInstr *MI,
1275                               SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1276   if (!MI->canFoldAsLoad() || !MI->mayLoad())
1277     return false;
1278   const MCInstrDesc &MCID = MI->getDesc();
1279   if (MCID.getNumDefs() != 1)
1280     return false;
1281
1282   unsigned Reg = MI->getOperand(0).getReg();
1283   // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1284   // loads. It should be checked when processing uses of the load, since
1285   // uses can be removed during peephole.
1286   if (!MI->getOperand(0).getSubReg() &&
1287       TargetRegisterInfo::isVirtualRegister(Reg) &&
1288       MRI->hasOneNonDBGUse(Reg)) {
1289     FoldAsLoadDefCandidates.insert(Reg);
1290     return true;
1291   }
1292   return false;
1293 }
1294
1295 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1296                                         SmallSet<unsigned, 4> &ImmDefRegs,
1297                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1298   const MCInstrDesc &MCID = MI->getDesc();
1299   if (!MI->isMoveImmediate())
1300     return false;
1301   if (MCID.getNumDefs() != 1)
1302     return false;
1303   unsigned Reg = MI->getOperand(0).getReg();
1304   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1305     ImmDefMIs.insert(std::make_pair(Reg, MI));
1306     ImmDefRegs.insert(Reg);
1307     return true;
1308   }
1309
1310   return false;
1311 }
1312
1313 /// foldImmediate - Try folding register operands that are defined by move
1314 /// immediate instructions, i.e. a trivial constant folding optimization, if
1315 /// and only if the def and use are in the same BB.
1316 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1317                                       SmallSet<unsigned, 4> &ImmDefRegs,
1318                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1319   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1320     MachineOperand &MO = MI->getOperand(i);
1321     if (!MO.isReg() || MO.isDef())
1322       continue;
1323     unsigned Reg = MO.getReg();
1324     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1325       continue;
1326     if (ImmDefRegs.count(Reg) == 0)
1327       continue;
1328     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1329     assert(II != ImmDefMIs.end());
1330     if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1331       ++NumImmFold;
1332       return true;
1333     }
1334   }
1335   return false;
1336 }
1337
1338 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1339   if (skipOptnoneFunction(*MF.getFunction()))
1340     return false;
1341
1342   DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1343   DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1344
1345   if (DisablePeephole)
1346     return false;
1347
1348   TII = MF.getSubtarget().getInstrInfo();
1349   TRI = MF.getSubtarget().getRegisterInfo();
1350   MRI = &MF.getRegInfo();
1351   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1352
1353   bool Changed = false;
1354
1355   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1356     MachineBasicBlock *MBB = &*I;
1357
1358     bool SeenMoveImm = false;
1359
1360     // During this forward scan, at some point it needs to answer the question
1361     // "given a pointer to an MI in the current BB, is it located before or
1362     // after the current instruction".
1363     // To perform this, the following set keeps track of the MIs already seen
1364     // during the scan, if a MI is not in the set, it is assumed to be located
1365     // after. Newly created MIs have to be inserted in the set as well.
1366     SmallPtrSet<MachineInstr*, 16> LocalMIs;
1367     SmallSet<unsigned, 4> ImmDefRegs;
1368     DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1369     SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1370
1371     for (MachineBasicBlock::iterator
1372            MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1373       MachineInstr *MI = &*MII;
1374       // We may be erasing MI below, increment MII now.
1375       ++MII;
1376       LocalMIs.insert(MI);
1377
1378       // Skip debug values. They should not affect this peephole optimization.
1379       if (MI->isDebugValue())
1380           continue;
1381
1382       // If we run into an instruction we can't fold across, discard
1383       // the load candidates.
1384       if (MI->isLoadFoldBarrier())
1385         FoldAsLoadDefCandidates.clear();
1386
1387       if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1388           MI->isKill() || MI->isInlineAsm() ||
1389           MI->hasUnmodeledSideEffects())
1390         continue;
1391
1392       if ((isUncoalescableCopy(*MI) &&
1393            optimizeUncoalescableCopy(MI, LocalMIs)) ||
1394           (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1395           (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1396         // MI is deleted.
1397         LocalMIs.erase(MI);
1398         Changed = true;
1399         continue;
1400       }
1401
1402       if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1403         Changed = true;
1404         continue;
1405       }
1406
1407       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1408         // MI is just rewritten.
1409         Changed = true;
1410         continue;
1411       }
1412
1413       if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1414         SeenMoveImm = true;
1415       } else {
1416         Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1417         // optimizeExtInstr might have created new instructions after MI
1418         // and before the already incremented MII. Adjust MII so that the
1419         // next iteration sees the new instructions.
1420         MII = MI;
1421         ++MII;
1422         if (SeenMoveImm)
1423           Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1424       }
1425
1426       // Check whether MI is a load candidate for folding into a later
1427       // instruction. If MI is not a candidate, check whether we can fold an
1428       // earlier load into MI.
1429       if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1430           !FoldAsLoadDefCandidates.empty()) {
1431         const MCInstrDesc &MIDesc = MI->getDesc();
1432         for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1433              ++i) {
1434           const MachineOperand &MOp = MI->getOperand(i);
1435           if (!MOp.isReg())
1436             continue;
1437           unsigned FoldAsLoadDefReg = MOp.getReg();
1438           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1439             // We need to fold load after optimizeCmpInstr, since
1440             // optimizeCmpInstr can enable folding by converting SUB to CMP.
1441             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1442             // we need it for markUsesInDebugValueAsUndef().
1443             unsigned FoldedReg = FoldAsLoadDefReg;
1444             MachineInstr *DefMI = nullptr;
1445             MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1446                                                           FoldAsLoadDefReg,
1447                                                           DefMI);
1448             if (FoldMI) {
1449               // Update LocalMIs since we replaced MI with FoldMI and deleted
1450               // DefMI.
1451               DEBUG(dbgs() << "Replacing: " << *MI);
1452               DEBUG(dbgs() << "     With: " << *FoldMI);
1453               LocalMIs.erase(MI);
1454               LocalMIs.erase(DefMI);
1455               LocalMIs.insert(FoldMI);
1456               MI->eraseFromParent();
1457               DefMI->eraseFromParent();
1458               MRI->markUsesInDebugValueAsUndef(FoldedReg);
1459               FoldAsLoadDefCandidates.erase(FoldedReg);
1460               ++NumLoadFold;
1461               // MI is replaced with FoldMI.
1462               Changed = true;
1463               break;
1464             }
1465           }
1466         }
1467       }
1468     }
1469   }
1470
1471   return Changed;
1472 }
1473
1474 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1475   assert(Def->isCopy() && "Invalid definition");
1476   // Copy instruction are supposed to be: Def = Src.
1477   // If someone breaks this assumption, bad things will happen everywhere.
1478   assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1479
1480   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1481     // If we look for a different subreg, it means we want a subreg of src.
1482     // Bails as we do not support composing subregs yet.
1483     return ValueTrackerResult();
1484   // Otherwise, we want the whole source.
1485   const MachineOperand &Src = Def->getOperand(1);
1486   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1487 }
1488
1489 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1490   assert(Def->isBitcast() && "Invalid definition");
1491
1492   // Bail if there are effects that a plain copy will not expose.
1493   if (Def->hasUnmodeledSideEffects())
1494     return ValueTrackerResult();
1495
1496   // Bitcasts with more than one def are not supported.
1497   if (Def->getDesc().getNumDefs() != 1)
1498     return ValueTrackerResult();
1499   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1500     // If we look for a different subreg, it means we want a subreg of the src.
1501     // Bails as we do not support composing subregs yet.
1502     return ValueTrackerResult();
1503
1504   unsigned SrcIdx = Def->getNumOperands();
1505   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1506        ++OpIdx) {
1507     const MachineOperand &MO = Def->getOperand(OpIdx);
1508     if (!MO.isReg() || !MO.getReg())
1509       continue;
1510     assert(!MO.isDef() && "We should have skipped all the definitions by now");
1511     if (SrcIdx != EndOpIdx)
1512       // Multiple sources?
1513       return ValueTrackerResult();
1514     SrcIdx = OpIdx;
1515   }
1516   const MachineOperand &Src = Def->getOperand(SrcIdx);
1517   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1518 }
1519
1520 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1521   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1522          "Invalid definition");
1523
1524   if (Def->getOperand(DefIdx).getSubReg())
1525     // If we are composing subregs, bail out.
1526     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1527     // This should almost never happen as the SSA property is tracked at
1528     // the register level (as opposed to the subreg level).
1529     // I.e.,
1530     // Def.sub0 =
1531     // Def.sub1 =
1532     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1533     // Def. Thus, it must not be generated.
1534     // However, some code could theoretically generates a single
1535     // Def.sub0 (i.e, not defining the other subregs) and we would
1536     // have this case.
1537     // If we can ascertain (or force) that this never happens, we could
1538     // turn that into an assertion.
1539     return ValueTrackerResult();
1540
1541   if (!TII)
1542     // We could handle the REG_SEQUENCE here, but we do not want to
1543     // duplicate the code from the generic TII.
1544     return ValueTrackerResult();
1545
1546   SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1547   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1548     return ValueTrackerResult();
1549
1550   // We are looking at:
1551   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1552   // Check if one of the operand defines the subreg we are interested in.
1553   for (auto &RegSeqInput : RegSeqInputRegs) {
1554     if (RegSeqInput.SubIdx == DefSubReg) {
1555       if (RegSeqInput.SubReg)
1556         // Bail if we have to compose sub registers.
1557         return ValueTrackerResult();
1558
1559       return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1560     }
1561   }
1562
1563   // If the subreg we are tracking is super-defined by another subreg,
1564   // we could follow this value. However, this would require to compose
1565   // the subreg and we do not do that for now.
1566   return ValueTrackerResult();
1567 }
1568
1569 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1570   assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1571          "Invalid definition");
1572
1573   if (Def->getOperand(DefIdx).getSubReg())
1574     // If we are composing subreg, bail out.
1575     // Same remark as getNextSourceFromRegSequence.
1576     // I.e., this may be turned into an assert.
1577     return ValueTrackerResult();
1578
1579   if (!TII)
1580     // We could handle the REG_SEQUENCE here, but we do not want to
1581     // duplicate the code from the generic TII.
1582     return ValueTrackerResult();
1583
1584   TargetInstrInfo::RegSubRegPair BaseReg;
1585   TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1586   if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1587     return ValueTrackerResult();
1588
1589   // We are looking at:
1590   // Def = INSERT_SUBREG v0, v1, sub1
1591   // There are two cases:
1592   // 1. DefSubReg == sub1, get v1.
1593   // 2. DefSubReg != sub1, the value may be available through v0.
1594
1595   // #1 Check if the inserted register matches the required sub index.
1596   if (InsertedReg.SubIdx == DefSubReg) {
1597     return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1598   }
1599   // #2 Otherwise, if the sub register we are looking for is not partial
1600   // defined by the inserted element, we can look through the main
1601   // register (v0).
1602   const MachineOperand &MODef = Def->getOperand(DefIdx);
1603   // If the result register (Def) and the base register (v0) do not
1604   // have the same register class or if we have to compose
1605   // subregisters, bail out.
1606   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1607       BaseReg.SubReg)
1608     return ValueTrackerResult();
1609
1610   // Get the TRI and check if the inserted sub-register overlaps with the
1611   // sub-register we are tracking.
1612   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1613   if (!TRI ||
1614       (TRI->getSubRegIndexLaneMask(DefSubReg) &
1615        TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1616     return ValueTrackerResult();
1617   // At this point, the value is available in v0 via the same subreg
1618   // we used for Def.
1619   return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1620 }
1621
1622 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1623   assert((Def->isExtractSubreg() ||
1624           Def->isExtractSubregLike()) && "Invalid definition");
1625   // We are looking at:
1626   // Def = EXTRACT_SUBREG v0, sub0
1627
1628   // Bail if we have to compose sub registers.
1629   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1630   if (DefSubReg)
1631     return ValueTrackerResult();
1632
1633   if (!TII)
1634     // We could handle the EXTRACT_SUBREG here, but we do not want to
1635     // duplicate the code from the generic TII.
1636     return ValueTrackerResult();
1637
1638   TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1639   if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1640     return ValueTrackerResult();
1641
1642   // Bail if we have to compose sub registers.
1643   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1644   if (ExtractSubregInputReg.SubReg)
1645     return ValueTrackerResult();
1646   // Otherwise, the value is available in the v0.sub0.
1647   return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
1648 }
1649
1650 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
1651   assert(Def->isSubregToReg() && "Invalid definition");
1652   // We are looking at:
1653   // Def = SUBREG_TO_REG Imm, v0, sub0
1654
1655   // Bail if we have to compose sub registers.
1656   // If DefSubReg != sub0, we would have to check that all the bits
1657   // we track are included in sub0 and if yes, we would have to
1658   // determine the right subreg in v0.
1659   if (DefSubReg != Def->getOperand(3).getImm())
1660     return ValueTrackerResult();
1661   // Bail if we have to compose sub registers.
1662   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1663   if (Def->getOperand(2).getSubReg())
1664     return ValueTrackerResult();
1665
1666   return ValueTrackerResult(Def->getOperand(2).getReg(),
1667                             Def->getOperand(3).getImm());
1668 }
1669
1670 /// \brief Explore each PHI incoming operand and return its sources
1671 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1672   assert(Def->isPHI() && "Invalid definition");
1673   ValueTrackerResult Res;
1674
1675   // If we look for a different subreg, bail as we do not support composing
1676   // subregs yet.
1677   if (Def->getOperand(0).getSubReg() != DefSubReg)
1678     return ValueTrackerResult();
1679
1680   // Return all register sources for PHI instructions.
1681   for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1682     auto &MO = Def->getOperand(i);
1683     assert(MO.isReg() && "Invalid PHI instruction");
1684     Res.addSource(MO.getReg(), MO.getSubReg());
1685   }
1686
1687   return Res;
1688 }
1689
1690 ValueTrackerResult ValueTracker::getNextSourceImpl() {
1691   assert(Def && "This method needs a valid definition");
1692
1693   assert(
1694       (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1695       Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1696   if (Def->isCopy())
1697     return getNextSourceFromCopy();
1698   if (Def->isBitcast())
1699     return getNextSourceFromBitcast();
1700   // All the remaining cases involve "complex" instructions.
1701   // Bail if we did not ask for the advanced tracking.
1702   if (!UseAdvancedTracking)
1703     return ValueTrackerResult();
1704   if (Def->isRegSequence() || Def->isRegSequenceLike())
1705     return getNextSourceFromRegSequence();
1706   if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1707     return getNextSourceFromInsertSubreg();
1708   if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1709     return getNextSourceFromExtractSubreg();
1710   if (Def->isSubregToReg())
1711     return getNextSourceFromSubregToReg();
1712   if (Def->isPHI())
1713     return getNextSourceFromPHI();
1714   return ValueTrackerResult();
1715 }
1716
1717 ValueTrackerResult ValueTracker::getNextSource() {
1718   // If we reach a point where we cannot move up in the use-def chain,
1719   // there is nothing we can get.
1720   if (!Def)
1721     return ValueTrackerResult();
1722
1723   ValueTrackerResult Res = getNextSourceImpl();
1724   if (Res.isValid()) {
1725     // Update definition, definition index, and subregister for the
1726     // next call of getNextSource.
1727     // Update the current register.
1728     bool OneRegSrc = Res.getNumSources() == 1;
1729     if (OneRegSrc)
1730       Reg = Res.getSrcReg(0);
1731     // Update the result before moving up in the use-def chain
1732     // with the instruction containing the last found sources.
1733     Res.setInst(Def);
1734
1735     // If we can still move up in the use-def chain, move to the next
1736     // definition.
1737     if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
1738       Def = MRI.getVRegDef(Reg);
1739       DefIdx = MRI.def_begin(Reg).getOperandNo();
1740       DefSubReg = Res.getSrcSubReg(0);
1741       return Res;
1742     }
1743   }
1744   // If we end up here, this means we will not be able to find another source
1745   // for the next iteration. Make sure any new call to getNextSource bails out
1746   // early by cutting the use-def chain.
1747   Def = nullptr;
1748   return Res;
1749 }