1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Perform peephole optimizations on the machine code:
12 // - Optimize Extensions
14 // Optimization of sign / zero extension instructions. It may be extended to
15 // handle other instructions with similar properties.
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.
22 // - Optimize Comparisons
24 // Optimization of comparison instructions. For instance, in this code:
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.
34 // Another instance, in this code:
36 // sub r1, r3 | sub r1, imm
37 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
40 // If the branch instruction can use flag from "sub", then we can replace
41 // "sub" with "subs" and eliminate the "cmp" instruction.
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
49 // - Optimize Copies and Bitcast (more generally, target specific copies):
51 // Rewrite copies and bitcasts to avoid cross register bank copies
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
58 // b = copy A <-- cross-bank copy
59 // C = copy A <-- same-bank copy
62 // b = bitcast A <-- cross-bank copy
63 // C = bitcast b <-- cross-bank copy
65 // b = bitcast A <-- cross-bank copy
66 // C = copy A <-- same-bank copy
67 //===----------------------------------------------------------------------===//
69 #include "llvm/ADT/DenseMap.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/CodeGen/MachineBasicBlock.h"
75 #include "llvm/CodeGen/MachineDominators.h"
76 #include "llvm/CodeGen/MachineFunction.h"
77 #include "llvm/CodeGen/MachineInstr.h"
78 #include "llvm/CodeGen/MachineInstrBuilder.h"
79 #include "llvm/CodeGen/MachineLoopInfo.h"
80 #include "llvm/CodeGen/MachineOperand.h"
81 #include "llvm/CodeGen/MachineRegisterInfo.h"
82 #include "llvm/CodeGen/Passes.h"
83 #include "llvm/MC/MCInstrDesc.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetInstrInfo.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
90 #include "llvm/Target/TargetSubtargetInfo.h"
98 #define DEBUG_TYPE "peephole-opt"
100 // Optimize Extensions
102 Aggressive("aggressive-ext-opt", cl::Hidden,
103 cl::desc("Aggressive extension optimization"));
106 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
107 cl::desc("Disable the peephole optimizer"));
110 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
111 cl::desc("Disable advanced copy optimization"));
113 static cl::opt<bool> DisableNAPhysCopyOpt(
114 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
115 cl::desc("Disable non-allocatable physical register copy optimization"));
117 // Limit the number of PHI instructions to process
118 // in PeepholeOptimizer::getNextSource.
119 static cl::opt<unsigned> RewritePHILimit(
120 "rewrite-phi-limit", cl::Hidden, cl::init(10),
121 cl::desc("Limit the length of PHI chains to lookup"));
123 // Limit the length of recurrence chain when evaluating the benefit of
124 // commuting operands.
125 static cl::opt<unsigned> MaxRecurrenceChain(
126 "recurrence-chain-limit", cl::Hidden, cl::init(3),
127 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
128 "of commuting operands"));
131 STATISTIC(NumReuse, "Number of extension results reused");
132 STATISTIC(NumCmps, "Number of compares eliminated");
133 STATISTIC(NumImmFold, "Number of move immediate folded");
134 STATISTIC(NumLoadFold, "Number of loads folded");
135 STATISTIC(NumSelects, "Number of selects optimized");
136 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
137 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
138 STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
142 class ValueTrackerResult;
143 class RecurrenceInstr;
145 class PeepholeOptimizer : public MachineFunctionPass {
146 const TargetInstrInfo *TII;
147 const TargetRegisterInfo *TRI;
148 MachineRegisterInfo *MRI;
149 MachineDominatorTree *DT; // Machine dominator tree
150 MachineLoopInfo *MLI;
153 static char ID; // Pass identification
155 PeepholeOptimizer() : MachineFunctionPass(ID) {
156 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
159 bool runOnMachineFunction(MachineFunction &MF) override;
161 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 AU.setPreservesCFG();
163 MachineFunctionPass::getAnalysisUsage(AU);
164 AU.addRequired<MachineLoopInfo>();
165 AU.addPreserved<MachineLoopInfo>();
167 AU.addRequired<MachineDominatorTree>();
168 AU.addPreserved<MachineDominatorTree>();
172 /// \brief Track Def -> Use info used for rewriting copies.
173 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
176 /// \brief Sequence of instructions that formulate recurrence cycle.
177 typedef SmallVector<RecurrenceInstr, 4> RecurrenceCycle;
180 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
181 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
182 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
183 bool optimizeSelect(MachineInstr *MI,
184 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
185 bool optimizeCondBranch(MachineInstr *MI);
186 bool optimizeCoalescableCopy(MachineInstr *MI);
187 bool optimizeUncoalescableCopy(MachineInstr *MI,
188 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
189 bool optimizeRecurrence(MachineInstr &PHI);
190 bool findNextSource(unsigned Reg, unsigned SubReg,
191 RewriteMapTy &RewriteMap);
192 bool isMoveImmediate(MachineInstr *MI,
193 SmallSet<unsigned, 4> &ImmDefRegs,
194 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
195 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
196 SmallSet<unsigned, 4> &ImmDefRegs,
197 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
198 /// \brief Finds recurrence cycles, but only ones that formulated around
199 /// a def operand and a use operand that are tied. If there is a use
200 /// operand commutable with the tied use operand, find recurrence cycle
201 /// along that operand as well.
202 bool findTargetRecurrence(unsigned Reg,
203 const SmallSet<unsigned, 2> &TargetReg,
204 RecurrenceCycle &RC);
206 /// \brief If copy instruction \p MI is a virtual register copy, track it in
207 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
208 /// previously seen as a copy, replace the uses of this copy with the
209 /// previously seen copy's destination register.
210 bool foldRedundantCopy(MachineInstr *MI,
211 SmallSet<unsigned, 4> &CopySrcRegs,
212 DenseMap<unsigned, MachineInstr *> &CopyMIs);
214 /// \brief Is the register \p Reg a non-allocatable physical register?
215 bool isNAPhysCopy(unsigned Reg);
217 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
218 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
219 /// non-allocatable physical register was previously copied to a virtual
220 /// registered and hasn't been clobbered, the virt->phys copy can be
222 bool foldRedundantNAPhysCopy(
224 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
226 bool isLoadFoldable(MachineInstr *MI,
227 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
229 /// \brief Check whether \p MI is understood by the register coalescer
230 /// but may require some rewriting.
231 bool isCoalescableCopy(const MachineInstr &MI) {
232 // SubregToRegs are not interesting, because they are already register
233 // coalescer friendly.
234 return MI.isCopy() || (!DisableAdvCopyOpt &&
235 (MI.isRegSequence() || MI.isInsertSubreg() ||
236 MI.isExtractSubreg()));
239 /// \brief Check whether \p MI is a copy like instruction that is
240 /// not recognized by the register coalescer.
241 bool isUncoalescableCopy(const MachineInstr &MI) {
242 return MI.isBitcast() ||
243 (!DisableAdvCopyOpt &&
244 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
245 MI.isExtractSubregLike()));
249 /// \brief Helper class to hold instructions that are inside recurrence
250 /// cycles. The recurrence cycle is formulated around 1) a def operand and its
251 /// tied use operand, or 2) a def operand and a use operand that is commutable
252 /// with another use operand which is tied to the def operand. In the latter
253 /// case, index of the tied use operand and the commutable use operand are
254 /// maintained with CommutePair.
255 class RecurrenceInstr {
257 typedef std::pair<unsigned, unsigned> IndexPair;
259 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
260 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
261 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
263 MachineInstr *getMI() const { return MI; }
264 Optional<IndexPair> getCommutePair() const { return CommutePair; }
268 Optional<IndexPair> CommutePair;
271 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
272 /// returned sources for a given search and the instructions where the sources
273 /// were tracked from.
274 class ValueTrackerResult {
276 /// Track all sources found by one ValueTracker query.
277 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
279 /// Instruction using the sources in 'RegSrcs'.
280 const MachineInstr *Inst;
283 ValueTrackerResult() : Inst(nullptr) {}
284 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
285 addSource(Reg, SubReg);
288 bool isValid() const { return getNumSources() > 0; }
290 void setInst(const MachineInstr *I) { Inst = I; }
291 const MachineInstr *getInst() const { return Inst; }
298 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
299 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
302 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
303 assert(Idx < getNumSources() && "Reg pair source out of index");
304 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
307 int getNumSources() const { return RegSrcs.size(); }
309 unsigned getSrcReg(int Idx) const {
310 assert(Idx < getNumSources() && "Reg source out of index");
311 return RegSrcs[Idx].Reg;
314 unsigned getSrcSubReg(int Idx) const {
315 assert(Idx < getNumSources() && "SubReg source out of index");
316 return RegSrcs[Idx].SubReg;
319 bool operator==(const ValueTrackerResult &Other) {
320 if (Other.getInst() != getInst())
323 if (Other.getNumSources() != getNumSources())
326 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
327 if (Other.getSrcReg(i) != getSrcReg(i) ||
328 Other.getSrcSubReg(i) != getSrcSubReg(i))
334 /// \brief Helper class to track the possible sources of a value defined by
335 /// a (chain of) copy related instructions.
336 /// Given a definition (instruction and definition index), this class
337 /// follows the use-def chain to find successive suitable sources.
338 /// The given source can be used to rewrite the definition into
341 /// For instance, let us consider the following snippet:
343 /// v2 = INSERT_SUBREG v1, v0, sub0
344 /// def = COPY v2.sub0
346 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
347 /// suitable sources:
349 /// Then, def can be rewritten into def = COPY v0.
352 /// The current point into the use-def chain.
353 const MachineInstr *Def;
354 /// The index of the definition in Def.
356 /// The sub register index of the definition.
358 /// The register where the value can be found.
360 /// Specifiy whether or not the value tracking looks through
361 /// complex instructions. When this is false, the value tracker
362 /// bails on everything that is not a copy or a bitcast.
364 /// Note: This could have been implemented as a specialized version of
365 /// the ValueTracker class but that would have complicated the code of
366 /// the users of this class.
367 bool UseAdvancedTracking;
368 /// MachineRegisterInfo used to perform tracking.
369 const MachineRegisterInfo &MRI;
370 /// Optional TargetInstrInfo used to perform some complex
372 const TargetInstrInfo *TII;
374 /// \brief Dispatcher to the right underlying implementation of
376 ValueTrackerResult getNextSourceImpl();
377 /// \brief Specialized version of getNextSource for Copy instructions.
378 ValueTrackerResult getNextSourceFromCopy();
379 /// \brief Specialized version of getNextSource for Bitcast instructions.
380 ValueTrackerResult getNextSourceFromBitcast();
381 /// \brief Specialized version of getNextSource for RegSequence
383 ValueTrackerResult getNextSourceFromRegSequence();
384 /// \brief Specialized version of getNextSource for InsertSubreg
386 ValueTrackerResult getNextSourceFromInsertSubreg();
387 /// \brief Specialized version of getNextSource for ExtractSubreg
389 ValueTrackerResult getNextSourceFromExtractSubreg();
390 /// \brief Specialized version of getNextSource for SubregToReg
392 ValueTrackerResult getNextSourceFromSubregToReg();
393 /// \brief Specialized version of getNextSource for PHI instructions.
394 ValueTrackerResult getNextSourceFromPHI();
397 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
398 /// \p DefSubReg represents the sub register index the value tracker will
399 /// track. It does not need to match the sub register index used in the
400 /// definition of \p Reg.
401 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
402 /// through complex instructions. By default (false), it handles only copy
403 /// and bitcast instructions.
404 /// If \p Reg is a physical register, a value tracker constructed with
405 /// this constructor will not find any alternative source.
406 /// Indeed, when \p Reg is a physical register that constructor does not
407 /// know which definition of \p Reg it should track.
408 /// Use the next constructor to track a physical register.
409 ValueTracker(unsigned Reg, unsigned DefSubReg,
410 const MachineRegisterInfo &MRI,
411 bool UseAdvancedTracking = false,
412 const TargetInstrInfo *TII = nullptr)
413 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
414 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
415 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
416 Def = MRI.getVRegDef(Reg);
417 DefIdx = MRI.def_begin(Reg).getOperandNo();
421 /// \brief Create a ValueTracker instance for the value defined by
422 /// the pair \p MI, \p DefIdx.
423 /// Unlike the other constructor, the value tracker produced by this one
424 /// may be able to find a new source when the definition is a physical
426 /// This could be useful to rewrite target specific instructions into
427 /// generic copy instructions.
428 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
429 const MachineRegisterInfo &MRI,
430 bool UseAdvancedTracking = false,
431 const TargetInstrInfo *TII = nullptr)
432 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
433 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
434 assert(DefIdx < Def->getDesc().getNumDefs() &&
435 Def->getOperand(DefIdx).isReg() && "Invalid definition");
436 Reg = Def->getOperand(DefIdx).getReg();
439 /// \brief Following the use-def chain, get the next available source
440 /// for the tracked value.
441 /// \return A ValueTrackerResult containing a set of registers
442 /// and sub registers with tracked values. A ValueTrackerResult with
443 /// an empty set of registers means no source was found.
444 ValueTrackerResult getNextSource();
446 /// \brief Get the last register where the initial value can be found.
447 /// Initially this is the register of the definition.
448 /// Then, after each successful call to getNextSource, this is the
449 /// register of the last source.
450 unsigned getReg() const { return Reg; }
453 } // end anonymous namespace
455 char PeepholeOptimizer::ID = 0;
456 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
458 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
459 "Peephole Optimizations", false, false)
460 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
461 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
462 INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
463 "Peephole Optimizations", false, false)
465 /// If instruction is a copy-like instruction, i.e. it reads a single register
466 /// and writes a single register and it does not modify the source, and if the
467 /// source value is preserved as a sub-register of the result, then replace all
468 /// reachable uses of the source with the subreg of the result.
470 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
471 /// the code. Since this code does not currently share EXTRACTs, just ignore all
473 bool PeepholeOptimizer::
474 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
475 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
476 unsigned SrcReg, DstReg, SubIdx;
477 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
480 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
481 TargetRegisterInfo::isPhysicalRegister(SrcReg))
484 if (MRI->hasOneNonDBGUse(SrcReg))
488 // Ensure DstReg can get a register class that actually supports
489 // sub-registers. Don't change the class until we commit.
490 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
491 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
495 // The ext instr may be operating on a sub-register of SrcReg as well.
496 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
498 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
499 // SrcReg:SubIdx should be replaced.
501 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
503 // The source has other uses. See if we can replace the other uses with use of
504 // the result of the extension.
505 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
506 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
507 ReachedBBs.insert(UI.getParent());
509 // Uses that are in the same BB of uses of the result of the instruction.
510 SmallVector<MachineOperand*, 8> Uses;
512 // Uses that the result of the instruction can reach.
513 SmallVector<MachineOperand*, 8> ExtendedUses;
515 bool ExtendLife = true;
516 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
517 MachineInstr *UseMI = UseMO.getParent();
521 if (UseMI->isPHI()) {
526 // Only accept uses of SrcReg:SubIdx.
527 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
530 // It's an error to translate this:
532 // %reg1025 = <sext> %reg1024
534 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
538 // %reg1025 = <sext> %reg1024
540 // %reg1027 = COPY %reg1025:4
541 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
543 // The problem here is that SUBREG_TO_REG is there to assert that an
544 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
545 // the COPY here, it will give us the value after the <sext>, not the
546 // original value of %reg1024 before <sext>.
547 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
550 MachineBasicBlock *UseMBB = UseMI->getParent();
552 // Local uses that come after the extension.
553 if (!LocalMIs.count(UseMI))
554 Uses.push_back(&UseMO);
555 } else if (ReachedBBs.count(UseMBB)) {
556 // Non-local uses where the result of the extension is used. Always
557 // replace these unless it's a PHI.
558 Uses.push_back(&UseMO);
559 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
560 // We may want to extend the live range of the extension result in order
561 // to replace these uses.
562 ExtendedUses.push_back(&UseMO);
564 // Both will be live out of the def MBB anyway. Don't extend live range of
565 // the extension result.
571 if (ExtendLife && !ExtendedUses.empty())
572 // Extend the liveness of the extension result.
573 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
575 // Now replace all uses.
576 bool Changed = false;
578 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
580 // Look for PHI uses of the extended result, we don't want to extend the
581 // liveness of a PHI input. It breaks all kinds of assumptions down
582 // stream. A PHI use is expected to be the kill of its source values.
583 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
585 PHIBBs.insert(UI.getParent());
587 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
588 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
589 MachineOperand *UseMO = Uses[i];
590 MachineInstr *UseMI = UseMO->getParent();
591 MachineBasicBlock *UseMBB = UseMI->getParent();
592 if (PHIBBs.count(UseMBB))
595 // About to add uses of DstReg, clear DstReg's kill flags.
597 MRI->clearKillFlags(DstReg);
598 MRI->constrainRegClass(DstReg, DstRC);
601 unsigned NewVR = MRI->createVirtualRegister(RC);
602 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
603 TII->get(TargetOpcode::COPY), NewVR)
604 .addReg(DstReg, 0, SubIdx);
605 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
607 Copy->getOperand(0).setSubReg(SubIdx);
608 Copy->getOperand(0).setIsUndef();
610 UseMO->setReg(NewVR);
619 /// If the instruction is a compare and the previous instruction it's comparing
620 /// against already sets (or could be modified to set) the same flag as the
621 /// compare, then we can remove the comparison and use the flag from the
622 /// previous instruction.
623 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
624 MachineBasicBlock *MBB) {
625 // If this instruction is a comparison against zero and isn't comparing a
626 // physical register, we can try to optimize it.
627 unsigned SrcReg, SrcReg2;
628 int CmpMask, CmpValue;
629 if (!TII->analyzeCompare(*MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
630 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
631 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
634 // Attempt to optimize the comparison instruction.
635 if (TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
643 /// Optimize a select instruction.
644 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
645 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
647 unsigned FalseOp = 0;
648 bool Optimizable = false;
649 SmallVector<MachineOperand, 4> Cond;
650 if (TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable))
654 if (!TII->optimizeSelect(*MI, LocalMIs))
656 MI->eraseFromParent();
661 /// \brief Check if a simpler conditional branch can be
663 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
664 return TII->optimizeCondBranch(*MI);
667 /// \brief Try to find the next source that share the same register file
668 /// for the value defined by \p Reg and \p SubReg.
669 /// When true is returned, the \p RewriteMap can be used by the client to
670 /// retrieve all Def -> Use along the way up to the next source. Any found
671 /// Use that is not itself a key for another entry, is the next source to
672 /// use. During the search for the next source, multiple sources can be found
673 /// given multiple incoming sources of a PHI instruction. In this case, we
674 /// look in each PHI source for the next source; all found next sources must
675 /// share the same register file as \p Reg and \p SubReg. The client should
676 /// then be capable to rewrite all intermediate PHIs to get the next source.
677 /// \return False if no alternative sources are available. True otherwise.
678 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
679 RewriteMapTy &RewriteMap) {
680 // Do not try to find a new source for a physical register.
681 // So far we do not have any motivating example for doing that.
682 // Thus, instead of maintaining untested code, we will revisit that if
683 // that changes at some point.
684 if (TargetRegisterInfo::isPhysicalRegister(Reg))
686 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
688 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
689 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
690 SrcToLook.push_back(CurSrcPair);
692 unsigned PHICount = 0;
693 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
694 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
695 // As explained above, do not handle physical registers
696 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
700 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
701 !DisableAdvCopyOpt, TII);
702 ValueTrackerResult Res;
703 bool ShouldRewrite = false;
706 // Follow the chain of copies until we reach the top of the use-def chain
707 // or find a more suitable source.
708 Res = ValTracker.getNextSource();
712 // Insert the Def -> Use entry for the recently found source.
713 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
714 if (CurSrcRes.isValid()) {
715 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
716 // An existent entry with multiple sources is a PHI cycle we must avoid.
717 // Otherwise it's an entry with a valid next source we already found.
718 if (CurSrcRes.getNumSources() > 1) {
719 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
724 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
726 // ValueTrackerResult usually have one source unless it's the result from
727 // a PHI instruction. Add the found PHI edges to be looked up further.
728 unsigned NumSrcs = Res.getNumSources();
731 for (unsigned i = 0; i < NumSrcs; ++i)
732 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
733 Res.getSrcReg(i), Res.getSrcSubReg(i)));
737 CurSrcPair.Reg = Res.getSrcReg(0);
738 CurSrcPair.SubReg = Res.getSrcSubReg(0);
739 // Do not extend the live-ranges of physical registers as they add
740 // constraints to the register allocator. Moreover, if we want to extend
741 // the live-range of a physical register, unlike SSA virtual register,
742 // we will have to check that they aren't redefine before the related use.
743 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
746 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
747 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
749 } while (!ShouldRewrite);
751 // Continue looking for new sources...
755 // Do not continue searching for a new source if the there's at least
756 // one use-def which cannot be rewritten.
761 if (PHICount >= RewritePHILimit) {
762 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
766 // If we did not find a more suitable source, there is nothing to optimize.
767 return CurSrcPair.Reg != Reg;
770 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
771 /// guaranteed to have the same register class. This is necessary whenever we
772 /// successfully traverse a PHI instruction and find suitable sources coming
773 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
774 /// suitable to be used in a new COPY instruction.
775 static MachineInstr *
776 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
777 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
778 MachineInstr *OrigPHI) {
779 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
781 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
782 unsigned NewVR = MRI->createVirtualRegister(NewRC);
783 MachineBasicBlock *MBB = OrigPHI->getParent();
784 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
785 TII->get(TargetOpcode::PHI), NewVR);
787 unsigned MBBOpIdx = 2;
788 for (auto RegPair : SrcRegs) {
789 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
790 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
791 // Since we're extended the lifetime of RegPair.Reg, clear the
792 // kill flags to account for that and make RegPair.Reg reaches
794 MRI->clearKillFlags(RegPair.Reg);
803 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
806 /// The copy-like instruction.
807 MachineInstr &CopyLike;
808 /// The index of the source being rewritten.
809 unsigned CurrentSrcIdx;
812 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
814 virtual ~CopyRewriter() {}
816 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
817 /// the related value that it affects (TrackReg, TrackSubReg).
818 /// A source is considered rewritable if its register class and the
819 /// register class of the related TrackReg may not be register
820 /// coalescer friendly. In other words, given a copy-like instruction
821 /// not all the arguments may be returned at rewritable source, since
822 /// some arguments are none to be register coalescer friendly.
824 /// Each call of this method moves the current source to the next
825 /// rewritable source.
826 /// For instance, let CopyLike be the instruction to rewrite.
827 /// CopyLike has one definition and one source:
828 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
830 /// The first call will give the first rewritable source, i.e.,
831 /// the only source this instruction has:
832 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
833 /// This source defines the whole definition, i.e.,
834 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
836 /// The second and subsequent calls will return false, as there is only one
837 /// rewritable source.
839 /// \return True if a rewritable source has been found, false otherwise.
840 /// The output arguments are valid if and only if true is returned.
841 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
843 unsigned &TrackSubReg) {
844 // If CurrentSrcIdx == 1, this means this function has already been called
845 // once. CopyLike has one definition and one argument, thus, there is
846 // nothing else to rewrite.
847 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
849 // This is the first call to getNextRewritableSource.
850 // Move the CurrentSrcIdx to remember that we made that call.
852 // The rewritable source is the argument.
853 const MachineOperand &MOSrc = CopyLike.getOperand(1);
854 SrcReg = MOSrc.getReg();
855 SrcSubReg = MOSrc.getSubReg();
856 // What we track are the alternative sources of the definition.
857 const MachineOperand &MODef = CopyLike.getOperand(0);
858 TrackReg = MODef.getReg();
859 TrackSubReg = MODef.getSubReg();
863 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
865 /// \return True if the rewriting was possible, false otherwise.
866 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
867 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
869 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
870 MOSrc.setReg(NewReg);
871 MOSrc.setSubReg(NewSubReg);
875 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
876 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
877 /// multiple sources for a given \p Def are found along the way, we found a
878 /// PHI instructions that needs to be rewritten.
879 /// TODO: HandleMultipleSources should be removed once we test PHI handling
880 /// with coalescable copies.
881 TargetInstrInfo::RegSubRegPair
882 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
883 TargetInstrInfo::RegSubRegPair Def,
884 PeepholeOptimizer::RewriteMapTy &RewriteMap,
885 bool HandleMultipleSources = true) {
886 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
888 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
889 // If there are no entries on the map, LookupSrc is the new source.
893 // There's only one source for this definition, keep searching...
894 unsigned NumSrcs = Res.getNumSources();
896 LookupSrc.Reg = Res.getSrcReg(0);
897 LookupSrc.SubReg = Res.getSrcSubReg(0);
901 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
902 if (!HandleMultipleSources)
905 // Multiple sources, recurse into each source to find a new source
906 // for it. Then, rewrite the PHI accordingly to its new edges.
907 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
908 for (unsigned i = 0; i < NumSrcs; ++i) {
909 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
910 Res.getSrcSubReg(i));
911 NewPHISrcs.push_back(
912 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
915 // Build the new PHI node and return its def register as the new source.
916 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
917 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
918 DEBUG(dbgs() << "-- getNewSource\n");
919 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
920 DEBUG(dbgs() << " With: " << *NewPHI);
921 const MachineOperand &MODef = NewPHI->getOperand(0);
922 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
926 return TargetInstrInfo::RegSubRegPair(0, 0);
929 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
930 /// and create a new COPY instruction. More info about RewriteMap in
931 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
932 /// Uncoalescable copies, since they are copy like instructions that aren't
933 /// recognized by the register allocator.
934 virtual MachineInstr *
935 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
936 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
941 /// \brief Helper class to rewrite uncoalescable copy like instructions
942 /// into new COPY (coalescable friendly) instructions.
943 class UncoalescableRewriter : public CopyRewriter {
945 const TargetInstrInfo &TII;
946 MachineRegisterInfo &MRI;
947 /// The number of defs in the bitcast
951 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
952 MachineRegisterInfo &MRI)
953 : CopyRewriter(MI), TII(TII), MRI(MRI) {
954 NumDefs = MI.getDesc().getNumDefs();
957 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
958 /// All such sources need to be considered rewritable in order to
959 /// rewrite a uncoalescable copy-like instruction. This method return
960 /// each definition that must be checked if rewritable.
962 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
964 unsigned &TrackSubReg) override {
965 // Find the next non-dead definition and continue from there.
966 if (CurrentSrcIdx == NumDefs)
969 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
971 if (CurrentSrcIdx == NumDefs)
975 // What we track are the alternative sources of the definition.
976 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
977 TrackReg = MODef.getReg();
978 TrackSubReg = MODef.getSubReg();
984 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
985 /// and create a new COPY instruction. More info about RewriteMap in
986 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
987 /// Uncoalescable copies, since they are copy like instructions that aren't
988 /// recognized by the register allocator.
990 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
991 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
992 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
993 "We do not rewrite physical registers");
995 // Find the new source to use in the COPY rewrite.
996 TargetInstrInfo::RegSubRegPair NewSrc =
997 getNewSource(&MRI, &TII, Def, RewriteMap);
1000 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
1001 unsigned NewVR = MRI.createVirtualRegister(DefRC);
1003 MachineInstr *NewCopy =
1004 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1005 TII.get(TargetOpcode::COPY), NewVR)
1006 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
1008 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1010 NewCopy->getOperand(0).setIsUndef();
1012 DEBUG(dbgs() << "-- RewriteSource\n");
1013 DEBUG(dbgs() << " Replacing: " << CopyLike);
1014 DEBUG(dbgs() << " With: " << *NewCopy);
1015 MRI.replaceRegWith(Def.Reg, NewVR);
1016 MRI.clearKillFlags(NewVR);
1018 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1019 // account for that.
1020 MRI.clearKillFlags(NewSrc.Reg);
1026 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
1027 class InsertSubregRewriter : public CopyRewriter {
1029 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1030 assert(MI.isInsertSubreg() && "Invalid instruction");
1033 /// \brief See CopyRewriter::getNextRewritableSource.
1034 /// Here CopyLike has the following form:
1035 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
1036 /// Src1 has the same register class has dst, hence, there is
1037 /// nothing to rewrite.
1038 /// Src2.src2SubIdx, may not be register coalescer friendly.
1039 /// Therefore, the first call to this method returns:
1040 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1041 /// (TrackReg, TrackSubReg) = (dst, subIdx).
1043 /// Subsequence calls will return false.
1044 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1046 unsigned &TrackSubReg) override {
1047 // If we already get the only source we can rewrite, return false.
1048 if (CurrentSrcIdx == 2)
1050 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
1052 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
1053 SrcReg = MOInsertedReg.getReg();
1054 SrcSubReg = MOInsertedReg.getSubReg();
1055 const MachineOperand &MODef = CopyLike.getOperand(0);
1057 // We want to track something that is compatible with the
1058 // partial definition.
1059 TrackReg = MODef.getReg();
1060 if (MODef.getSubReg())
1061 // Bail if we have to compose sub-register indices.
1063 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1067 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1068 if (CurrentSrcIdx != 2)
1070 // We are rewriting the inserted reg.
1071 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1073 MO.setSubReg(NewSubReg);
1078 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1079 class ExtractSubregRewriter : public CopyRewriter {
1080 const TargetInstrInfo &TII;
1083 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1084 : CopyRewriter(MI), TII(TII) {
1085 assert(MI.isExtractSubreg() && "Invalid instruction");
1088 /// \brief See CopyRewriter::getNextRewritableSource.
1089 /// Here CopyLike has the following form:
1090 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1091 /// There is only one rewritable source: Src.subIdx,
1092 /// which defines dst.dstSubIdx.
1093 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1095 unsigned &TrackSubReg) override {
1096 // If we already get the only source we can rewrite, return false.
1097 if (CurrentSrcIdx == 1)
1099 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1101 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1102 SrcReg = MOExtractedReg.getReg();
1103 // If we have to compose sub-register indices, bail out.
1104 if (MOExtractedReg.getSubReg())
1107 SrcSubReg = CopyLike.getOperand(2).getImm();
1109 // We want to track something that is compatible with the definition.
1110 const MachineOperand &MODef = CopyLike.getOperand(0);
1111 TrackReg = MODef.getReg();
1112 TrackSubReg = MODef.getSubReg();
1116 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1117 // The only source we can rewrite is the input register.
1118 if (CurrentSrcIdx != 1)
1121 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1123 // If we find a source that does not require to extract something,
1124 // rewrite the operation with a copy.
1126 // Move the current index to an invalid position.
1127 // We do not want another call to this method to be able
1128 // to do any change.
1130 // Rewrite the operation as a COPY.
1131 // Get rid of the sub-register index.
1132 CopyLike.RemoveOperand(2);
1133 // Morph the operation into a COPY.
1134 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1137 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1142 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1143 class RegSequenceRewriter : public CopyRewriter {
1145 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1146 assert(MI.isRegSequence() && "Invalid instruction");
1149 /// \brief See CopyRewriter::getNextRewritableSource.
1150 /// Here CopyLike has the following form:
1151 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1152 /// Each call will return a different source, walking all the available
1155 /// The first call returns:
1156 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1157 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1159 /// The second call returns:
1160 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1161 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1163 /// And so on, until all the sources have been traversed, then
1164 /// it returns false.
1165 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1167 unsigned &TrackSubReg) override {
1168 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1170 // If this is the first call, move to the first argument.
1171 if (CurrentSrcIdx == 0) {
1174 // Otherwise, move to the next argument and check that it is valid.
1176 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1179 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1180 SrcReg = MOInsertedReg.getReg();
1181 // If we have to compose sub-register indices, bail out.
1182 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1185 // We want to track something that is compatible with the related
1186 // partial definition.
1187 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1189 const MachineOperand &MODef = CopyLike.getOperand(0);
1190 TrackReg = MODef.getReg();
1191 // If we have to compose sub-registers, bail.
1192 return MODef.getSubReg() == 0;
1195 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1196 // We cannot rewrite out of bound operands.
1197 // Moreover, rewritable sources are at odd positions.
1198 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1201 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1203 MO.setSubReg(NewSubReg);
1208 } // end anonymous namespace
1210 /// \brief Get the appropriated CopyRewriter for \p MI.
1211 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1212 /// if no rewriter works for \p MI.
1213 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1214 const TargetInstrInfo &TII,
1215 MachineRegisterInfo &MRI) {
1216 // Handle uncoalescable copy-like instructions.
1217 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1218 MI.isExtractSubregLike()))
1219 return new UncoalescableRewriter(MI, TII, MRI);
1221 switch (MI.getOpcode()) {
1224 case TargetOpcode::COPY:
1225 return new CopyRewriter(MI);
1226 case TargetOpcode::INSERT_SUBREG:
1227 return new InsertSubregRewriter(MI);
1228 case TargetOpcode::EXTRACT_SUBREG:
1229 return new ExtractSubregRewriter(MI, TII);
1230 case TargetOpcode::REG_SEQUENCE:
1231 return new RegSequenceRewriter(MI);
1233 llvm_unreachable(nullptr);
1236 /// \brief Optimize generic copy instructions to avoid cross
1237 /// register bank copy. The optimization looks through a chain of
1238 /// copies and tries to find a source that has a compatible register
1240 /// Two register classes are considered to be compatible if they share
1241 /// the same register bank.
1242 /// New copies issued by this optimization are register allocator
1243 /// friendly. This optimization does not remove any copy as it may
1244 /// overconstrain the register allocator, but replaces some operands
1246 /// \pre isCoalescableCopy(*MI) is true.
1247 /// \return True, when \p MI has been rewritten. False otherwise.
1248 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1249 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1250 assert(MI->getDesc().getNumDefs() == 1 &&
1251 "Coalescer can understand multiple defs?!");
1252 const MachineOperand &MODef = MI->getOperand(0);
1253 // Do not rewrite physical definitions.
1254 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1257 bool Changed = false;
1258 // Get the right rewriter for the current copy.
1259 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1260 // If none exists, bail out.
1263 // Rewrite each rewritable source.
1264 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1265 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1267 // Keep track of PHI nodes and its incoming edges when looking for sources.
1268 RewriteMapTy RewriteMap;
1269 // Try to find a more suitable source. If we failed to do so, or get the
1270 // actual source, move to the next source.
1271 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1274 // Get the new source to rewrite. TODO: Only enable handling of multiple
1275 // sources (PHIs) once we have a motivating example and testcases for it.
1276 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1277 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1278 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1279 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1283 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1284 // We may have extended the live-range of NewSrc, account for that.
1285 MRI->clearKillFlags(NewSrc.Reg);
1289 // TODO: We could have a clean-up method to tidy the instruction.
1290 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1292 // Currently we haven't seen motivating example for that and we
1293 // want to avoid untested code.
1294 NumRewrittenCopies += Changed;
1298 /// \brief Optimize copy-like instructions to create
1299 /// register coalescer friendly instruction.
1300 /// The optimization tries to kill-off the \p MI by looking
1301 /// through a chain of copies to find a source that has a compatible
1303 /// If such a source is found, it replace \p MI by a generic COPY
1305 /// \pre isUncoalescableCopy(*MI) is true.
1306 /// \return True, when \p MI has been optimized. In that case, \p MI has
1307 /// been removed from its parent.
1308 /// All COPY instructions created, are inserted in \p LocalMIs.
1309 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1310 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1311 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1313 // Check if we can rewrite all the values defined by this instruction.
1314 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1315 // Get the right rewriter for the current copy.
1316 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1317 // If none exists, bail out.
1321 // Rewrite each rewritable source by generating new COPYs. This works
1322 // differently from optimizeCoalescableCopy since it first makes sure that all
1323 // definitions can be rewritten.
1324 RewriteMapTy RewriteMap;
1325 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1326 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1328 // If a physical register is here, this is probably for a good reason.
1329 // Do not rewrite that.
1330 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1333 // If we do not know how to rewrite this definition, there is no point
1334 // in trying to kill this instruction.
1335 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1336 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1339 RewritePairs.push_back(Def);
1342 // The change is possible for all defs, do it.
1343 for (const auto &Def : RewritePairs) {
1344 // Rewrite the "copy" in a way the register coalescer understands.
1345 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1346 assert(NewCopy && "Should be able to always generate a new copy");
1347 LocalMIs.insert(NewCopy);
1351 MI->eraseFromParent();
1352 ++NumUncoalescableCopies;
1356 /// Check whether MI is a candidate for folding into a later instruction.
1357 /// We only fold loads to virtual registers and the virtual register defined
1358 /// has a single use.
1359 bool PeepholeOptimizer::isLoadFoldable(
1360 MachineInstr *MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1361 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1363 const MCInstrDesc &MCID = MI->getDesc();
1364 if (MCID.getNumDefs() != 1)
1367 unsigned Reg = MI->getOperand(0).getReg();
1368 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1369 // loads. It should be checked when processing uses of the load, since
1370 // uses can be removed during peephole.
1371 if (!MI->getOperand(0).getSubReg() &&
1372 TargetRegisterInfo::isVirtualRegister(Reg) &&
1373 MRI->hasOneNonDBGUse(Reg)) {
1374 FoldAsLoadDefCandidates.insert(Reg);
1380 bool PeepholeOptimizer::isMoveImmediate(
1381 MachineInstr *MI, SmallSet<unsigned, 4> &ImmDefRegs,
1382 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1383 const MCInstrDesc &MCID = MI->getDesc();
1384 if (!MI->isMoveImmediate())
1386 if (MCID.getNumDefs() != 1)
1388 unsigned Reg = MI->getOperand(0).getReg();
1389 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1390 ImmDefMIs.insert(std::make_pair(Reg, MI));
1391 ImmDefRegs.insert(Reg);
1398 /// Try folding register operands that are defined by move immediate
1399 /// instructions, i.e. a trivial constant folding optimization, if
1400 /// and only if the def and use are in the same BB.
1401 bool PeepholeOptimizer::foldImmediate(
1402 MachineInstr *MI, MachineBasicBlock *MBB, SmallSet<unsigned, 4> &ImmDefRegs,
1403 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1404 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1405 MachineOperand &MO = MI->getOperand(i);
1406 if (!MO.isReg() || MO.isDef())
1408 // Ignore dead implicit defs.
1409 if (MO.isImplicit() && MO.isDead())
1411 unsigned Reg = MO.getReg();
1412 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1414 if (ImmDefRegs.count(Reg) == 0)
1416 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1417 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1418 if (TII->FoldImmediate(*MI, *II->second, Reg, MRI)) {
1426 // FIXME: This is very simple and misses some cases which should be handled when
1427 // motivating examples are found.
1429 // The copy rewriting logic should look at uses as well as defs and be able to
1430 // eliminate copies across blocks.
1432 // Later copies that are subregister extracts will also not be eliminated since
1433 // only the first copy is considered.
1436 // %vreg1 = COPY %vreg0
1437 // %vreg2 = COPY %vreg0:sub1
1439 // Should replace %vreg2 uses with %vreg1:sub1
1440 bool PeepholeOptimizer::foldRedundantCopy(
1441 MachineInstr *MI, SmallSet<unsigned, 4> &CopySrcRegs,
1442 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1443 assert(MI->isCopy() && "expected a COPY machine instruction");
1445 unsigned SrcReg = MI->getOperand(1).getReg();
1446 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1449 unsigned DstReg = MI->getOperand(0).getReg();
1450 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1453 if (CopySrcRegs.insert(SrcReg).second) {
1454 // First copy of this reg seen.
1455 CopyMIs.insert(std::make_pair(SrcReg, MI));
1459 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1461 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1462 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1464 // Can't replace different subregister extracts.
1465 if (SrcSubReg != PrevSrcSubReg)
1468 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1470 // Only replace if the copy register class is the same.
1472 // TODO: If we have multiple copies to different register classes, we may want
1473 // to track multiple copies of the same source register.
1474 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1477 MRI->replaceRegWith(DstReg, PrevDstReg);
1479 // Lifetime of the previous copy has been extended.
1480 MRI->clearKillFlags(PrevDstReg);
1484 bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1485 return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1486 !MRI->isAllocatable(Reg);
1489 bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1490 MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1491 assert(MI->isCopy() && "expected a COPY machine instruction");
1493 if (DisableNAPhysCopyOpt)
1496 unsigned DstReg = MI->getOperand(0).getReg();
1497 unsigned SrcReg = MI->getOperand(1).getReg();
1498 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1499 // %vreg = COPY %PHYSREG
1500 // Avoid using a datastructure which can track multiple live non-allocatable
1501 // phys->virt copies since LLVM doesn't seem to do this.
1502 NAPhysToVirtMIs.insert({SrcReg, MI});
1506 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1509 // %PHYSREG = COPY %vreg
1510 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1511 if (PrevCopy == NAPhysToVirtMIs.end()) {
1512 // We can't remove the copy: there was an intervening clobber of the
1513 // non-allocatable physical register after the copy to virtual.
1514 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI
1519 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1520 if (PrevDstReg == SrcReg) {
1521 // Remove the virt->phys copy: we saw the virtual register definition, and
1522 // the non-allocatable physical register's state hasn't changed since then.
1523 DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n');
1528 // Potential missed optimization opportunity: we saw a different virtual
1529 // register get a copy of the non-allocatable physical register, and we only
1530 // track one such copy. Avoid getting confused by this new non-allocatable
1531 // physical register definition, and remove it from the tracked copies.
1532 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n');
1533 NAPhysToVirtMIs.erase(PrevCopy);
1537 /// \bried Returns true if \p MO is a virtual register operand.
1538 static bool isVirtualRegisterOperand(MachineOperand &MO) {
1541 return TargetRegisterInfo::isVirtualRegister(MO.getReg());
1544 bool PeepholeOptimizer::findTargetRecurrence(
1545 unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1546 RecurrenceCycle &RC) {
1547 // Recurrence found if Reg is in TargetRegs.
1548 if (TargetRegs.count(Reg))
1551 // TODO: Curerntly, we only allow the last instruction of the recurrence
1552 // cycle (the instruction that feeds the PHI instruction) to have more than
1553 // one uses to guarantee that commuting operands does not tie registers
1554 // with overlapping live range. Once we have actual live range info of
1555 // each register, this constraint can be relaxed.
1556 if (!MRI->hasOneNonDBGUse(Reg))
1559 // Give up if the reccurrence chain length is longer than the limit.
1560 if (RC.size() >= MaxRecurrenceChain)
1563 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1564 unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1566 // Only interested in recurrences whose instructions have only one def, which
1567 // is a virtual register.
1568 if (MI.getDesc().getNumDefs() != 1)
1571 MachineOperand &DefOp = MI.getOperand(0);
1572 if (!isVirtualRegisterOperand(DefOp))
1575 // Check if def operand of MI is tied to any use operand. We are only
1576 // interested in the case that all the instructions in the recurrence chain
1577 // have there def operand tied with one of the use operand.
1578 unsigned TiedUseIdx;
1579 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1582 if (Idx == TiedUseIdx) {
1583 RC.push_back(RecurrenceInstr(&MI));
1584 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1586 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1587 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1588 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1589 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1590 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1597 /// \brief Phi instructions will eventually be lowered to copy instructions. If
1598 /// phi is in a loop header, a recurrence may formulated around the source and
1599 /// destination of the phi. For such case commuting operands of the instructions
1600 /// in the recurrence may enable coalescing of the copy instruction generated
1601 /// from the phi. For example, if there is a recurrence of
1604 /// %vreg1 = phi(%vreg0, %vreg100)
1606 /// %vreg0<def, tied1> = ADD %vreg2<def, tied0>, %vreg1
1608 /// , the fact that vreg0 and vreg2 are in the same tied operands set makes
1609 /// the coalescing of copy instruction generated from the phi in
1610 /// LoopHeader(i.e. %vreg1 = COPY %vreg0) impossible, because %vreg1 and
1611 /// %vreg2 have overlapping live range. This introduces additional move
1612 /// instruction to the final assembly. However, if we commute %vreg2 and
1613 /// %vreg1 of ADD instruction, the redundant move instruction can be
1615 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1616 SmallSet<unsigned, 2> TargetRegs;
1617 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1618 MachineOperand &MO = PHI.getOperand(Idx);
1619 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1620 TargetRegs.insert(MO.getReg());
1623 bool Changed = false;
1625 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1626 // Commutes operands of instructions in RC if necessary so that the copy to
1627 // be generated from PHI can be coalesced.
1628 DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1629 for (auto &RI : RC) {
1630 DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1631 auto CP = RI.getCommutePair();
1634 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1636 DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1644 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1645 if (skipFunction(*MF.getFunction()))
1648 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1649 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1651 if (DisablePeephole)
1654 TII = MF.getSubtarget().getInstrInfo();
1655 TRI = MF.getSubtarget().getRegisterInfo();
1656 MRI = &MF.getRegInfo();
1657 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1658 MLI = &getAnalysis<MachineLoopInfo>();
1660 bool Changed = false;
1662 for (MachineBasicBlock &MBB : MF) {
1663 bool SeenMoveImm = false;
1665 // During this forward scan, at some point it needs to answer the question
1666 // "given a pointer to an MI in the current BB, is it located before or
1667 // after the current instruction".
1668 // To perform this, the following set keeps track of the MIs already seen
1669 // during the scan, if a MI is not in the set, it is assumed to be located
1670 // after. Newly created MIs have to be inserted in the set as well.
1671 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1672 SmallSet<unsigned, 4> ImmDefRegs;
1673 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1674 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1676 // Track when a non-allocatable physical register is copied to a virtual
1677 // register so that useless moves can be removed.
1679 // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG`
1680 // without any intervening re-definition of %PHYSREG.
1681 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1683 // Set of virtual registers that are copied from.
1684 SmallSet<unsigned, 4> CopySrcRegs;
1685 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1687 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1689 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1691 MachineInstr *MI = &*MII;
1692 // We may be erasing MI below, increment MII now.
1694 LocalMIs.insert(MI);
1696 // Skip debug values. They should not affect this peephole optimization.
1697 if (MI->isDebugValue())
1700 if (MI->isPosition())
1703 if (IsLoopHeader && MI->isPHI()) {
1704 if (optimizeRecurrence(*MI)) {
1710 if (!MI->isCopy()) {
1711 for (const auto &Op : MI->operands()) {
1712 // Visit all operands: definitions can be implicit or explicit.
1714 unsigned Reg = Op.getReg();
1715 if (Op.isDef() && isNAPhysCopy(Reg)) {
1716 const auto &Def = NAPhysToVirtMIs.find(Reg);
1717 if (Def != NAPhysToVirtMIs.end()) {
1718 // A new definition of the non-allocatable physical register
1719 // invalidates previous copies.
1720 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1722 NAPhysToVirtMIs.erase(Def);
1725 } else if (Op.isRegMask()) {
1726 const uint32_t *RegMask = Op.getRegMask();
1727 for (auto &RegMI : NAPhysToVirtMIs) {
1728 unsigned Def = RegMI.first;
1729 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1730 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1732 NAPhysToVirtMIs.erase(Def);
1739 if (MI->isImplicitDef() || MI->isKill())
1742 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1743 // Blow away all non-allocatable physical registers knowledge since we
1744 // don't know what's correct anymore.
1746 // FIXME: handle explicit asm clobbers.
1747 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI
1749 NAPhysToVirtMIs.clear();
1752 if ((isUncoalescableCopy(*MI) &&
1753 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1754 (MI->isCompare() && optimizeCmpInstr(MI, &MBB)) ||
1755 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1762 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1767 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1768 // MI is just rewritten.
1774 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1775 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
1777 MI->eraseFromParent();
1782 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1785 Changed |= optimizeExtInstr(MI, &MBB, LocalMIs);
1786 // optimizeExtInstr might have created new instructions after MI
1787 // and before the already incremented MII. Adjust MII so that the
1788 // next iteration sees the new instructions.
1792 Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs);
1795 // Check whether MI is a load candidate for folding into a later
1796 // instruction. If MI is not a candidate, check whether we can fold an
1797 // earlier load into MI.
1798 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1799 !FoldAsLoadDefCandidates.empty()) {
1801 // We visit each operand even after successfully folding a previous
1802 // one. This allows us to fold multiple loads into a single
1803 // instruction. We do assume that optimizeLoadInstr doesn't insert
1804 // foldable uses earlier in the argument list. Since we don't restart
1805 // iteration, we'd miss such cases.
1806 const MCInstrDesc &MIDesc = MI->getDesc();
1807 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
1809 const MachineOperand &MOp = MI->getOperand(i);
1812 unsigned FoldAsLoadDefReg = MOp.getReg();
1813 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1814 // We need to fold load after optimizeCmpInstr, since
1815 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1816 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1817 // we need it for markUsesInDebugValueAsUndef().
1818 unsigned FoldedReg = FoldAsLoadDefReg;
1819 MachineInstr *DefMI = nullptr;
1820 if (MachineInstr *FoldMI =
1821 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
1822 // Update LocalMIs since we replaced MI with FoldMI and deleted
1824 DEBUG(dbgs() << "Replacing: " << *MI);
1825 DEBUG(dbgs() << " With: " << *FoldMI);
1827 LocalMIs.erase(DefMI);
1828 LocalMIs.insert(FoldMI);
1829 MI->eraseFromParent();
1830 DefMI->eraseFromParent();
1831 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1832 FoldAsLoadDefCandidates.erase(FoldedReg);
1835 // MI is replaced with FoldMI so we can continue trying to fold
1843 // If we run into an instruction we can't fold across, discard
1844 // the load candidates. Note: We might be able to fold *into* this
1845 // instruction, so this needs to be after the folding logic.
1846 if (MI->isLoadFoldBarrier()) {
1847 DEBUG(dbgs() << "Encountered load fold barrier on " << *MI << "\n");
1848 FoldAsLoadDefCandidates.clear();
1857 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1858 assert(Def->isCopy() && "Invalid definition");
1859 // Copy instruction are supposed to be: Def = Src.
1860 // If someone breaks this assumption, bad things will happen everywhere.
1861 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1863 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1864 // If we look for a different subreg, it means we want a subreg of src.
1865 // Bails as we do not support composing subregs yet.
1866 return ValueTrackerResult();
1867 // Otherwise, we want the whole source.
1868 const MachineOperand &Src = Def->getOperand(1);
1869 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1872 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1873 assert(Def->isBitcast() && "Invalid definition");
1875 // Bail if there are effects that a plain copy will not expose.
1876 if (Def->hasUnmodeledSideEffects())
1877 return ValueTrackerResult();
1879 // Bitcasts with more than one def are not supported.
1880 if (Def->getDesc().getNumDefs() != 1)
1881 return ValueTrackerResult();
1882 const MachineOperand DefOp = Def->getOperand(DefIdx);
1883 if (DefOp.getSubReg() != DefSubReg)
1884 // If we look for a different subreg, it means we want a subreg of the src.
1885 // Bails as we do not support composing subregs yet.
1886 return ValueTrackerResult();
1888 unsigned SrcIdx = Def->getNumOperands();
1889 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1891 const MachineOperand &MO = Def->getOperand(OpIdx);
1892 if (!MO.isReg() || !MO.getReg())
1894 // Ignore dead implicit defs.
1895 if (MO.isImplicit() && MO.isDead())
1897 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1898 if (SrcIdx != EndOpIdx)
1899 // Multiple sources?
1900 return ValueTrackerResult();
1904 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1905 // will break the assumed guarantees for the upper bits.
1906 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1907 if (UseMI.isSubregToReg())
1908 return ValueTrackerResult();
1911 const MachineOperand &Src = Def->getOperand(SrcIdx);
1912 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1915 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1916 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1917 "Invalid definition");
1919 if (Def->getOperand(DefIdx).getSubReg())
1920 // If we are composing subregs, bail out.
1921 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1922 // This should almost never happen as the SSA property is tracked at
1923 // the register level (as opposed to the subreg level).
1927 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1928 // Def. Thus, it must not be generated.
1929 // However, some code could theoretically generates a single
1930 // Def.sub0 (i.e, not defining the other subregs) and we would
1932 // If we can ascertain (or force) that this never happens, we could
1933 // turn that into an assertion.
1934 return ValueTrackerResult();
1937 // We could handle the REG_SEQUENCE here, but we do not want to
1938 // duplicate the code from the generic TII.
1939 return ValueTrackerResult();
1941 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1942 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1943 return ValueTrackerResult();
1945 // We are looking at:
1946 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1947 // Check if one of the operand defines the subreg we are interested in.
1948 for (auto &RegSeqInput : RegSeqInputRegs) {
1949 if (RegSeqInput.SubIdx == DefSubReg) {
1950 if (RegSeqInput.SubReg)
1951 // Bail if we have to compose sub registers.
1952 return ValueTrackerResult();
1954 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1958 // If the subreg we are tracking is super-defined by another subreg,
1959 // we could follow this value. However, this would require to compose
1960 // the subreg and we do not do that for now.
1961 return ValueTrackerResult();
1964 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1965 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1966 "Invalid definition");
1968 if (Def->getOperand(DefIdx).getSubReg())
1969 // If we are composing subreg, bail out.
1970 // Same remark as getNextSourceFromRegSequence.
1971 // I.e., this may be turned into an assert.
1972 return ValueTrackerResult();
1975 // We could handle the REG_SEQUENCE here, but we do not want to
1976 // duplicate the code from the generic TII.
1977 return ValueTrackerResult();
1979 TargetInstrInfo::RegSubRegPair BaseReg;
1980 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1981 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1982 return ValueTrackerResult();
1984 // We are looking at:
1985 // Def = INSERT_SUBREG v0, v1, sub1
1986 // There are two cases:
1987 // 1. DefSubReg == sub1, get v1.
1988 // 2. DefSubReg != sub1, the value may be available through v0.
1990 // #1 Check if the inserted register matches the required sub index.
1991 if (InsertedReg.SubIdx == DefSubReg) {
1992 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1994 // #2 Otherwise, if the sub register we are looking for is not partial
1995 // defined by the inserted element, we can look through the main
1997 const MachineOperand &MODef = Def->getOperand(DefIdx);
1998 // If the result register (Def) and the base register (v0) do not
1999 // have the same register class or if we have to compose
2000 // subregisters, bail out.
2001 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
2003 return ValueTrackerResult();
2005 // Get the TRI and check if the inserted sub-register overlaps with the
2006 // sub-register we are tracking.
2007 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2009 !(TRI->getSubRegIndexLaneMask(DefSubReg) &
2010 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
2011 return ValueTrackerResult();
2012 // At this point, the value is available in v0 via the same subreg
2014 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
2017 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
2018 assert((Def->isExtractSubreg() ||
2019 Def->isExtractSubregLike()) && "Invalid definition");
2020 // We are looking at:
2021 // Def = EXTRACT_SUBREG v0, sub0
2023 // Bail if we have to compose sub registers.
2024 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2026 return ValueTrackerResult();
2029 // We could handle the EXTRACT_SUBREG here, but we do not want to
2030 // duplicate the code from the generic TII.
2031 return ValueTrackerResult();
2033 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
2034 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
2035 return ValueTrackerResult();
2037 // Bail if we have to compose sub registers.
2038 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2039 if (ExtractSubregInputReg.SubReg)
2040 return ValueTrackerResult();
2041 // Otherwise, the value is available in the v0.sub0.
2042 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2043 ExtractSubregInputReg.SubIdx);
2046 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2047 assert(Def->isSubregToReg() && "Invalid definition");
2048 // We are looking at:
2049 // Def = SUBREG_TO_REG Imm, v0, sub0
2051 // Bail if we have to compose sub registers.
2052 // If DefSubReg != sub0, we would have to check that all the bits
2053 // we track are included in sub0 and if yes, we would have to
2054 // determine the right subreg in v0.
2055 if (DefSubReg != Def->getOperand(3).getImm())
2056 return ValueTrackerResult();
2057 // Bail if we have to compose sub registers.
2058 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2059 if (Def->getOperand(2).getSubReg())
2060 return ValueTrackerResult();
2062 return ValueTrackerResult(Def->getOperand(2).getReg(),
2063 Def->getOperand(3).getImm());
2066 /// \brief Explore each PHI incoming operand and return its sources
2067 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2068 assert(Def->isPHI() && "Invalid definition");
2069 ValueTrackerResult Res;
2071 // If we look for a different subreg, bail as we do not support composing
2073 if (Def->getOperand(0).getSubReg() != DefSubReg)
2074 return ValueTrackerResult();
2076 // Return all register sources for PHI instructions.
2077 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2078 auto &MO = Def->getOperand(i);
2079 assert(MO.isReg() && "Invalid PHI instruction");
2080 Res.addSource(MO.getReg(), MO.getSubReg());
2086 ValueTrackerResult ValueTracker::getNextSourceImpl() {
2087 assert(Def && "This method needs a valid definition");
2089 assert(((Def->getOperand(DefIdx).isDef() &&
2090 (DefIdx < Def->getDesc().getNumDefs() ||
2091 Def->getDesc().isVariadic())) ||
2092 Def->getOperand(DefIdx).isImplicit()) &&
2095 return getNextSourceFromCopy();
2096 if (Def->isBitcast())
2097 return getNextSourceFromBitcast();
2098 // All the remaining cases involve "complex" instructions.
2099 // Bail if we did not ask for the advanced tracking.
2100 if (!UseAdvancedTracking)
2101 return ValueTrackerResult();
2102 if (Def->isRegSequence() || Def->isRegSequenceLike())
2103 return getNextSourceFromRegSequence();
2104 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2105 return getNextSourceFromInsertSubreg();
2106 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2107 return getNextSourceFromExtractSubreg();
2108 if (Def->isSubregToReg())
2109 return getNextSourceFromSubregToReg();
2111 return getNextSourceFromPHI();
2112 return ValueTrackerResult();
2115 ValueTrackerResult ValueTracker::getNextSource() {
2116 // If we reach a point where we cannot move up in the use-def chain,
2117 // there is nothing we can get.
2119 return ValueTrackerResult();
2121 ValueTrackerResult Res = getNextSourceImpl();
2122 if (Res.isValid()) {
2123 // Update definition, definition index, and subregister for the
2124 // next call of getNextSource.
2125 // Update the current register.
2126 bool OneRegSrc = Res.getNumSources() == 1;
2128 Reg = Res.getSrcReg(0);
2129 // Update the result before moving up in the use-def chain
2130 // with the instruction containing the last found sources.
2133 // If we can still move up in the use-def chain, move to the next
2135 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
2136 Def = MRI.getVRegDef(Reg);
2137 DefIdx = MRI.def_begin(Reg).getOperandNo();
2138 DefSubReg = Res.getSrcSubReg(0);
2142 // If we end up here, this means we will not be able to find another source
2143 // for the next iteration. Make sure any new call to getNextSource bails out
2144 // early by cutting the use-def chain.