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