[PeepholeOptimizer] Refactor the advanced copy optimization to take advantage of
[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/Target/TargetInstrInfo.h"
80 #include "llvm/Target/TargetRegisterInfo.h"
81 #include "llvm/Target/TargetSubtargetInfo.h"
82 #include <utility>
83 using namespace llvm;
84
85 #define DEBUG_TYPE "peephole-opt"
86
87 // Optimize Extensions
88 static cl::opt<bool>
89 Aggressive("aggressive-ext-opt", cl::Hidden,
90            cl::desc("Aggressive extension optimization"));
91
92 static cl::opt<bool>
93 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
94                 cl::desc("Disable the peephole optimizer"));
95
96 static cl::opt<bool>
97 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(true),
98                   cl::desc("Disable advanced copy optimization"));
99
100 STATISTIC(NumReuse,      "Number of extension results reused");
101 STATISTIC(NumCmps,       "Number of compares eliminated");
102 STATISTIC(NumImmFold,    "Number of move immediate folded");
103 STATISTIC(NumLoadFold,   "Number of loads folded");
104 STATISTIC(NumSelects,    "Number of selects optimized");
105 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
106 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
107
108 namespace {
109   class PeepholeOptimizer : public MachineFunctionPass {
110     const TargetMachine   *TM;
111     const TargetInstrInfo *TII;
112     MachineRegisterInfo   *MRI;
113     MachineDominatorTree  *DT;  // Machine dominator tree
114
115   public:
116     static char ID; // Pass identification
117     PeepholeOptimizer() : MachineFunctionPass(ID) {
118       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
119     }
120
121     bool runOnMachineFunction(MachineFunction &MF) override;
122
123     void getAnalysisUsage(AnalysisUsage &AU) const override {
124       AU.setPreservesCFG();
125       MachineFunctionPass::getAnalysisUsage(AU);
126       if (Aggressive) {
127         AU.addRequired<MachineDominatorTree>();
128         AU.addPreserved<MachineDominatorTree>();
129       }
130     }
131
132   private:
133     bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
134     bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
135                           SmallPtrSetImpl<MachineInstr*> &LocalMIs);
136     bool optimizeSelect(MachineInstr *MI);
137     bool optimizeCopyOrBitcast(MachineInstr *MI);
138     bool optimizeCoalescableCopy(MachineInstr *MI);
139     bool optimizeUncoalescableCopy(MachineInstr *MI,
140                                    SmallPtrSetImpl<MachineInstr *> &LocalMIs);
141     bool findNextSource(unsigned &Reg, unsigned &SubReg);
142     bool isMoveImmediate(MachineInstr *MI,
143                          SmallSet<unsigned, 4> &ImmDefRegs,
144                          DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
145     bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
146                        SmallSet<unsigned, 4> &ImmDefRegs,
147                        DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
148     bool isLoadFoldable(MachineInstr *MI,
149                         SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
150
151     /// \brief Check whether \p MI is understood by the register coalescer
152     /// but may require some rewriting.
153     bool isCoalescableCopy(const MachineInstr &MI) {
154       // SubregToRegs are not interesting, because they are already register
155       // coalescer friendly.
156       return MI.isCopy() || (!DisableAdvCopyOpt &&
157                              (MI.isRegSequence() || MI.isInsertSubreg() ||
158                               MI.isExtractSubreg()));
159     }
160
161     /// \brief Check whether \p MI is a copy like instruction that is
162     /// not recognized by the register coalescer.
163     bool isUncoalescableCopy(const MachineInstr &MI) {
164       return MI.isBitcast() || (!DisableAdvCopyOpt &&
165                                 MI.isRegSequenceLike());
166     }
167   };
168
169   /// \brief Helper class to track the possible sources of a value defined by
170   /// a (chain of) copy related instructions.
171   /// Given a definition (instruction and definition index), this class
172   /// follows the use-def chain to find successive suitable sources.
173   /// The given source can be used to rewrite the definition into
174   /// def = COPY src.
175   ///
176   /// For instance, let us consider the following snippet:
177   /// v0 =
178   /// v2 = INSERT_SUBREG v1, v0, sub0
179   /// def = COPY v2.sub0
180   ///
181   /// Using a ValueTracker for def = COPY v2.sub0 will give the following
182   /// suitable sources:
183   /// v2.sub0 and v0.
184   /// Then, def can be rewritten into def = COPY v0.
185   class ValueTracker {
186   private:
187     /// The current point into the use-def chain.
188     const MachineInstr *Def;
189     /// The index of the definition in Def.
190     unsigned DefIdx;
191     /// The sub register index of the definition.
192     unsigned DefSubReg;
193     /// The register where the value can be found.
194     unsigned Reg;
195     /// Specifiy whether or not the value tracking looks through
196     /// complex instructions. When this is false, the value tracker
197     /// bails on everything that is not a copy or a bitcast.
198     ///
199     /// Note: This could have been implemented as a specialized version of
200     /// the ValueTracker class but that would have complicated the code of
201     /// the users of this class.
202     bool UseAdvancedTracking;
203     /// MachineRegisterInfo used to perform tracking.
204     const MachineRegisterInfo &MRI;
205     /// Optional TargetInstrInfo used to perform some complex
206     /// tracking.
207     const TargetInstrInfo *TII;
208
209     /// \brief Dispatcher to the right underlying implementation of
210     /// getNextSource.
211     bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
212     /// \brief Specialized version of getNextSource for Copy instructions.
213     bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
214     /// \brief Specialized version of getNextSource for Bitcast instructions.
215     bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
216     /// \brief Specialized version of getNextSource for RegSequence
217     /// instructions.
218     bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
219     /// \brief Specialized version of getNextSource for InsertSubreg
220     /// instructions.
221     bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
222     /// \brief Specialized version of getNextSource for ExtractSubreg
223     /// instructions.
224     bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
225     /// \brief Specialized version of getNextSource for SubregToReg
226     /// instructions.
227     bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
228
229   public:
230     /// \brief Create a ValueTracker instance for the value defined by \p Reg.
231     /// \p DefSubReg represents the sub register index the value tracker will
232     /// track. It does not need to match the sub register index used in the
233     /// definition of \p Reg.
234     /// \p UseAdvancedTracking specifies whether or not the value tracker looks
235     /// through complex instructions. By default (false), it handles only copy
236     /// and bitcast instructions.
237     /// If \p Reg is a physical register, a value tracker constructed with
238     /// this constructor will not find any alternative source.
239     /// Indeed, when \p Reg is a physical register that constructor does not
240     /// know which definition of \p Reg it should track.
241     /// Use the next constructor to track a physical register.
242     ValueTracker(unsigned Reg, unsigned DefSubReg,
243                  const MachineRegisterInfo &MRI,
244                  bool UseAdvancedTracking = false,
245                  const TargetInstrInfo *TII = nullptr)
246         : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
247           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
248       if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
249         Def = MRI.getVRegDef(Reg);
250         DefIdx = MRI.def_begin(Reg).getOperandNo();
251       }
252     }
253
254     /// \brief Create a ValueTracker instance for the value defined by
255     /// the pair \p MI, \p DefIdx.
256     /// Unlike the other constructor, the value tracker produced by this one
257     /// may be able to find a new source when the definition is a physical
258     /// register.
259     /// This could be useful to rewrite target specific instructions into
260     /// generic copy instructions.
261     ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
262                  const MachineRegisterInfo &MRI,
263                  bool UseAdvancedTracking = false,
264                  const TargetInstrInfo *TII = nullptr)
265         : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
266           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
267       assert(DefIdx < Def->getDesc().getNumDefs() &&
268              Def->getOperand(DefIdx).isReg() && "Invalid definition");
269       Reg = Def->getOperand(DefIdx).getReg();
270     }
271
272     /// \brief Following the use-def chain, get the next available source
273     /// for the tracked value.
274     /// When the returned value is not nullptr, \p SrcReg gives the register
275     /// that contain the tracked value.
276     /// \note The sub register index returned in \p SrcSubReg must be used
277     /// on \p SrcReg to access the actual value.
278     /// \return Unless the returned value is nullptr (i.e., no source found),
279     /// \p SrcReg gives the register of the next source used in the returned
280     /// instruction and \p SrcSubReg the sub-register index to be used on that
281     /// source to get the tracked value. When nullptr is returned, no
282     /// alternative source has been found.
283     const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
284
285     /// \brief Get the last register where the initial value can be found.
286     /// Initially this is the register of the definition.
287     /// Then, after each successful call to getNextSource, this is the
288     /// register of the last source.
289     unsigned getReg() const { return Reg; }
290   };
291 }
292
293 char PeepholeOptimizer::ID = 0;
294 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
295 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
296                 "Peephole Optimizations", false, false)
297 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
298 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
299                 "Peephole Optimizations", false, false)
300
301 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
302 /// a single register and writes a single register and it does not modify the
303 /// source, and if the source value is preserved as a sub-register of the
304 /// result, then replace all reachable uses of the source with the subreg of the
305 /// result.
306 ///
307 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
308 /// the code. Since this code does not currently share EXTRACTs, just ignore all
309 /// debug uses.
310 bool PeepholeOptimizer::
311 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
312                  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
313   unsigned SrcReg, DstReg, SubIdx;
314   if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
315     return false;
316
317   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
318       TargetRegisterInfo::isPhysicalRegister(SrcReg))
319     return false;
320
321   if (MRI->hasOneNonDBGUse(SrcReg))
322     // No other uses.
323     return false;
324
325   // Ensure DstReg can get a register class that actually supports
326   // sub-registers. Don't change the class until we commit.
327   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
328   DstRC = TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
329       DstRC, SubIdx);
330   if (!DstRC)
331     return false;
332
333   // The ext instr may be operating on a sub-register of SrcReg as well.
334   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
335   // register.
336   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
337   // SrcReg:SubIdx should be replaced.
338   bool UseSrcSubIdx =
339       TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
340           MRI->getRegClass(SrcReg), SubIdx) != nullptr;
341
342   // The source has other uses. See if we can replace the other uses with use of
343   // the result of the extension.
344   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
345   for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
346     ReachedBBs.insert(UI.getParent());
347
348   // Uses that are in the same BB of uses of the result of the instruction.
349   SmallVector<MachineOperand*, 8> Uses;
350
351   // Uses that the result of the instruction can reach.
352   SmallVector<MachineOperand*, 8> ExtendedUses;
353
354   bool ExtendLife = true;
355   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
356     MachineInstr *UseMI = UseMO.getParent();
357     if (UseMI == MI)
358       continue;
359
360     if (UseMI->isPHI()) {
361       ExtendLife = false;
362       continue;
363     }
364
365     // Only accept uses of SrcReg:SubIdx.
366     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
367       continue;
368
369     // It's an error to translate this:
370     //
371     //    %reg1025 = <sext> %reg1024
372     //     ...
373     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
374     //
375     // into this:
376     //
377     //    %reg1025 = <sext> %reg1024
378     //     ...
379     //    %reg1027 = COPY %reg1025:4
380     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
381     //
382     // The problem here is that SUBREG_TO_REG is there to assert that an
383     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
384     // the COPY here, it will give us the value after the <sext>, not the
385     // original value of %reg1024 before <sext>.
386     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
387       continue;
388
389     MachineBasicBlock *UseMBB = UseMI->getParent();
390     if (UseMBB == MBB) {
391       // Local uses that come after the extension.
392       if (!LocalMIs.count(UseMI))
393         Uses.push_back(&UseMO);
394     } else if (ReachedBBs.count(UseMBB)) {
395       // Non-local uses where the result of the extension is used. Always
396       // replace these unless it's a PHI.
397       Uses.push_back(&UseMO);
398     } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
399       // We may want to extend the live range of the extension result in order
400       // to replace these uses.
401       ExtendedUses.push_back(&UseMO);
402     } else {
403       // Both will be live out of the def MBB anyway. Don't extend live range of
404       // the extension result.
405       ExtendLife = false;
406       break;
407     }
408   }
409
410   if (ExtendLife && !ExtendedUses.empty())
411     // Extend the liveness of the extension result.
412     std::copy(ExtendedUses.begin(), ExtendedUses.end(),
413               std::back_inserter(Uses));
414
415   // Now replace all uses.
416   bool Changed = false;
417   if (!Uses.empty()) {
418     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
419
420     // Look for PHI uses of the extended result, we don't want to extend the
421     // liveness of a PHI input. It breaks all kinds of assumptions down
422     // stream. A PHI use is expected to be the kill of its source values.
423     for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
424       if (UI.isPHI())
425         PHIBBs.insert(UI.getParent());
426
427     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
428     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
429       MachineOperand *UseMO = Uses[i];
430       MachineInstr *UseMI = UseMO->getParent();
431       MachineBasicBlock *UseMBB = UseMI->getParent();
432       if (PHIBBs.count(UseMBB))
433         continue;
434
435       // About to add uses of DstReg, clear DstReg's kill flags.
436       if (!Changed) {
437         MRI->clearKillFlags(DstReg);
438         MRI->constrainRegClass(DstReg, DstRC);
439       }
440
441       unsigned NewVR = MRI->createVirtualRegister(RC);
442       MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
443                                    TII->get(TargetOpcode::COPY), NewVR)
444         .addReg(DstReg, 0, SubIdx);
445       // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
446       if (UseSrcSubIdx) {
447         Copy->getOperand(0).setSubReg(SubIdx);
448         Copy->getOperand(0).setIsUndef();
449       }
450       UseMO->setReg(NewVR);
451       ++NumReuse;
452       Changed = true;
453     }
454   }
455
456   return Changed;
457 }
458
459 /// optimizeCmpInstr - If the instruction is a compare and the previous
460 /// instruction it's comparing against all ready sets (or could be modified to
461 /// set) the same flag as the compare, then we can remove the comparison and use
462 /// the flag from the previous instruction.
463 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
464                                          MachineBasicBlock *MBB) {
465   // If this instruction is a comparison against zero and isn't comparing a
466   // physical register, we can try to optimize it.
467   unsigned SrcReg, SrcReg2;
468   int CmpMask, CmpValue;
469   if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
470       TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
471       (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
472     return false;
473
474   // Attempt to optimize the comparison instruction.
475   if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
476     ++NumCmps;
477     return true;
478   }
479
480   return false;
481 }
482
483 /// Optimize a select instruction.
484 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI) {
485   unsigned TrueOp = 0;
486   unsigned FalseOp = 0;
487   bool Optimizable = false;
488   SmallVector<MachineOperand, 4> Cond;
489   if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
490     return false;
491   if (!Optimizable)
492     return false;
493   if (!TII->optimizeSelect(MI))
494     return false;
495   MI->eraseFromParent();
496   ++NumSelects;
497   return true;
498 }
499
500 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
501 /// share the same register file.
502 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
503                                   const TargetRegisterClass *DefRC,
504                                   unsigned DefSubReg,
505                                   const TargetRegisterClass *SrcRC,
506                                   unsigned SrcSubReg) {
507   // Same register class.
508   if (DefRC == SrcRC)
509     return true;
510
511   // Both operands are sub registers. Check if they share a register class.
512   unsigned SrcIdx, DefIdx;
513   if (SrcSubReg && DefSubReg)
514     return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
515                                       SrcIdx, DefIdx) != nullptr;
516   // At most one of the register is a sub register, make it Src to avoid
517   // duplicating the test.
518   if (!SrcSubReg) {
519     std::swap(DefSubReg, SrcSubReg);
520     std::swap(DefRC, SrcRC);
521   }
522
523   // One of the register is a sub register, check if we can get a superclass.
524   if (SrcSubReg)
525     return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
526   // Plain copy.
527   return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
528 }
529
530 /// \brief Try to find the next source that share the same register file
531 /// for the value defined by \p Reg and \p SubReg.
532 /// When true is returned, \p Reg and \p SubReg are updated with the
533 /// register number and sub-register index of the new source.
534 /// \return False if no alternative sources are available. True otherwise.
535 bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
536   // Do not try to find a new source for a physical register.
537   // So far we do not have any motivating example for doing that.
538   // Thus, instead of maintaining untested code, we will revisit that if
539   // that changes at some point.
540   if (TargetRegisterInfo::isPhysicalRegister(Reg))
541     return false;
542
543   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
544   unsigned DefSubReg = SubReg;
545
546   unsigned Src;
547   unsigned SrcSubReg;
548   bool ShouldRewrite = false;
549   const TargetRegisterInfo &TRI = *TM->getSubtargetImpl()->getRegisterInfo();
550
551   // Follow the chain of copies until we reach the top of the use-def chain
552   // or find a more suitable source.
553   ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
554   do {
555     unsigned CopySrcReg, CopySrcSubReg;
556     if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
557       break;
558     Src = CopySrcReg;
559     SrcSubReg = CopySrcSubReg;
560
561     // Do not extend the live-ranges of physical registers as they add
562     // constraints to the register allocator.
563     // Moreover, if we want to extend the live-range of a physical register,
564     // unlike SSA virtual register, we will have to check that they are not
565     // redefine before the related use.
566     if (TargetRegisterInfo::isPhysicalRegister(Src))
567       break;
568
569     const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
570
571     // If this source does not incur a cross register bank copy, use it.
572     ShouldRewrite = shareSameRegisterFile(TRI, DefRC, DefSubReg, SrcRC,
573                                           SrcSubReg);
574   } while (!ShouldRewrite);
575
576   // If we did not find a more suitable source, there is nothing to optimize.
577   if (!ShouldRewrite || Src == Reg)
578     return false;
579
580   Reg = Src;
581   SubReg = SrcSubReg;
582   return true;
583 }
584
585 namespace {
586 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
587 class CopyRewriter {
588 protected:
589   /// The copy-like instruction.
590   MachineInstr &CopyLike;
591   /// The index of the source being rewritten.
592   unsigned CurrentSrcIdx;
593
594 public:
595   CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
596
597   virtual ~CopyRewriter() {}
598
599   /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
600   /// the related value that it affects (TrackReg, TrackSubReg).
601   /// A source is considered rewritable if its register class and the
602   /// register class of the related TrackReg may not be register
603   /// coalescer friendly. In other words, given a copy-like instruction
604   /// not all the arguments may be returned at rewritable source, since
605   /// some arguments are none to be register coalescer friendly.
606   ///
607   /// Each call of this method moves the current source to the next
608   /// rewritable source.
609   /// For instance, let CopyLike be the instruction to rewrite.
610   /// CopyLike has one definition and one source:
611   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
612   ///
613   /// The first call will give the first rewritable source, i.e.,
614   /// the only source this instruction has:
615   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
616   /// This source defines the whole definition, i.e.,
617   /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
618   ///
619   /// The second and subsequent calls will return false, has there is only one
620   /// rewritable source.
621   ///
622   /// \return True if a rewritable source has been found, false otherwise.
623   /// The output arguments are valid if and only if true is returned.
624   virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
625                                        unsigned &TrackReg,
626                                        unsigned &TrackSubReg) {
627     // If CurrentSrcIdx == 1, this means this function has already been
628     // called once. CopyLike has one defintiion and one argument, thus,
629     // there is nothing else to rewrite.
630     if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
631       return false;
632     // This is the first call to getNextRewritableSource.
633     // Move the CurrentSrcIdx to remember that we made that call.
634     CurrentSrcIdx = 1;
635     // The rewritable source is the argument.
636     const MachineOperand &MOSrc = CopyLike.getOperand(1);
637     SrcReg = MOSrc.getReg();
638     SrcSubReg = MOSrc.getSubReg();
639     // What we track are the alternative sources of the definition.
640     const MachineOperand &MODef = CopyLike.getOperand(0);
641     TrackReg = MODef.getReg();
642     TrackSubReg = MODef.getSubReg();
643     return true;
644   }
645
646   /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
647   /// if possible.
648   /// \return True if the rewritting was possible, false otherwise.
649   virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
650     if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
651       return false;
652     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
653     MOSrc.setReg(NewReg);
654     MOSrc.setSubReg(NewSubReg);
655     return true;
656   }
657 };
658
659 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
660 class InsertSubregRewriter : public CopyRewriter {
661 public:
662   InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
663     assert(MI.isInsertSubreg() && "Invalid instruction");
664   }
665
666   /// \brief See CopyRewriter::getNextRewritableSource.
667   /// Here CopyLike has the following form:
668   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
669   /// Src1 has the same register class has dst, hence, there is
670   /// nothing to rewrite.
671   /// Src2.src2SubIdx, may not be register coalescer friendly.
672   /// Therefore, the first call to this method returns:
673   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
674   /// (TrackReg, TrackSubReg) = (dst, subIdx).
675   ///
676   /// Subsequence calls will return false.
677   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
678                                unsigned &TrackReg,
679                                unsigned &TrackSubReg) override {
680     // If we already get the only source we can rewrite, return false.
681     if (CurrentSrcIdx == 2)
682       return false;
683     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
684     CurrentSrcIdx = 2;
685     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
686     SrcReg = MOInsertedReg.getReg();
687     SrcSubReg = MOInsertedReg.getSubReg();
688     const MachineOperand &MODef = CopyLike.getOperand(0);
689
690     // We want to track something that is compatible with the
691     // partial definition.
692     TrackReg = MODef.getReg();
693     if (MODef.getSubReg())
694       // Bails if we have to compose sub-register indices.
695       return false;
696     TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
697     return true;
698   }
699   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
700     if (CurrentSrcIdx != 2)
701       return false;
702     // We are rewriting the inserted reg.
703     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
704     MO.setReg(NewReg);
705     MO.setSubReg(NewSubReg);
706     return true;
707   }
708 };
709
710 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
711 class ExtractSubregRewriter : public CopyRewriter {
712   const TargetInstrInfo &TII;
713
714 public:
715   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
716       : CopyRewriter(MI), TII(TII) {
717     assert(MI.isExtractSubreg() && "Invalid instruction");
718   }
719
720   /// \brief See CopyRewriter::getNextRewritableSource.
721   /// Here CopyLike has the following form:
722   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
723   /// There is only one rewritable source: Src.subIdx,
724   /// which defines dst.dstSubIdx.
725   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
726                                unsigned &TrackReg,
727                                unsigned &TrackSubReg) override {
728     // If we already get the only source we can rewrite, return false.
729     if (CurrentSrcIdx == 1)
730       return false;
731     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
732     CurrentSrcIdx = 1;
733     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
734     SrcReg = MOExtractedReg.getReg();
735     // If we have to compose sub-register indices, bails out.
736     if (MOExtractedReg.getSubReg())
737       return false;
738
739     SrcSubReg = CopyLike.getOperand(2).getImm();
740
741     // We want to track something that is compatible with the definition.
742     const MachineOperand &MODef = CopyLike.getOperand(0);
743     TrackReg = MODef.getReg();
744     TrackSubReg = MODef.getSubReg();
745     return true;
746   }
747
748   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
749     // The only source we can rewrite is the input register.
750     if (CurrentSrcIdx != 1)
751       return false;
752
753     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
754
755     // If we find a source that does not require to extract something,
756     // rewrite the operation with a copy.
757     if (!NewSubReg) {
758       // Move the current index to an invalid position.
759       // We do not want another call to this method to be able
760       // to do any change.
761       CurrentSrcIdx = -1;
762       // Rewrite the operation as a COPY.
763       // Get rid of the sub-register index.
764       CopyLike.RemoveOperand(2);
765       // Morph the operation into a COPY.
766       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
767       return true;
768     }
769     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
770     return true;
771   }
772 };
773
774 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
775 class RegSequenceRewriter : public CopyRewriter {
776 public:
777   RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
778     assert(MI.isRegSequence() && "Invalid instruction");
779   }
780
781   /// \brief See CopyRewriter::getNextRewritableSource.
782   /// Here CopyLike has the following form:
783   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
784   /// Each call will return a different source, walking all the available
785   /// source.
786   ///
787   /// The first call returns:
788   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
789   /// (TrackReg, TrackSubReg) = (dst, subIdx1).
790   ///
791   /// The second call returns:
792   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
793   /// (TrackReg, TrackSubReg) = (dst, subIdx2).
794   ///
795   /// And so on, until all the sources have been traversed, then
796   /// it returns false.
797   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
798                                unsigned &TrackReg,
799                                unsigned &TrackSubReg) override {
800     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
801
802     // If this is the first call, move to the first argument.
803     if (CurrentSrcIdx == 0) {
804       CurrentSrcIdx = 1;
805     } else {
806       // Otherwise, move to the next argument and check that it is valid.
807       CurrentSrcIdx += 2;
808       if (CurrentSrcIdx >= CopyLike.getNumOperands())
809         return false;
810     }
811     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
812     SrcReg = MOInsertedReg.getReg();
813     // If we have to compose sub-register indices, bails out.
814     if ((SrcSubReg = MOInsertedReg.getSubReg()))
815       return false;
816
817     // We want to track something that is compatible with the related
818     // partial definition.
819     TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
820
821     const MachineOperand &MODef = CopyLike.getOperand(0);
822     TrackReg = MODef.getReg();
823     // If we have to compose sub-registers, bails.
824     return MODef.getSubReg() == 0;
825   }
826
827   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
828     // We cannot rewrite out of bound operands.
829     // Moreover, rewritable sources are at odd positions.
830     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
831       return false;
832
833     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
834     MO.setReg(NewReg);
835     MO.setSubReg(NewSubReg);
836     return true;
837   }
838 };
839 } // End namespace.
840
841 /// \brief Get the appropriated CopyRewriter for \p MI.
842 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
843 /// if no rewriter works for \p MI.
844 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
845                                      const TargetInstrInfo &TII) {
846   switch (MI.getOpcode()) {
847   default:
848     return nullptr;
849   case TargetOpcode::COPY:
850     return new CopyRewriter(MI);
851   case TargetOpcode::INSERT_SUBREG:
852     return new InsertSubregRewriter(MI);
853   case TargetOpcode::EXTRACT_SUBREG:
854     return new ExtractSubregRewriter(MI, TII);
855   case TargetOpcode::REG_SEQUENCE:
856     return new RegSequenceRewriter(MI);
857   }
858   llvm_unreachable(nullptr);
859 }
860
861 /// \brief Optimize generic copy instructions to avoid cross
862 /// register bank copy. The optimization looks through a chain of
863 /// copies and tries to find a source that has a compatible register
864 /// class.
865 /// Two register classes are considered to be compatible if they share
866 /// the same register bank.
867 /// New copies issued by this optimization are register allocator
868 /// friendly. This optimization does not remove any copy as it may
869 /// overconstraint the register allocator, but replaces some operands
870 /// when possible.
871 /// \pre isCoalescableCopy(*MI) is true.
872 /// \return True, when \p MI has been rewritten. False otherwise.
873 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
874   assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
875   assert(MI->getDesc().getNumDefs() == 1 &&
876          "Coalescer can understand multiple defs?!");
877   const MachineOperand &MODef = MI->getOperand(0);
878   // Do not rewrite physical definitions.
879   if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
880     return false;
881
882   bool Changed = false;
883   // Get the right rewriter for the current copy.
884   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
885   // If none exists, bails out.
886   if (!CpyRewriter)
887     return false;
888   // Rewrite each rewritable source.
889   unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
890   while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
891                                               TrackSubReg)) {
892     unsigned NewSrc = TrackReg;
893     unsigned NewSubReg = TrackSubReg;
894     // Try to find a more suitable source.
895     // If we failed to do so, or get the actual source,
896     // move to the next source.
897     if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
898       continue;
899     // Rewrite source.
900     Changed |= CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg);
901   }
902   // TODO: We could have a clean-up method to tidy the instruction.
903   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
904   // => v0 = COPY v1
905   // Currently we haven't seen motivating example for that and we
906   // want to avoid untested code.
907   NumRewrittenCopies += Changed == true;
908   return Changed;
909 }
910
911 /// \brief Optimize copy-like instructions to create
912 /// register coalescer friendly instruction.
913 /// The optimization tries to kill-off the \p MI by looking
914 /// through a chain of copies to find a source that has a compatible
915 /// register class.
916 /// If such a source is found, it replace \p MI by a generic COPY
917 /// operation.
918 /// \pre isUncoalescableCopy(*MI) is true.
919 /// \return True, when \p MI has been optimized. In that case, \p MI has
920 /// been removed from its parent.
921 /// All COPY instructions created, are inserted in \p LocalMIs.
922 bool PeepholeOptimizer::optimizeUncoalescableCopy(
923     MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
924   assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
925
926   // Check if we can rewrite all the values defined by this instruction.
927   SmallVector<
928       std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
929       4> RewritePairs;
930   for (const MachineOperand &MODef : MI->defs()) {
931     if (MODef.isDead())
932       // We can ignore those.
933       continue;
934
935     // If a physical register is here, this is probably for a good reason.
936     // Do not rewrite that.
937     if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
938       return false;
939
940     // If we do not know how to rewrite this definition, there is no point
941     // in trying to kill this instruction.
942     TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
943     TargetInstrInfo::RegSubRegPair Src = Def;
944     if (!findNextSource(Src.Reg, Src.SubReg))
945       return false;
946     RewritePairs.push_back(std::make_pair(Def, Src));
947   }
948   // The change is possible for all defs, do it.
949   for (const auto &PairDefSrc : RewritePairs) {
950     const auto &Def = PairDefSrc.first;
951     const auto &Src = PairDefSrc.second;
952     // Rewrite the "copy" in a way the register coalescer understands.
953     assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
954            "We do not rewrite physical registers");
955     const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
956     unsigned NewVR = MRI->createVirtualRegister(DefRC);
957     MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
958                                     TII->get(TargetOpcode::COPY),
959                                     NewVR).addReg(Src.Reg, 0, Src.SubReg);
960     NewCopy->getOperand(0).setSubReg(Def.SubReg);
961     if (Def.SubReg)
962       NewCopy->getOperand(0).setIsUndef();
963     LocalMIs.insert(NewCopy);
964     MRI->replaceRegWith(Def.Reg, NewVR);
965     MRI->clearKillFlags(NewVR);
966     // We extended the lifetime of Src.
967     // Clear the kill flags to account for that.
968     MRI->clearKillFlags(Src.Reg);
969   }
970   // MI is now dead.
971   MI->eraseFromParent();
972   ++NumUncoalescableCopies;
973   return true;
974 }
975
976 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
977 /// instruction. We only fold loads to virtual registers and the virtual
978 /// register defined has a single use.
979 bool PeepholeOptimizer::isLoadFoldable(
980                               MachineInstr *MI,
981                               SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
982   if (!MI->canFoldAsLoad() || !MI->mayLoad())
983     return false;
984   const MCInstrDesc &MCID = MI->getDesc();
985   if (MCID.getNumDefs() != 1)
986     return false;
987
988   unsigned Reg = MI->getOperand(0).getReg();
989   // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
990   // loads. It should be checked when processing uses of the load, since
991   // uses can be removed during peephole.
992   if (!MI->getOperand(0).getSubReg() &&
993       TargetRegisterInfo::isVirtualRegister(Reg) &&
994       MRI->hasOneNonDBGUse(Reg)) {
995     FoldAsLoadDefCandidates.insert(Reg);
996     return true;
997   }
998   return false;
999 }
1000
1001 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1002                                         SmallSet<unsigned, 4> &ImmDefRegs,
1003                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1004   const MCInstrDesc &MCID = MI->getDesc();
1005   if (!MI->isMoveImmediate())
1006     return false;
1007   if (MCID.getNumDefs() != 1)
1008     return false;
1009   unsigned Reg = MI->getOperand(0).getReg();
1010   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1011     ImmDefMIs.insert(std::make_pair(Reg, MI));
1012     ImmDefRegs.insert(Reg);
1013     return true;
1014   }
1015
1016   return false;
1017 }
1018
1019 /// foldImmediate - Try folding register operands that are defined by move
1020 /// immediate instructions, i.e. a trivial constant folding optimization, if
1021 /// and only if the def and use are in the same BB.
1022 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1023                                       SmallSet<unsigned, 4> &ImmDefRegs,
1024                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1025   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1026     MachineOperand &MO = MI->getOperand(i);
1027     if (!MO.isReg() || MO.isDef())
1028       continue;
1029     unsigned Reg = MO.getReg();
1030     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1031       continue;
1032     if (ImmDefRegs.count(Reg) == 0)
1033       continue;
1034     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1035     assert(II != ImmDefMIs.end());
1036     if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1037       ++NumImmFold;
1038       return true;
1039     }
1040   }
1041   return false;
1042 }
1043
1044 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1045   if (skipOptnoneFunction(*MF.getFunction()))
1046     return false;
1047
1048   DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1049   DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1050
1051   if (DisablePeephole)
1052     return false;
1053
1054   TM  = &MF.getTarget();
1055   TII = TM->getSubtargetImpl()->getInstrInfo();
1056   MRI = &MF.getRegInfo();
1057   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1058
1059   bool Changed = false;
1060
1061   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1062     MachineBasicBlock *MBB = &*I;
1063
1064     bool SeenMoveImm = false;
1065     SmallPtrSet<MachineInstr*, 16> LocalMIs;
1066     SmallSet<unsigned, 4> ImmDefRegs;
1067     DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1068     SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1069
1070     for (MachineBasicBlock::iterator
1071            MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1072       MachineInstr *MI = &*MII;
1073       // We may be erasing MI below, increment MII now.
1074       ++MII;
1075       LocalMIs.insert(MI);
1076
1077       // Skip debug values. They should not affect this peephole optimization.
1078       if (MI->isDebugValue())
1079           continue;
1080
1081       // If there exists an instruction which belongs to the following
1082       // categories, we will discard the load candidates.
1083       if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1084           MI->isKill() || MI->isInlineAsm() ||
1085           MI->hasUnmodeledSideEffects()) {
1086         FoldAsLoadDefCandidates.clear();
1087         continue;
1088       }
1089       if (MI->mayStore() || MI->isCall())
1090         FoldAsLoadDefCandidates.clear();
1091
1092       if ((isUncoalescableCopy(*MI) &&
1093            optimizeUncoalescableCopy(MI, LocalMIs)) ||
1094           (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1095           (MI->isSelect() && optimizeSelect(MI))) {
1096         // MI is deleted.
1097         LocalMIs.erase(MI);
1098         Changed = true;
1099         continue;
1100       }
1101
1102       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1103         // MI is just rewritten.
1104         Changed = true;
1105         continue;
1106       }
1107
1108       if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1109         SeenMoveImm = true;
1110       } else {
1111         Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1112         // optimizeExtInstr might have created new instructions after MI
1113         // and before the already incremented MII. Adjust MII so that the
1114         // next iteration sees the new instructions.
1115         MII = MI;
1116         ++MII;
1117         if (SeenMoveImm)
1118           Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1119       }
1120
1121       // Check whether MI is a load candidate for folding into a later
1122       // instruction. If MI is not a candidate, check whether we can fold an
1123       // earlier load into MI.
1124       if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1125           !FoldAsLoadDefCandidates.empty()) {
1126         const MCInstrDesc &MIDesc = MI->getDesc();
1127         for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1128              ++i) {
1129           const MachineOperand &MOp = MI->getOperand(i);
1130           if (!MOp.isReg())
1131             continue;
1132           unsigned FoldAsLoadDefReg = MOp.getReg();
1133           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1134             // We need to fold load after optimizeCmpInstr, since
1135             // optimizeCmpInstr can enable folding by converting SUB to CMP.
1136             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1137             // we need it for markUsesInDebugValueAsUndef().
1138             unsigned FoldedReg = FoldAsLoadDefReg;
1139             MachineInstr *DefMI = nullptr;
1140             MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1141                                                           FoldAsLoadDefReg,
1142                                                           DefMI);
1143             if (FoldMI) {
1144               // Update LocalMIs since we replaced MI with FoldMI and deleted
1145               // DefMI.
1146               DEBUG(dbgs() << "Replacing: " << *MI);
1147               DEBUG(dbgs() << "     With: " << *FoldMI);
1148               LocalMIs.erase(MI);
1149               LocalMIs.erase(DefMI);
1150               LocalMIs.insert(FoldMI);
1151               MI->eraseFromParent();
1152               DefMI->eraseFromParent();
1153               MRI->markUsesInDebugValueAsUndef(FoldedReg);
1154               FoldAsLoadDefCandidates.erase(FoldedReg);
1155               ++NumLoadFold;
1156               // MI is replaced with FoldMI.
1157               Changed = true;
1158               break;
1159             }
1160           }
1161         }
1162       }
1163     }
1164   }
1165
1166   return Changed;
1167 }
1168
1169 bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
1170                                          unsigned &SrcSubReg) {
1171   assert(Def->isCopy() && "Invalid definition");
1172   // Copy instruction are supposed to be: Def = Src.
1173   // If someone breaks this assumption, bad things will happen everywhere.
1174   assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1175
1176   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1177     // If we look for a different subreg, it means we want a subreg of src.
1178     // Bails as we do not support composing subreg yet.
1179     return false;
1180   // Otherwise, we want the whole source.
1181   const MachineOperand &Src = Def->getOperand(1);
1182   SrcReg = Src.getReg();
1183   SrcSubReg = Src.getSubReg();
1184   return true;
1185 }
1186
1187 bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
1188                                             unsigned &SrcSubReg) {
1189   assert(Def->isBitcast() && "Invalid definition");
1190
1191   // Bail if there are effects that a plain copy will not expose.
1192   if (Def->hasUnmodeledSideEffects())
1193     return false;
1194
1195   // Bitcasts with more than one def are not supported.
1196   if (Def->getDesc().getNumDefs() != 1)
1197     return false;
1198   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1199     // If we look for a different subreg, it means we want a subreg of the src.
1200     // Bails as we do not support composing subreg yet.
1201     return false;
1202
1203   unsigned SrcIdx = Def->getNumOperands();
1204   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1205        ++OpIdx) {
1206     const MachineOperand &MO = Def->getOperand(OpIdx);
1207     if (!MO.isReg() || !MO.getReg())
1208       continue;
1209     assert(!MO.isDef() && "We should have skipped all the definitions by now");
1210     if (SrcIdx != EndOpIdx)
1211       // Multiple sources?
1212       return false;
1213     SrcIdx = OpIdx;
1214   }
1215   const MachineOperand &Src = Def->getOperand(SrcIdx);
1216   SrcReg = Src.getReg();
1217   SrcSubReg = Src.getSubReg();
1218   return true;
1219 }
1220
1221 bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
1222                                                 unsigned &SrcSubReg) {
1223   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1224          "Invalid definition");
1225
1226   if (Def->getOperand(DefIdx).getSubReg())
1227     // If we are composing subreg, bails out.
1228     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1229     // This should almost never happen as the SSA property is tracked at
1230     // the register level (as opposed to the subreg level).
1231     // I.e.,
1232     // Def.sub0 =
1233     // Def.sub1 =
1234     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1235     // Def. Thus, it must not be generated.
1236     // However, some code could theoretically generates a single
1237     // Def.sub0 (i.e, not defining the other subregs) and we would
1238     // have this case.
1239     // If we can ascertain (or force) that this never happens, we could
1240     // turn that into an assertion.
1241     return false;
1242
1243   if (!TII)
1244     // We could handle the REG_SEQUENCE here, but we do not want to
1245     // duplicate the code from the generic TII.
1246     return false;
1247
1248   SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1249   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1250     return false;
1251
1252   // We are looking at:
1253   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1254   // Check if one of the operand defines the subreg we are interested in.
1255   for (auto &RegSeqInput : RegSeqInputRegs) {
1256     if (RegSeqInput.SubIdx == DefSubReg) {
1257       if (RegSeqInput.SubReg)
1258         // Bails if we have to compose sub registers.
1259         return false;
1260
1261       SrcReg = RegSeqInput.Reg;
1262       SrcSubReg = RegSeqInput.SubReg;
1263       return true;
1264     }
1265   }
1266
1267   // If the subreg we are tracking is super-defined by another subreg,
1268   // we could follow this value. However, this would require to compose
1269   // the subreg and we do not do that for now.
1270   return false;
1271 }
1272
1273 /// Extract the inputs from INSERT_SUBREG.
1274 /// INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
1275 /// - BaseReg: vreg0:sub0
1276 /// - InsertedReg: vreg1:sub1, sub3
1277 static void
1278 getInsertSubregInputs(const MachineInstr &MI,
1279                       TargetInstrInfo::RegSubRegPair &BaseReg,
1280                       TargetInstrInfo::RegSubRegPairAndIdx &InsertedReg) {
1281   assert(MI.isInsertSubreg() && "Instruction do not have the proper type");
1282
1283   // We are looking at:
1284   // Def = INSERT_SUBREG v0, v1, sub0.
1285   const MachineOperand &MOBaseReg = MI.getOperand(1);
1286   const MachineOperand &MOInsertedReg = MI.getOperand(2);
1287   const MachineOperand &MOSubIdx = MI.getOperand(3);
1288   assert(MOSubIdx.isImm() &&
1289          "One of the subindex of the reg_sequence is not an immediate");
1290   BaseReg.Reg = MOBaseReg.getReg();
1291   BaseReg.SubReg = MOBaseReg.getSubReg();
1292
1293   InsertedReg.Reg = MOInsertedReg.getReg();
1294   InsertedReg.SubReg = MOInsertedReg.getSubReg();
1295   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
1296 }
1297
1298 bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
1299                                                  unsigned &SrcSubReg) {
1300   assert(Def->isInsertSubreg() && "Invalid definition");
1301   if (Def->getOperand(DefIdx).getSubReg())
1302     // If we are composing subreg, bails out.
1303     // Same remark as getNextSourceFromRegSequence.
1304     // I.e., this may be turned into an assert.
1305     return false;
1306
1307   TargetInstrInfo::RegSubRegPair BaseReg;
1308   TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1309   assert(DefIdx == 0 && "Invalid definition");
1310   getInsertSubregInputs(*Def, BaseReg, InsertedReg);
1311
1312   // We are looking at:
1313   // Def = INSERT_SUBREG v0, v1, sub1
1314   // There are two cases:
1315   // 1. DefSubReg == sub1, get v1.
1316   // 2. DefSubReg != sub1, the value may be available through v0.
1317
1318   // #1 Check if the inserted register matches the required sub index.
1319   if (InsertedReg.SubIdx == DefSubReg) {
1320     SrcReg = InsertedReg.Reg;
1321     SrcSubReg = InsertedReg.SubReg;
1322     return true;
1323   }
1324   // #2 Otherwise, if the sub register we are looking for is not partial
1325   // defined by the inserted element, we can look through the main
1326   // register (v0).
1327   const MachineOperand &MODef = Def->getOperand(DefIdx);
1328   // If the result register (Def) and the base register (v0) do not
1329   // have the same register class or if we have to compose
1330   // subregisters, bails out.
1331   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1332       BaseReg.SubReg)
1333     return false;
1334
1335   // Get the TRI and check if the inserted sub-register overlaps with the
1336   // sub-register we are tracking.
1337   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1338   if (!TRI ||
1339       (TRI->getSubRegIndexLaneMask(DefSubReg) &
1340        TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1341     return false;
1342   // At this point, the value is available in v0 via the same subreg
1343   // we used for Def.
1344   SrcReg = BaseReg.Reg;
1345   SrcSubReg = DefSubReg;
1346   return true;
1347 }
1348
1349 /// Extract the inputs from EXTRACT_SUBREG.
1350 /// EXTRACT_SUBREG vreg1:sub1, sub0, would produce:
1351 /// - vreg1:sub1, sub0
1352 static void
1353 getExtractSubregInputs(const MachineInstr &MI,
1354                        TargetInstrInfo::RegSubRegPairAndIdx &InputReg) {
1355   assert(MI.isExtractSubreg() && "Instruction do not have the proper type");
1356   // We are looking at:
1357   // Def = EXTRACT_SUBREG v0.sub1, sub0.
1358   const MachineOperand &MOReg = MI.getOperand(1);
1359   const MachineOperand &MOSubIdx = MI.getOperand(2);
1360   assert(MOSubIdx.isImm() &&
1361          "The subindex of the extract_subreg is not an immediate");
1362
1363   InputReg.Reg = MOReg.getReg();
1364   InputReg.SubReg = MOReg.getSubReg();
1365   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
1366 }
1367
1368 bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
1369                                                   unsigned &SrcSubReg) {
1370   assert(Def->isExtractSubreg() && "Invalid definition");
1371   // We are looking at:
1372   // Def = EXTRACT_SUBREG v0, sub0
1373
1374   // Bails if we have to compose sub registers.
1375   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1376   if (DefSubReg)
1377     return false;
1378
1379   TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1380   assert(DefIdx == 0 && "Invalid definition");
1381   getExtractSubregInputs(*Def, ExtractSubregInputReg);
1382
1383   // Bails if we have to compose sub registers.
1384   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1385   if (ExtractSubregInputReg.SubReg)
1386     return false;
1387   // Otherwise, the value is available in the v0.sub0.
1388   SrcReg = ExtractSubregInputReg.Reg;
1389   SrcSubReg = ExtractSubregInputReg.SubIdx;
1390   return true;
1391 }
1392
1393 bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
1394                                                 unsigned &SrcSubReg) {
1395   assert(Def->isSubregToReg() && "Invalid definition");
1396   // We are looking at:
1397   // Def = SUBREG_TO_REG Imm, v0, sub0
1398
1399   // Bails if we have to compose sub registers.
1400   // If DefSubReg != sub0, we would have to check that all the bits
1401   // we track are included in sub0 and if yes, we would have to
1402   // determine the right subreg in v0.
1403   if (DefSubReg != Def->getOperand(3).getImm())
1404     return false;
1405   // Bails if we have to compose sub registers.
1406   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1407   if (Def->getOperand(2).getSubReg())
1408     return false;
1409
1410   SrcReg = Def->getOperand(2).getReg();
1411   SrcSubReg = Def->getOperand(3).getImm();
1412   return true;
1413 }
1414
1415 bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
1416   assert(Def && "This method needs a valid definition");
1417
1418   assert(
1419       (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1420       Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1421   if (Def->isCopy())
1422     return getNextSourceFromCopy(SrcReg, SrcSubReg);
1423   if (Def->isBitcast())
1424     return getNextSourceFromBitcast(SrcReg, SrcSubReg);
1425   // All the remaining cases involve "complex" instructions.
1426   // Bails if we did not ask for the advanced tracking.
1427   if (!UseAdvancedTracking)
1428     return false;
1429   if (Def->isRegSequence() || Def->isRegSequenceLike())
1430     return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
1431   if (Def->isInsertSubreg())
1432     return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
1433   if (Def->isExtractSubreg())
1434     return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
1435   if (Def->isSubregToReg())
1436     return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
1437   return false;
1438 }
1439
1440 const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
1441                                                 unsigned &SrcSubReg) {
1442   // If we reach a point where we cannot move up in the use-def chain,
1443   // there is nothing we can get.
1444   if (!Def)
1445     return nullptr;
1446
1447   const MachineInstr *PrevDef = nullptr;
1448   // Try to find the next source.
1449   if (getNextSourceImpl(SrcReg, SrcSubReg)) {
1450     // Update definition, definition index, and subregister for the
1451     // next call of getNextSource.
1452     // Update the current register.
1453     Reg = SrcReg;
1454     // Update the return value before moving up in the use-def chain.
1455     PrevDef = Def;
1456     // If we can still move up in the use-def chain, move to the next
1457     // defintion.
1458     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
1459       Def = MRI.getVRegDef(Reg);
1460       DefIdx = MRI.def_begin(Reg).getOperandNo();
1461       DefSubReg = SrcSubReg;
1462       return PrevDef;
1463     }
1464   }
1465   // If we end up here, this means we will not be able to find another source
1466   // for the next iteration.
1467   // Make sure any new call to getNextSource bails out early by cutting the
1468   // use-def chain.
1469   Def = nullptr;
1470   return PrevDef;
1471 }