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