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/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"
85 #define DEBUG_TYPE "peephole-opt"
87 // Optimize Extensions
89 Aggressive("aggressive-ext-opt", cl::Hidden,
90 cl::desc("Aggressive extension optimization"));
93 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
94 cl::desc("Disable the peephole optimizer"));
97 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(true),
98 cl::desc("Disable advanced copy optimization"));
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");
109 class PeepholeOptimizer : public MachineFunctionPass {
110 const TargetMachine *TM;
111 const TargetInstrInfo *TII;
112 MachineRegisterInfo *MRI;
113 MachineDominatorTree *DT; // Machine dominator tree
116 static char ID; // Pass identification
117 PeepholeOptimizer() : MachineFunctionPass(ID) {
118 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
121 bool runOnMachineFunction(MachineFunction &MF) override;
123 void getAnalysisUsage(AnalysisUsage &AU) const override {
124 AU.setPreservesCFG();
125 MachineFunctionPass::getAnalysisUsage(AU);
127 AU.addRequired<MachineDominatorTree>();
128 AU.addPreserved<MachineDominatorTree>();
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);
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()));
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() ||
165 (!DisableAdvCopyOpt &&
166 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
167 MI.isExtractSubregLike()));
171 /// \brief Helper class to track the possible sources of a value defined by
172 /// a (chain of) copy related instructions.
173 /// Given a definition (instruction and definition index), this class
174 /// follows the use-def chain to find successive suitable sources.
175 /// The given source can be used to rewrite the definition into
178 /// For instance, let us consider the following snippet:
180 /// v2 = INSERT_SUBREG v1, v0, sub0
181 /// def = COPY v2.sub0
183 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
184 /// suitable sources:
186 /// Then, def can be rewritten into def = COPY v0.
189 /// The current point into the use-def chain.
190 const MachineInstr *Def;
191 /// The index of the definition in Def.
193 /// The sub register index of the definition.
195 /// The register where the value can be found.
197 /// Specifiy whether or not the value tracking looks through
198 /// complex instructions. When this is false, the value tracker
199 /// bails on everything that is not a copy or a bitcast.
201 /// Note: This could have been implemented as a specialized version of
202 /// the ValueTracker class but that would have complicated the code of
203 /// the users of this class.
204 bool UseAdvancedTracking;
205 /// MachineRegisterInfo used to perform tracking.
206 const MachineRegisterInfo &MRI;
207 /// Optional TargetInstrInfo used to perform some complex
209 const TargetInstrInfo *TII;
211 /// \brief Dispatcher to the right underlying implementation of
213 bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
214 /// \brief Specialized version of getNextSource for Copy instructions.
215 bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
216 /// \brief Specialized version of getNextSource for Bitcast instructions.
217 bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
218 /// \brief Specialized version of getNextSource for RegSequence
220 bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
221 /// \brief Specialized version of getNextSource for InsertSubreg
223 bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
224 /// \brief Specialized version of getNextSource for ExtractSubreg
226 bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
227 /// \brief Specialized version of getNextSource for SubregToReg
229 bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
232 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
233 /// \p DefSubReg represents the sub register index the value tracker will
234 /// track. It does not need to match the sub register index used in the
235 /// definition of \p Reg.
236 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
237 /// through complex instructions. By default (false), it handles only copy
238 /// and bitcast instructions.
239 /// If \p Reg is a physical register, a value tracker constructed with
240 /// this constructor will not find any alternative source.
241 /// Indeed, when \p Reg is a physical register that constructor does not
242 /// know which definition of \p Reg it should track.
243 /// Use the next constructor to track a physical register.
244 ValueTracker(unsigned Reg, unsigned DefSubReg,
245 const MachineRegisterInfo &MRI,
246 bool UseAdvancedTracking = false,
247 const TargetInstrInfo *TII = nullptr)
248 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
249 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
250 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
251 Def = MRI.getVRegDef(Reg);
252 DefIdx = MRI.def_begin(Reg).getOperandNo();
256 /// \brief Create a ValueTracker instance for the value defined by
257 /// the pair \p MI, \p DefIdx.
258 /// Unlike the other constructor, the value tracker produced by this one
259 /// may be able to find a new source when the definition is a physical
261 /// This could be useful to rewrite target specific instructions into
262 /// generic copy instructions.
263 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
264 const MachineRegisterInfo &MRI,
265 bool UseAdvancedTracking = false,
266 const TargetInstrInfo *TII = nullptr)
267 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
268 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
269 assert(DefIdx < Def->getDesc().getNumDefs() &&
270 Def->getOperand(DefIdx).isReg() && "Invalid definition");
271 Reg = Def->getOperand(DefIdx).getReg();
274 /// \brief Following the use-def chain, get the next available source
275 /// for the tracked value.
276 /// When the returned value is not nullptr, \p SrcReg gives the register
277 /// that contain the tracked value.
278 /// \note The sub register index returned in \p SrcSubReg must be used
279 /// on \p SrcReg to access the actual value.
280 /// \return Unless the returned value is nullptr (i.e., no source found),
281 /// \p SrcReg gives the register of the next source used in the returned
282 /// instruction and \p SrcSubReg the sub-register index to be used on that
283 /// source to get the tracked value. When nullptr is returned, no
284 /// alternative source has been found.
285 const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
287 /// \brief Get the last register where the initial value can be found.
288 /// Initially this is the register of the definition.
289 /// Then, after each successful call to getNextSource, this is the
290 /// register of the last source.
291 unsigned getReg() const { return Reg; }
295 char PeepholeOptimizer::ID = 0;
296 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
297 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
298 "Peephole Optimizations", false, false)
299 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
300 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
301 "Peephole Optimizations", false, false)
303 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
304 /// a single register and writes a single register and it does not modify the
305 /// source, and if the source value is preserved as a sub-register of the
306 /// result, then replace all reachable uses of the source with the subreg of the
309 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
310 /// the code. Since this code does not currently share EXTRACTs, just ignore all
312 bool PeepholeOptimizer::
313 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
314 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
315 unsigned SrcReg, DstReg, SubIdx;
316 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
319 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
320 TargetRegisterInfo::isPhysicalRegister(SrcReg))
323 if (MRI->hasOneNonDBGUse(SrcReg))
327 // Ensure DstReg can get a register class that actually supports
328 // sub-registers. Don't change the class until we commit.
329 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
330 DstRC = TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
335 // The ext instr may be operating on a sub-register of SrcReg as well.
336 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
338 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
339 // SrcReg:SubIdx should be replaced.
341 TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
342 MRI->getRegClass(SrcReg), SubIdx) != nullptr;
344 // The source has other uses. See if we can replace the other uses with use of
345 // the result of the extension.
346 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
347 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
348 ReachedBBs.insert(UI.getParent());
350 // Uses that are in the same BB of uses of the result of the instruction.
351 SmallVector<MachineOperand*, 8> Uses;
353 // Uses that the result of the instruction can reach.
354 SmallVector<MachineOperand*, 8> ExtendedUses;
356 bool ExtendLife = true;
357 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
358 MachineInstr *UseMI = UseMO.getParent();
362 if (UseMI->isPHI()) {
367 // Only accept uses of SrcReg:SubIdx.
368 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
371 // It's an error to translate this:
373 // %reg1025 = <sext> %reg1024
375 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
379 // %reg1025 = <sext> %reg1024
381 // %reg1027 = COPY %reg1025:4
382 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
384 // The problem here is that SUBREG_TO_REG is there to assert that an
385 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
386 // the COPY here, it will give us the value after the <sext>, not the
387 // original value of %reg1024 before <sext>.
388 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
391 MachineBasicBlock *UseMBB = UseMI->getParent();
393 // Local uses that come after the extension.
394 if (!LocalMIs.count(UseMI))
395 Uses.push_back(&UseMO);
396 } else if (ReachedBBs.count(UseMBB)) {
397 // Non-local uses where the result of the extension is used. Always
398 // replace these unless it's a PHI.
399 Uses.push_back(&UseMO);
400 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
401 // We may want to extend the live range of the extension result in order
402 // to replace these uses.
403 ExtendedUses.push_back(&UseMO);
405 // Both will be live out of the def MBB anyway. Don't extend live range of
406 // the extension result.
412 if (ExtendLife && !ExtendedUses.empty())
413 // Extend the liveness of the extension result.
414 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
415 std::back_inserter(Uses));
417 // Now replace all uses.
418 bool Changed = false;
420 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
422 // Look for PHI uses of the extended result, we don't want to extend the
423 // liveness of a PHI input. It breaks all kinds of assumptions down
424 // stream. A PHI use is expected to be the kill of its source values.
425 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
427 PHIBBs.insert(UI.getParent());
429 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
430 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
431 MachineOperand *UseMO = Uses[i];
432 MachineInstr *UseMI = UseMO->getParent();
433 MachineBasicBlock *UseMBB = UseMI->getParent();
434 if (PHIBBs.count(UseMBB))
437 // About to add uses of DstReg, clear DstReg's kill flags.
439 MRI->clearKillFlags(DstReg);
440 MRI->constrainRegClass(DstReg, DstRC);
443 unsigned NewVR = MRI->createVirtualRegister(RC);
444 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
445 TII->get(TargetOpcode::COPY), NewVR)
446 .addReg(DstReg, 0, SubIdx);
447 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
449 Copy->getOperand(0).setSubReg(SubIdx);
450 Copy->getOperand(0).setIsUndef();
452 UseMO->setReg(NewVR);
461 /// optimizeCmpInstr - If the instruction is a compare and the previous
462 /// instruction it's comparing against all ready sets (or could be modified to
463 /// set) the same flag as the compare, then we can remove the comparison and use
464 /// the flag from the previous instruction.
465 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
466 MachineBasicBlock *MBB) {
467 // If this instruction is a comparison against zero and isn't comparing a
468 // physical register, we can try to optimize it.
469 unsigned SrcReg, SrcReg2;
470 int CmpMask, CmpValue;
471 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
472 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
473 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
476 // Attempt to optimize the comparison instruction.
477 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
485 /// Optimize a select instruction.
486 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI) {
488 unsigned FalseOp = 0;
489 bool Optimizable = false;
490 SmallVector<MachineOperand, 4> Cond;
491 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
495 if (!TII->optimizeSelect(MI))
497 MI->eraseFromParent();
502 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
503 /// share the same register file.
504 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
505 const TargetRegisterClass *DefRC,
507 const TargetRegisterClass *SrcRC,
508 unsigned SrcSubReg) {
509 // Same register class.
513 // Both operands are sub registers. Check if they share a register class.
514 unsigned SrcIdx, DefIdx;
515 if (SrcSubReg && DefSubReg)
516 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
517 SrcIdx, DefIdx) != nullptr;
518 // At most one of the register is a sub register, make it Src to avoid
519 // duplicating the test.
521 std::swap(DefSubReg, SrcSubReg);
522 std::swap(DefRC, SrcRC);
525 // One of the register is a sub register, check if we can get a superclass.
527 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
529 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
532 /// \brief Try to find the next source that share the same register file
533 /// for the value defined by \p Reg and \p SubReg.
534 /// When true is returned, \p Reg and \p SubReg are updated with the
535 /// register number and sub-register index of the new source.
536 /// \return False if no alternative sources are available. True otherwise.
537 bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
538 // Do not try to find a new source for a physical register.
539 // So far we do not have any motivating example for doing that.
540 // Thus, instead of maintaining untested code, we will revisit that if
541 // that changes at some point.
542 if (TargetRegisterInfo::isPhysicalRegister(Reg))
545 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
546 unsigned DefSubReg = SubReg;
550 bool ShouldRewrite = false;
551 const TargetRegisterInfo &TRI = *TM->getSubtargetImpl()->getRegisterInfo();
553 // Follow the chain of copies until we reach the top of the use-def chain
554 // or find a more suitable source.
555 ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
557 unsigned CopySrcReg, CopySrcSubReg;
558 if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
561 SrcSubReg = CopySrcSubReg;
563 // Do not extend the live-ranges of physical registers as they add
564 // constraints to the register allocator.
565 // Moreover, if we want to extend the live-range of a physical register,
566 // unlike SSA virtual register, we will have to check that they are not
567 // redefine before the related use.
568 if (TargetRegisterInfo::isPhysicalRegister(Src))
571 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
573 // If this source does not incur a cross register bank copy, use it.
574 ShouldRewrite = shareSameRegisterFile(TRI, DefRC, DefSubReg, SrcRC,
576 } while (!ShouldRewrite);
578 // If we did not find a more suitable source, there is nothing to optimize.
579 if (!ShouldRewrite || Src == Reg)
588 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
591 /// The copy-like instruction.
592 MachineInstr &CopyLike;
593 /// The index of the source being rewritten.
594 unsigned CurrentSrcIdx;
597 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
599 virtual ~CopyRewriter() {}
601 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
602 /// the related value that it affects (TrackReg, TrackSubReg).
603 /// A source is considered rewritable if its register class and the
604 /// register class of the related TrackReg may not be register
605 /// coalescer friendly. In other words, given a copy-like instruction
606 /// not all the arguments may be returned at rewritable source, since
607 /// some arguments are none to be register coalescer friendly.
609 /// Each call of this method moves the current source to the next
610 /// rewritable source.
611 /// For instance, let CopyLike be the instruction to rewrite.
612 /// CopyLike has one definition and one source:
613 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
615 /// The first call will give the first rewritable source, i.e.,
616 /// the only source this instruction has:
617 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
618 /// This source defines the whole definition, i.e.,
619 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
621 /// The second and subsequent calls will return false, has there is only one
622 /// rewritable source.
624 /// \return True if a rewritable source has been found, false otherwise.
625 /// The output arguments are valid if and only if true is returned.
626 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
628 unsigned &TrackSubReg) {
629 // If CurrentSrcIdx == 1, this means this function has already been
630 // called once. CopyLike has one defintiion and one argument, thus,
631 // there is nothing else to rewrite.
632 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
634 // This is the first call to getNextRewritableSource.
635 // Move the CurrentSrcIdx to remember that we made that call.
637 // The rewritable source is the argument.
638 const MachineOperand &MOSrc = CopyLike.getOperand(1);
639 SrcReg = MOSrc.getReg();
640 SrcSubReg = MOSrc.getSubReg();
641 // What we track are the alternative sources of the definition.
642 const MachineOperand &MODef = CopyLike.getOperand(0);
643 TrackReg = MODef.getReg();
644 TrackSubReg = MODef.getSubReg();
648 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
650 /// \return True if the rewritting was possible, false otherwise.
651 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
652 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
654 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
655 MOSrc.setReg(NewReg);
656 MOSrc.setSubReg(NewSubReg);
661 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
662 class InsertSubregRewriter : public CopyRewriter {
664 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
665 assert(MI.isInsertSubreg() && "Invalid instruction");
668 /// \brief See CopyRewriter::getNextRewritableSource.
669 /// Here CopyLike has the following form:
670 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
671 /// Src1 has the same register class has dst, hence, there is
672 /// nothing to rewrite.
673 /// Src2.src2SubIdx, may not be register coalescer friendly.
674 /// Therefore, the first call to this method returns:
675 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
676 /// (TrackReg, TrackSubReg) = (dst, subIdx).
678 /// Subsequence calls will return false.
679 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
681 unsigned &TrackSubReg) override {
682 // If we already get the only source we can rewrite, return false.
683 if (CurrentSrcIdx == 2)
685 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
687 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
688 SrcReg = MOInsertedReg.getReg();
689 SrcSubReg = MOInsertedReg.getSubReg();
690 const MachineOperand &MODef = CopyLike.getOperand(0);
692 // We want to track something that is compatible with the
693 // partial definition.
694 TrackReg = MODef.getReg();
695 if (MODef.getSubReg())
696 // Bails if we have to compose sub-register indices.
698 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
701 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
702 if (CurrentSrcIdx != 2)
704 // We are rewriting the inserted reg.
705 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
707 MO.setSubReg(NewSubReg);
712 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
713 class ExtractSubregRewriter : public CopyRewriter {
714 const TargetInstrInfo &TII;
717 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
718 : CopyRewriter(MI), TII(TII) {
719 assert(MI.isExtractSubreg() && "Invalid instruction");
722 /// \brief See CopyRewriter::getNextRewritableSource.
723 /// Here CopyLike has the following form:
724 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
725 /// There is only one rewritable source: Src.subIdx,
726 /// which defines dst.dstSubIdx.
727 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
729 unsigned &TrackSubReg) override {
730 // If we already get the only source we can rewrite, return false.
731 if (CurrentSrcIdx == 1)
733 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
735 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
736 SrcReg = MOExtractedReg.getReg();
737 // If we have to compose sub-register indices, bails out.
738 if (MOExtractedReg.getSubReg())
741 SrcSubReg = CopyLike.getOperand(2).getImm();
743 // We want to track something that is compatible with the definition.
744 const MachineOperand &MODef = CopyLike.getOperand(0);
745 TrackReg = MODef.getReg();
746 TrackSubReg = MODef.getSubReg();
750 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
751 // The only source we can rewrite is the input register.
752 if (CurrentSrcIdx != 1)
755 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
757 // If we find a source that does not require to extract something,
758 // rewrite the operation with a copy.
760 // Move the current index to an invalid position.
761 // We do not want another call to this method to be able
764 // Rewrite the operation as a COPY.
765 // Get rid of the sub-register index.
766 CopyLike.RemoveOperand(2);
767 // Morph the operation into a COPY.
768 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
771 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
776 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
777 class RegSequenceRewriter : public CopyRewriter {
779 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
780 assert(MI.isRegSequence() && "Invalid instruction");
783 /// \brief See CopyRewriter::getNextRewritableSource.
784 /// Here CopyLike has the following form:
785 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
786 /// Each call will return a different source, walking all the available
789 /// The first call returns:
790 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
791 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
793 /// The second call returns:
794 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
795 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
797 /// And so on, until all the sources have been traversed, then
798 /// it returns false.
799 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
801 unsigned &TrackSubReg) override {
802 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
804 // If this is the first call, move to the first argument.
805 if (CurrentSrcIdx == 0) {
808 // Otherwise, move to the next argument and check that it is valid.
810 if (CurrentSrcIdx >= CopyLike.getNumOperands())
813 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
814 SrcReg = MOInsertedReg.getReg();
815 // If we have to compose sub-register indices, bails out.
816 if ((SrcSubReg = MOInsertedReg.getSubReg()))
819 // We want to track something that is compatible with the related
820 // partial definition.
821 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
823 const MachineOperand &MODef = CopyLike.getOperand(0);
824 TrackReg = MODef.getReg();
825 // If we have to compose sub-registers, bails.
826 return MODef.getSubReg() == 0;
829 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
830 // We cannot rewrite out of bound operands.
831 // Moreover, rewritable sources are at odd positions.
832 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
835 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
837 MO.setSubReg(NewSubReg);
843 /// \brief Get the appropriated CopyRewriter for \p MI.
844 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
845 /// if no rewriter works for \p MI.
846 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
847 const TargetInstrInfo &TII) {
848 switch (MI.getOpcode()) {
851 case TargetOpcode::COPY:
852 return new CopyRewriter(MI);
853 case TargetOpcode::INSERT_SUBREG:
854 return new InsertSubregRewriter(MI);
855 case TargetOpcode::EXTRACT_SUBREG:
856 return new ExtractSubregRewriter(MI, TII);
857 case TargetOpcode::REG_SEQUENCE:
858 return new RegSequenceRewriter(MI);
860 llvm_unreachable(nullptr);
863 /// \brief Optimize generic copy instructions to avoid cross
864 /// register bank copy. The optimization looks through a chain of
865 /// copies and tries to find a source that has a compatible register
867 /// Two register classes are considered to be compatible if they share
868 /// the same register bank.
869 /// New copies issued by this optimization are register allocator
870 /// friendly. This optimization does not remove any copy as it may
871 /// overconstraint the register allocator, but replaces some operands
873 /// \pre isCoalescableCopy(*MI) is true.
874 /// \return True, when \p MI has been rewritten. False otherwise.
875 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
876 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
877 assert(MI->getDesc().getNumDefs() == 1 &&
878 "Coalescer can understand multiple defs?!");
879 const MachineOperand &MODef = MI->getOperand(0);
880 // Do not rewrite physical definitions.
881 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
884 bool Changed = false;
885 // Get the right rewriter for the current copy.
886 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
887 // If none exists, bails out.
890 // Rewrite each rewritable source.
891 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
892 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
894 unsigned NewSrc = TrackReg;
895 unsigned NewSubReg = TrackSubReg;
896 // Try to find a more suitable source.
897 // If we failed to do so, or get the actual source,
898 // move to the next source.
899 if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
902 Changed |= CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg);
904 // TODO: We could have a clean-up method to tidy the instruction.
905 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
907 // Currently we haven't seen motivating example for that and we
908 // want to avoid untested code.
909 NumRewrittenCopies += Changed == true;
913 /// \brief Optimize copy-like instructions to create
914 /// register coalescer friendly instruction.
915 /// The optimization tries to kill-off the \p MI by looking
916 /// through a chain of copies to find a source that has a compatible
918 /// If such a source is found, it replace \p MI by a generic COPY
920 /// \pre isUncoalescableCopy(*MI) is true.
921 /// \return True, when \p MI has been optimized. In that case, \p MI has
922 /// been removed from its parent.
923 /// All COPY instructions created, are inserted in \p LocalMIs.
924 bool PeepholeOptimizer::optimizeUncoalescableCopy(
925 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
926 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
928 // Check if we can rewrite all the values defined by this instruction.
930 std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
932 for (const MachineOperand &MODef : MI->defs()) {
934 // We can ignore those.
937 // If a physical register is here, this is probably for a good reason.
938 // Do not rewrite that.
939 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
942 // If we do not know how to rewrite this definition, there is no point
943 // in trying to kill this instruction.
944 TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
945 TargetInstrInfo::RegSubRegPair Src = Def;
946 if (!findNextSource(Src.Reg, Src.SubReg))
948 RewritePairs.push_back(std::make_pair(Def, Src));
950 // The change is possible for all defs, do it.
951 for (const auto &PairDefSrc : RewritePairs) {
952 const auto &Def = PairDefSrc.first;
953 const auto &Src = PairDefSrc.second;
954 // Rewrite the "copy" in a way the register coalescer understands.
955 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
956 "We do not rewrite physical registers");
957 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
958 unsigned NewVR = MRI->createVirtualRegister(DefRC);
959 MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
960 TII->get(TargetOpcode::COPY),
961 NewVR).addReg(Src.Reg, 0, Src.SubReg);
962 NewCopy->getOperand(0).setSubReg(Def.SubReg);
964 NewCopy->getOperand(0).setIsUndef();
965 LocalMIs.insert(NewCopy);
966 MRI->replaceRegWith(Def.Reg, NewVR);
967 MRI->clearKillFlags(NewVR);
968 // We extended the lifetime of Src.
969 // Clear the kill flags to account for that.
970 MRI->clearKillFlags(Src.Reg);
973 MI->eraseFromParent();
974 ++NumUncoalescableCopies;
978 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
979 /// instruction. We only fold loads to virtual registers and the virtual
980 /// register defined has a single use.
981 bool PeepholeOptimizer::isLoadFoldable(
983 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
984 if (!MI->canFoldAsLoad() || !MI->mayLoad())
986 const MCInstrDesc &MCID = MI->getDesc();
987 if (MCID.getNumDefs() != 1)
990 unsigned Reg = MI->getOperand(0).getReg();
991 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
992 // loads. It should be checked when processing uses of the load, since
993 // uses can be removed during peephole.
994 if (!MI->getOperand(0).getSubReg() &&
995 TargetRegisterInfo::isVirtualRegister(Reg) &&
996 MRI->hasOneNonDBGUse(Reg)) {
997 FoldAsLoadDefCandidates.insert(Reg);
1003 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1004 SmallSet<unsigned, 4> &ImmDefRegs,
1005 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1006 const MCInstrDesc &MCID = MI->getDesc();
1007 if (!MI->isMoveImmediate())
1009 if (MCID.getNumDefs() != 1)
1011 unsigned Reg = MI->getOperand(0).getReg();
1012 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1013 ImmDefMIs.insert(std::make_pair(Reg, MI));
1014 ImmDefRegs.insert(Reg);
1021 /// foldImmediate - Try folding register operands that are defined by move
1022 /// immediate instructions, i.e. a trivial constant folding optimization, if
1023 /// and only if the def and use are in the same BB.
1024 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1025 SmallSet<unsigned, 4> &ImmDefRegs,
1026 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1027 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1028 MachineOperand &MO = MI->getOperand(i);
1029 if (!MO.isReg() || MO.isDef())
1031 unsigned Reg = MO.getReg();
1032 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1034 if (ImmDefRegs.count(Reg) == 0)
1036 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1037 assert(II != ImmDefMIs.end());
1038 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1046 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1047 if (skipOptnoneFunction(*MF.getFunction()))
1050 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1051 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1053 if (DisablePeephole)
1056 TM = &MF.getTarget();
1057 TII = TM->getSubtargetImpl()->getInstrInfo();
1058 MRI = &MF.getRegInfo();
1059 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1061 bool Changed = false;
1063 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1064 MachineBasicBlock *MBB = &*I;
1066 bool SeenMoveImm = false;
1067 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1068 SmallSet<unsigned, 4> ImmDefRegs;
1069 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1070 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1072 for (MachineBasicBlock::iterator
1073 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1074 MachineInstr *MI = &*MII;
1075 // We may be erasing MI below, increment MII now.
1077 LocalMIs.insert(MI);
1079 // Skip debug values. They should not affect this peephole optimization.
1080 if (MI->isDebugValue())
1083 // If there exists an instruction which belongs to the following
1084 // categories, we will discard the load candidates.
1085 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1086 MI->isKill() || MI->isInlineAsm() ||
1087 MI->hasUnmodeledSideEffects()) {
1088 FoldAsLoadDefCandidates.clear();
1091 if (MI->mayStore() || MI->isCall())
1092 FoldAsLoadDefCandidates.clear();
1094 if ((isUncoalescableCopy(*MI) &&
1095 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1096 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1097 (MI->isSelect() && optimizeSelect(MI))) {
1104 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1105 // MI is just rewritten.
1110 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1113 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1114 // optimizeExtInstr might have created new instructions after MI
1115 // and before the already incremented MII. Adjust MII so that the
1116 // next iteration sees the new instructions.
1120 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1123 // Check whether MI is a load candidate for folding into a later
1124 // instruction. If MI is not a candidate, check whether we can fold an
1125 // earlier load into MI.
1126 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1127 !FoldAsLoadDefCandidates.empty()) {
1128 const MCInstrDesc &MIDesc = MI->getDesc();
1129 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1131 const MachineOperand &MOp = MI->getOperand(i);
1134 unsigned FoldAsLoadDefReg = MOp.getReg();
1135 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1136 // We need to fold load after optimizeCmpInstr, since
1137 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1138 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1139 // we need it for markUsesInDebugValueAsUndef().
1140 unsigned FoldedReg = FoldAsLoadDefReg;
1141 MachineInstr *DefMI = nullptr;
1142 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1146 // Update LocalMIs since we replaced MI with FoldMI and deleted
1148 DEBUG(dbgs() << "Replacing: " << *MI);
1149 DEBUG(dbgs() << " With: " << *FoldMI);
1151 LocalMIs.erase(DefMI);
1152 LocalMIs.insert(FoldMI);
1153 MI->eraseFromParent();
1154 DefMI->eraseFromParent();
1155 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1156 FoldAsLoadDefCandidates.erase(FoldedReg);
1158 // MI is replaced with FoldMI.
1171 bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
1172 unsigned &SrcSubReg) {
1173 assert(Def->isCopy() && "Invalid definition");
1174 // Copy instruction are supposed to be: Def = Src.
1175 // If someone breaks this assumption, bad things will happen everywhere.
1176 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1178 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1179 // If we look for a different subreg, it means we want a subreg of src.
1180 // Bails as we do not support composing subreg yet.
1182 // Otherwise, we want the whole source.
1183 const MachineOperand &Src = Def->getOperand(1);
1184 SrcReg = Src.getReg();
1185 SrcSubReg = Src.getSubReg();
1189 bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
1190 unsigned &SrcSubReg) {
1191 assert(Def->isBitcast() && "Invalid definition");
1193 // Bail if there are effects that a plain copy will not expose.
1194 if (Def->hasUnmodeledSideEffects())
1197 // Bitcasts with more than one def are not supported.
1198 if (Def->getDesc().getNumDefs() != 1)
1200 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1201 // If we look for a different subreg, it means we want a subreg of the src.
1202 // Bails as we do not support composing subreg yet.
1205 unsigned SrcIdx = Def->getNumOperands();
1206 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1208 const MachineOperand &MO = Def->getOperand(OpIdx);
1209 if (!MO.isReg() || !MO.getReg())
1211 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1212 if (SrcIdx != EndOpIdx)
1213 // Multiple sources?
1217 const MachineOperand &Src = Def->getOperand(SrcIdx);
1218 SrcReg = Src.getReg();
1219 SrcSubReg = Src.getSubReg();
1223 bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
1224 unsigned &SrcSubReg) {
1225 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1226 "Invalid definition");
1228 if (Def->getOperand(DefIdx).getSubReg())
1229 // If we are composing subreg, bails out.
1230 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1231 // This should almost never happen as the SSA property is tracked at
1232 // the register level (as opposed to the subreg level).
1236 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1237 // Def. Thus, it must not be generated.
1238 // However, some code could theoretically generates a single
1239 // Def.sub0 (i.e, not defining the other subregs) and we would
1241 // If we can ascertain (or force) that this never happens, we could
1242 // turn that into an assertion.
1246 // We could handle the REG_SEQUENCE here, but we do not want to
1247 // duplicate the code from the generic TII.
1250 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1251 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1254 // We are looking at:
1255 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1256 // Check if one of the operand defines the subreg we are interested in.
1257 for (auto &RegSeqInput : RegSeqInputRegs) {
1258 if (RegSeqInput.SubIdx == DefSubReg) {
1259 if (RegSeqInput.SubReg)
1260 // Bails if we have to compose sub registers.
1263 SrcReg = RegSeqInput.Reg;
1264 SrcSubReg = RegSeqInput.SubReg;
1269 // If the subreg we are tracking is super-defined by another subreg,
1270 // we could follow this value. However, this would require to compose
1271 // the subreg and we do not do that for now.
1275 bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
1276 unsigned &SrcSubReg) {
1277 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1278 "Invalid definition");
1280 if (Def->getOperand(DefIdx).getSubReg())
1281 // If we are composing subreg, bails out.
1282 // Same remark as getNextSourceFromRegSequence.
1283 // I.e., this may be turned into an assert.
1287 // We could handle the REG_SEQUENCE here, but we do not want to
1288 // duplicate the code from the generic TII.
1291 TargetInstrInfo::RegSubRegPair BaseReg;
1292 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1293 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1296 // We are looking at:
1297 // Def = INSERT_SUBREG v0, v1, sub1
1298 // There are two cases:
1299 // 1. DefSubReg == sub1, get v1.
1300 // 2. DefSubReg != sub1, the value may be available through v0.
1302 // #1 Check if the inserted register matches the required sub index.
1303 if (InsertedReg.SubIdx == DefSubReg) {
1304 SrcReg = InsertedReg.Reg;
1305 SrcSubReg = InsertedReg.SubReg;
1308 // #2 Otherwise, if the sub register we are looking for is not partial
1309 // defined by the inserted element, we can look through the main
1311 const MachineOperand &MODef = Def->getOperand(DefIdx);
1312 // If the result register (Def) and the base register (v0) do not
1313 // have the same register class or if we have to compose
1314 // subregisters, bails out.
1315 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1319 // Get the TRI and check if the inserted sub-register overlaps with the
1320 // sub-register we are tracking.
1321 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1323 (TRI->getSubRegIndexLaneMask(DefSubReg) &
1324 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1326 // At this point, the value is available in v0 via the same subreg
1328 SrcReg = BaseReg.Reg;
1329 SrcSubReg = DefSubReg;
1333 bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
1334 unsigned &SrcSubReg) {
1335 assert((Def->isExtractSubreg() ||
1336 Def->isExtractSubregLike()) && "Invalid definition");
1337 // We are looking at:
1338 // Def = EXTRACT_SUBREG v0, sub0
1340 // Bails if we have to compose sub registers.
1341 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1346 // We could handle the EXTRACT_SUBREG here, but we do not want to
1347 // duplicate the code from the generic TII.
1350 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1351 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1354 // Bails if we have to compose sub registers.
1355 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1356 if (ExtractSubregInputReg.SubReg)
1358 // Otherwise, the value is available in the v0.sub0.
1359 SrcReg = ExtractSubregInputReg.Reg;
1360 SrcSubReg = ExtractSubregInputReg.SubIdx;
1364 bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
1365 unsigned &SrcSubReg) {
1366 assert(Def->isSubregToReg() && "Invalid definition");
1367 // We are looking at:
1368 // Def = SUBREG_TO_REG Imm, v0, sub0
1370 // Bails if we have to compose sub registers.
1371 // If DefSubReg != sub0, we would have to check that all the bits
1372 // we track are included in sub0 and if yes, we would have to
1373 // determine the right subreg in v0.
1374 if (DefSubReg != Def->getOperand(3).getImm())
1376 // Bails if we have to compose sub registers.
1377 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1378 if (Def->getOperand(2).getSubReg())
1381 SrcReg = Def->getOperand(2).getReg();
1382 SrcSubReg = Def->getOperand(3).getImm();
1386 bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
1387 assert(Def && "This method needs a valid definition");
1390 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1391 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1393 return getNextSourceFromCopy(SrcReg, SrcSubReg);
1394 if (Def->isBitcast())
1395 return getNextSourceFromBitcast(SrcReg, SrcSubReg);
1396 // All the remaining cases involve "complex" instructions.
1397 // Bails if we did not ask for the advanced tracking.
1398 if (!UseAdvancedTracking)
1400 if (Def->isRegSequence() || Def->isRegSequenceLike())
1401 return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
1402 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1403 return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
1404 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1405 return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
1406 if (Def->isSubregToReg())
1407 return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
1411 const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
1412 unsigned &SrcSubReg) {
1413 // If we reach a point where we cannot move up in the use-def chain,
1414 // there is nothing we can get.
1418 const MachineInstr *PrevDef = nullptr;
1419 // Try to find the next source.
1420 if (getNextSourceImpl(SrcReg, SrcSubReg)) {
1421 // Update definition, definition index, and subregister for the
1422 // next call of getNextSource.
1423 // Update the current register.
1425 // Update the return value before moving up in the use-def chain.
1427 // If we can still move up in the use-def chain, move to the next
1429 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
1430 Def = MRI.getVRegDef(Reg);
1431 DefIdx = MRI.def_begin(Reg).getOperandNo();
1432 DefSubReg = SrcSubReg;
1436 // If we end up here, this means we will not be able to find another source
1437 // for the next iteration.
1438 // Make sure any new call to getNextSource bails out early by cutting the