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/Support/raw_ostream.h"
80 #include "llvm/Target/TargetInstrInfo.h"
81 #include "llvm/Target/TargetRegisterInfo.h"
82 #include "llvm/Target/TargetSubtargetInfo.h"
86 #define DEBUG_TYPE "peephole-opt"
88 // Optimize Extensions
90 Aggressive("aggressive-ext-opt", cl::Hidden,
91 cl::desc("Aggressive extension optimization"));
94 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95 cl::desc("Disable the peephole optimizer"));
98 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
99 cl::desc("Disable advanced copy optimization"));
101 // Limit the number of PHI instructions to process
102 // in PeepholeOptimizer::getNextSource.
103 static cl::opt<unsigned> RewritePHILimit(
104 "rewrite-phi-limit", cl::Hidden, cl::init(10),
105 cl::desc("Limit the length of PHI chains to lookup"));
107 STATISTIC(NumReuse, "Number of extension results reused");
108 STATISTIC(NumCmps, "Number of compares eliminated");
109 STATISTIC(NumImmFold, "Number of move immediate folded");
110 STATISTIC(NumLoadFold, "Number of loads folded");
111 STATISTIC(NumSelects, "Number of selects optimized");
112 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
113 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
116 class ValueTrackerResult;
118 class PeepholeOptimizer : public MachineFunctionPass {
119 const TargetInstrInfo *TII;
120 const TargetRegisterInfo *TRI;
121 MachineRegisterInfo *MRI;
122 MachineDominatorTree *DT; // Machine dominator tree
125 static char ID; // Pass identification
126 PeepholeOptimizer() : MachineFunctionPass(ID) {
127 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
130 bool runOnMachineFunction(MachineFunction &MF) override;
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
136 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineDominatorTree>();
141 /// \brief Track Def -> Use info used for rewriting copies.
142 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
146 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
147 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
148 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
149 bool optimizeSelect(MachineInstr *MI,
150 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
151 bool optimizeCondBranch(MachineInstr *MI);
152 bool optimizeCopyOrBitcast(MachineInstr *MI);
153 bool optimizeCoalescableCopy(MachineInstr *MI);
154 bool optimizeUncoalescableCopy(MachineInstr *MI,
155 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
156 bool findNextSource(unsigned Reg, unsigned SubReg,
157 RewriteMapTy &RewriteMap);
158 bool isMoveImmediate(MachineInstr *MI,
159 SmallSet<unsigned, 4> &ImmDefRegs,
160 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
161 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
162 SmallSet<unsigned, 4> &ImmDefRegs,
163 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
164 bool isLoadFoldable(MachineInstr *MI,
165 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
167 /// \brief Check whether \p MI is understood by the register coalescer
168 /// but may require some rewriting.
169 bool isCoalescableCopy(const MachineInstr &MI) {
170 // SubregToRegs are not interesting, because they are already register
171 // coalescer friendly.
172 return MI.isCopy() || (!DisableAdvCopyOpt &&
173 (MI.isRegSequence() || MI.isInsertSubreg() ||
174 MI.isExtractSubreg()));
177 /// \brief Check whether \p MI is a copy like instruction that is
178 /// not recognized by the register coalescer.
179 bool isUncoalescableCopy(const MachineInstr &MI) {
180 return MI.isBitcast() ||
181 (!DisableAdvCopyOpt &&
182 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
183 MI.isExtractSubregLike()));
187 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
188 /// returned sources for a given search and the instructions where the sources
189 /// were tracked from.
190 class ValueTrackerResult {
192 /// Track all sources found by one ValueTracker query.
193 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
195 /// Instruction using the sources in 'RegSrcs'.
196 const MachineInstr *Inst;
199 ValueTrackerResult() : Inst(nullptr) {}
200 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
201 addSource(Reg, SubReg);
204 bool isValid() const { return getNumSources() > 0; }
206 void setInst(const MachineInstr *I) { Inst = I; }
207 const MachineInstr *getInst() const { return Inst; }
214 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
215 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
218 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
219 assert(Idx < getNumSources() && "Reg pair source out of index");
220 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
223 int getNumSources() const { return RegSrcs.size(); }
225 unsigned getSrcReg(int Idx) const {
226 assert(Idx < getNumSources() && "Reg source out of index");
227 return RegSrcs[Idx].Reg;
230 unsigned getSrcSubReg(int Idx) const {
231 assert(Idx < getNumSources() && "SubReg source out of index");
232 return RegSrcs[Idx].SubReg;
235 bool operator==(const ValueTrackerResult &Other) {
236 if (Other.getInst() != getInst())
239 if (Other.getNumSources() != getNumSources())
242 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
243 if (Other.getSrcReg(i) != getSrcReg(i) ||
244 Other.getSrcSubReg(i) != getSrcSubReg(i))
250 /// \brief Helper class to track the possible sources of a value defined by
251 /// a (chain of) copy related instructions.
252 /// Given a definition (instruction and definition index), this class
253 /// follows the use-def chain to find successive suitable sources.
254 /// The given source can be used to rewrite the definition into
257 /// For instance, let us consider the following snippet:
259 /// v2 = INSERT_SUBREG v1, v0, sub0
260 /// def = COPY v2.sub0
262 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
263 /// suitable sources:
265 /// Then, def can be rewritten into def = COPY v0.
268 /// The current point into the use-def chain.
269 const MachineInstr *Def;
270 /// The index of the definition in Def.
272 /// The sub register index of the definition.
274 /// The register where the value can be found.
276 /// Specifiy whether or not the value tracking looks through
277 /// complex instructions. When this is false, the value tracker
278 /// bails on everything that is not a copy or a bitcast.
280 /// Note: This could have been implemented as a specialized version of
281 /// the ValueTracker class but that would have complicated the code of
282 /// the users of this class.
283 bool UseAdvancedTracking;
284 /// MachineRegisterInfo used to perform tracking.
285 const MachineRegisterInfo &MRI;
286 /// Optional TargetInstrInfo used to perform some complex
288 const TargetInstrInfo *TII;
290 /// \brief Dispatcher to the right underlying implementation of
292 ValueTrackerResult getNextSourceImpl();
293 /// \brief Specialized version of getNextSource for Copy instructions.
294 ValueTrackerResult getNextSourceFromCopy();
295 /// \brief Specialized version of getNextSource for Bitcast instructions.
296 ValueTrackerResult getNextSourceFromBitcast();
297 /// \brief Specialized version of getNextSource for RegSequence
299 ValueTrackerResult getNextSourceFromRegSequence();
300 /// \brief Specialized version of getNextSource for InsertSubreg
302 ValueTrackerResult getNextSourceFromInsertSubreg();
303 /// \brief Specialized version of getNextSource for ExtractSubreg
305 ValueTrackerResult getNextSourceFromExtractSubreg();
306 /// \brief Specialized version of getNextSource for SubregToReg
308 ValueTrackerResult getNextSourceFromSubregToReg();
309 /// \brief Specialized version of getNextSource for PHI instructions.
310 ValueTrackerResult getNextSourceFromPHI();
313 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
314 /// \p DefSubReg represents the sub register index the value tracker will
315 /// track. It does not need to match the sub register index used in the
316 /// definition of \p Reg.
317 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
318 /// through complex instructions. By default (false), it handles only copy
319 /// and bitcast instructions.
320 /// If \p Reg is a physical register, a value tracker constructed with
321 /// this constructor will not find any alternative source.
322 /// Indeed, when \p Reg is a physical register that constructor does not
323 /// know which definition of \p Reg it should track.
324 /// Use the next constructor to track a physical register.
325 ValueTracker(unsigned Reg, unsigned DefSubReg,
326 const MachineRegisterInfo &MRI,
327 bool UseAdvancedTracking = false,
328 const TargetInstrInfo *TII = nullptr)
329 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
330 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
331 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
332 Def = MRI.getVRegDef(Reg);
333 DefIdx = MRI.def_begin(Reg).getOperandNo();
337 /// \brief Create a ValueTracker instance for the value defined by
338 /// the pair \p MI, \p DefIdx.
339 /// Unlike the other constructor, the value tracker produced by this one
340 /// may be able to find a new source when the definition is a physical
342 /// This could be useful to rewrite target specific instructions into
343 /// generic copy instructions.
344 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
345 const MachineRegisterInfo &MRI,
346 bool UseAdvancedTracking = false,
347 const TargetInstrInfo *TII = nullptr)
348 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
349 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
350 assert(DefIdx < Def->getDesc().getNumDefs() &&
351 Def->getOperand(DefIdx).isReg() && "Invalid definition");
352 Reg = Def->getOperand(DefIdx).getReg();
355 /// \brief Following the use-def chain, get the next available source
356 /// for the tracked value.
357 /// \return A ValueTrackerResult containing a set of registers
358 /// and sub registers with tracked values. A ValueTrackerResult with
359 /// an empty set of registers means no source was found.
360 ValueTrackerResult getNextSource();
362 /// \brief Get the last register where the initial value can be found.
363 /// Initially this is the register of the definition.
364 /// Then, after each successful call to getNextSource, this is the
365 /// register of the last source.
366 unsigned getReg() const { return Reg; }
370 char PeepholeOptimizer::ID = 0;
371 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
372 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
373 "Peephole Optimizations", false, false)
374 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
375 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
376 "Peephole Optimizations", false, false)
378 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
379 /// a single register and writes a single register and it does not modify the
380 /// source, and if the source value is preserved as a sub-register of the
381 /// result, then replace all reachable uses of the source with the subreg of the
384 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
385 /// the code. Since this code does not currently share EXTRACTs, just ignore all
387 bool PeepholeOptimizer::
388 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
389 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
390 unsigned SrcReg, DstReg, SubIdx;
391 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
394 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
395 TargetRegisterInfo::isPhysicalRegister(SrcReg))
398 if (MRI->hasOneNonDBGUse(SrcReg))
402 // Ensure DstReg can get a register class that actually supports
403 // sub-registers. Don't change the class until we commit.
404 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
405 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
409 // The ext instr may be operating on a sub-register of SrcReg as well.
410 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
412 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
413 // SrcReg:SubIdx should be replaced.
415 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
417 // The source has other uses. See if we can replace the other uses with use of
418 // the result of the extension.
419 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
420 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
421 ReachedBBs.insert(UI.getParent());
423 // Uses that are in the same BB of uses of the result of the instruction.
424 SmallVector<MachineOperand*, 8> Uses;
426 // Uses that the result of the instruction can reach.
427 SmallVector<MachineOperand*, 8> ExtendedUses;
429 bool ExtendLife = true;
430 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
431 MachineInstr *UseMI = UseMO.getParent();
435 if (UseMI->isPHI()) {
440 // Only accept uses of SrcReg:SubIdx.
441 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
444 // It's an error to translate this:
446 // %reg1025 = <sext> %reg1024
448 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
452 // %reg1025 = <sext> %reg1024
454 // %reg1027 = COPY %reg1025:4
455 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
457 // The problem here is that SUBREG_TO_REG is there to assert that an
458 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
459 // the COPY here, it will give us the value after the <sext>, not the
460 // original value of %reg1024 before <sext>.
461 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
464 MachineBasicBlock *UseMBB = UseMI->getParent();
466 // Local uses that come after the extension.
467 if (!LocalMIs.count(UseMI))
468 Uses.push_back(&UseMO);
469 } else if (ReachedBBs.count(UseMBB)) {
470 // Non-local uses where the result of the extension is used. Always
471 // replace these unless it's a PHI.
472 Uses.push_back(&UseMO);
473 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
474 // We may want to extend the live range of the extension result in order
475 // to replace these uses.
476 ExtendedUses.push_back(&UseMO);
478 // Both will be live out of the def MBB anyway. Don't extend live range of
479 // the extension result.
485 if (ExtendLife && !ExtendedUses.empty())
486 // Extend the liveness of the extension result.
487 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
489 // Now replace all uses.
490 bool Changed = false;
492 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
494 // Look for PHI uses of the extended result, we don't want to extend the
495 // liveness of a PHI input. It breaks all kinds of assumptions down
496 // stream. A PHI use is expected to be the kill of its source values.
497 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
499 PHIBBs.insert(UI.getParent());
501 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
502 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
503 MachineOperand *UseMO = Uses[i];
504 MachineInstr *UseMI = UseMO->getParent();
505 MachineBasicBlock *UseMBB = UseMI->getParent();
506 if (PHIBBs.count(UseMBB))
509 // About to add uses of DstReg, clear DstReg's kill flags.
511 MRI->clearKillFlags(DstReg);
512 MRI->constrainRegClass(DstReg, DstRC);
515 unsigned NewVR = MRI->createVirtualRegister(RC);
516 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
517 TII->get(TargetOpcode::COPY), NewVR)
518 .addReg(DstReg, 0, SubIdx);
519 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
521 Copy->getOperand(0).setSubReg(SubIdx);
522 Copy->getOperand(0).setIsUndef();
524 UseMO->setReg(NewVR);
533 /// optimizeCmpInstr - If the instruction is a compare and the previous
534 /// instruction it's comparing against all ready sets (or could be modified to
535 /// set) the same flag as the compare, then we can remove the comparison and use
536 /// the flag from the previous instruction.
537 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
538 MachineBasicBlock *MBB) {
539 // If this instruction is a comparison against zero and isn't comparing a
540 // physical register, we can try to optimize it.
541 unsigned SrcReg, SrcReg2;
542 int CmpMask, CmpValue;
543 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
544 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
545 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
548 // Attempt to optimize the comparison instruction.
549 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
557 /// Optimize a select instruction.
558 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
559 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
561 unsigned FalseOp = 0;
562 bool Optimizable = false;
563 SmallVector<MachineOperand, 4> Cond;
564 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
568 if (!TII->optimizeSelect(MI, LocalMIs))
570 MI->eraseFromParent();
575 /// \brief Check if a simpler conditional branch can be
577 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
578 return TII->optimizeCondBranch(MI);
581 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
582 /// share the same register file.
583 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
584 const TargetRegisterClass *DefRC,
586 const TargetRegisterClass *SrcRC,
587 unsigned SrcSubReg) {
588 // Same register class.
592 // Both operands are sub registers. Check if they share a register class.
593 unsigned SrcIdx, DefIdx;
594 if (SrcSubReg && DefSubReg)
595 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
596 SrcIdx, DefIdx) != nullptr;
597 // At most one of the register is a sub register, make it Src to avoid
598 // duplicating the test.
600 std::swap(DefSubReg, SrcSubReg);
601 std::swap(DefRC, SrcRC);
604 // One of the register is a sub register, check if we can get a superclass.
606 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
608 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
611 /// \brief Try to find the next source that share the same register file
612 /// for the value defined by \p Reg and \p SubReg.
613 /// When true is returned, the \p RewriteMap can be used by the client to
614 /// retrieve all Def -> Use along the way up to the next source. Any found
615 /// Use that is not itself a key for another entry, is the next source to
616 /// use. During the search for the next source, multiple sources can be found
617 /// given multiple incoming sources of a PHI instruction. In this case, we
618 /// look in each PHI source for the next source; all found next sources must
619 /// share the same register file as \p Reg and \p SubReg. The client should
620 /// then be capable to rewrite all intermediate PHIs to get the next source.
621 /// \return False if no alternative sources are available. True otherwise.
622 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
623 RewriteMapTy &RewriteMap) {
624 // Do not try to find a new source for a physical register.
625 // So far we do not have any motivating example for doing that.
626 // Thus, instead of maintaining untested code, we will revisit that if
627 // that changes at some point.
628 if (TargetRegisterInfo::isPhysicalRegister(Reg))
630 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
632 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
633 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
634 SrcToLook.push_back(CurSrcPair);
636 unsigned PHICount = 0;
637 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
638 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
639 // As explained above, do not handle physical registers
640 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
644 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
645 !DisableAdvCopyOpt, TII);
646 ValueTrackerResult Res;
647 bool ShouldRewrite = false;
650 // Follow the chain of copies until we reach the top of the use-def chain
651 // or find a more suitable source.
652 Res = ValTracker.getNextSource();
656 // Insert the Def -> Use entry for the recently found source.
657 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
658 if (CurSrcRes.isValid()) {
659 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
660 // An existent entry with multiple sources is a PHI cycle we must avoid.
661 // Otherwise it's an entry with a valid next source we already found.
662 if (CurSrcRes.getNumSources() > 1) {
663 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
668 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
670 // ValueTrackerResult usually have one source unless it's the result from
671 // a PHI instruction. Add the found PHI edges to be looked up further.
672 unsigned NumSrcs = Res.getNumSources();
675 for (unsigned i = 0; i < NumSrcs; ++i)
676 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
677 Res.getSrcReg(i), Res.getSrcSubReg(i)));
681 CurSrcPair.Reg = Res.getSrcReg(0);
682 CurSrcPair.SubReg = Res.getSrcSubReg(0);
683 // Do not extend the live-ranges of physical registers as they add
684 // constraints to the register allocator. Moreover, if we want to extend
685 // the live-range of a physical register, unlike SSA virtual register,
686 // we will have to check that they aren't redefine before the related use.
687 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
690 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
692 // If this source does not incur a cross register bank copy, use it.
693 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, SubReg, SrcRC,
695 } while (!ShouldRewrite);
697 // Continue looking for new sources...
701 // Do not continue searching for a new source if the there's at least
702 // one use-def which cannot be rewritten.
707 if (PHICount >= RewritePHILimit) {
708 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
712 // If we did not find a more suitable source, there is nothing to optimize.
713 if (CurSrcPair.Reg == Reg)
719 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
720 /// guaranteed to have the same register class. This is necessary whenever we
721 /// successfully traverse a PHI instruction and find suitable sources coming
722 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
723 /// suitable to be used in a new COPY instruction.
724 static MachineInstr *
725 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
726 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
727 MachineInstr *OrigPHI) {
728 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
730 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
731 unsigned NewVR = MRI->createVirtualRegister(NewRC);
732 MachineBasicBlock *MBB = OrigPHI->getParent();
733 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
734 TII->get(TargetOpcode::PHI), NewVR);
736 unsigned MBBOpIdx = 2;
737 for (auto RegPair : SrcRegs) {
738 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
739 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
740 // Since we're extended the lifetime of RegPair.Reg, clear the
741 // kill flags to account for that and make RegPair.Reg reaches
743 MRI->clearKillFlags(RegPair.Reg);
751 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
754 /// The copy-like instruction.
755 MachineInstr &CopyLike;
756 /// The index of the source being rewritten.
757 unsigned CurrentSrcIdx;
760 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
762 virtual ~CopyRewriter() {}
764 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
765 /// the related value that it affects (TrackReg, TrackSubReg).
766 /// A source is considered rewritable if its register class and the
767 /// register class of the related TrackReg may not be register
768 /// coalescer friendly. In other words, given a copy-like instruction
769 /// not all the arguments may be returned at rewritable source, since
770 /// some arguments are none to be register coalescer friendly.
772 /// Each call of this method moves the current source to the next
773 /// rewritable source.
774 /// For instance, let CopyLike be the instruction to rewrite.
775 /// CopyLike has one definition and one source:
776 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
778 /// The first call will give the first rewritable source, i.e.,
779 /// the only source this instruction has:
780 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
781 /// This source defines the whole definition, i.e.,
782 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
784 /// The second and subsequent calls will return false, as there is only one
785 /// rewritable source.
787 /// \return True if a rewritable source has been found, false otherwise.
788 /// The output arguments are valid if and only if true is returned.
789 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
791 unsigned &TrackSubReg) {
792 // If CurrentSrcIdx == 1, this means this function has already been called
793 // once. CopyLike has one definition and one argument, thus, there is
794 // nothing else to rewrite.
795 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
797 // This is the first call to getNextRewritableSource.
798 // Move the CurrentSrcIdx to remember that we made that call.
800 // The rewritable source is the argument.
801 const MachineOperand &MOSrc = CopyLike.getOperand(1);
802 SrcReg = MOSrc.getReg();
803 SrcSubReg = MOSrc.getSubReg();
804 // What we track are the alternative sources of the definition.
805 const MachineOperand &MODef = CopyLike.getOperand(0);
806 TrackReg = MODef.getReg();
807 TrackSubReg = MODef.getSubReg();
811 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
813 /// \return True if the rewriting was possible, false otherwise.
814 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
815 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
817 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
818 MOSrc.setReg(NewReg);
819 MOSrc.setSubReg(NewSubReg);
823 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
824 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
825 /// multiple sources for a given \p Def are found along the way, we found a
826 /// PHI instructions that needs to be rewritten.
827 /// TODO: HandleMultipleSources should be removed once we test PHI handling
828 /// with coalescable copies.
829 TargetInstrInfo::RegSubRegPair
830 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
831 TargetInstrInfo::RegSubRegPair Def,
832 PeepholeOptimizer::RewriteMapTy &RewriteMap,
833 bool HandleMultipleSources = true) {
835 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
837 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
838 // If there are no entries on the map, LookupSrc is the new source.
842 // There's only one source for this definition, keep searching...
843 unsigned NumSrcs = Res.getNumSources();
845 LookupSrc.Reg = Res.getSrcReg(0);
846 LookupSrc.SubReg = Res.getSrcSubReg(0);
850 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
851 if (!HandleMultipleSources)
854 // Multiple sources, recurse into each source to find a new source
855 // for it. Then, rewrite the PHI accordingly to its new edges.
856 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
857 for (unsigned i = 0; i < NumSrcs; ++i) {
858 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
859 Res.getSrcSubReg(i));
860 NewPHISrcs.push_back(
861 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
864 // Build the new PHI node and return its def register as the new source.
865 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
866 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
867 DEBUG(dbgs() << "-- getNewSource\n");
868 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
869 DEBUG(dbgs() << " With: " << *NewPHI);
870 const MachineOperand &MODef = NewPHI->getOperand(0);
871 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
875 return TargetInstrInfo::RegSubRegPair(0, 0);
878 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
879 /// and create a new COPY instruction. More info about RewriteMap in
880 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
881 /// Uncoalescable copies, since they are copy like instructions that aren't
882 /// recognized by the register allocator.
883 virtual MachineInstr *
884 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
885 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
890 /// \brief Helper class to rewrite uncoalescable copy like instructions
891 /// into new COPY (coalescable friendly) instructions.
892 class UncoalescableRewriter : public CopyRewriter {
894 const TargetInstrInfo &TII;
895 MachineRegisterInfo &MRI;
896 /// The number of defs in the bitcast
900 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
901 MachineRegisterInfo &MRI)
902 : CopyRewriter(MI), TII(TII), MRI(MRI) {
903 NumDefs = MI.getDesc().getNumDefs();
906 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
907 /// All such sources need to be considered rewritable in order to
908 /// rewrite a uncoalescable copy-like instruction. This method return
909 /// each definition that must be checked if rewritable.
911 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
913 unsigned &TrackSubReg) override {
914 // Find the next non-dead definition and continue from there.
915 if (CurrentSrcIdx == NumDefs)
918 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
920 if (CurrentSrcIdx == NumDefs)
924 // What we track are the alternative sources of the definition.
925 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
926 TrackReg = MODef.getReg();
927 TrackSubReg = MODef.getSubReg();
933 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
934 /// and create a new COPY instruction. More info about RewriteMap in
935 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
936 /// Uncoalescable copies, since they are copy like instructions that aren't
937 /// recognized by the register allocator.
939 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
940 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
941 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
942 "We do not rewrite physical registers");
944 // Find the new source to use in the COPY rewrite.
945 TargetInstrInfo::RegSubRegPair NewSrc =
946 getNewSource(&MRI, &TII, Def, RewriteMap);
949 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
950 unsigned NewVR = MRI.createVirtualRegister(DefRC);
952 MachineInstr *NewCopy =
953 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
954 TII.get(TargetOpcode::COPY), NewVR)
955 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
957 NewCopy->getOperand(0).setSubReg(Def.SubReg);
959 NewCopy->getOperand(0).setIsUndef();
961 DEBUG(dbgs() << "-- RewriteSource\n");
962 DEBUG(dbgs() << " Replacing: " << CopyLike);
963 DEBUG(dbgs() << " With: " << *NewCopy);
964 MRI.replaceRegWith(Def.Reg, NewVR);
965 MRI.clearKillFlags(NewVR);
967 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
969 MRI.clearKillFlags(NewSrc.Reg);
975 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
976 class InsertSubregRewriter : public CopyRewriter {
978 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
979 assert(MI.isInsertSubreg() && "Invalid instruction");
982 /// \brief See CopyRewriter::getNextRewritableSource.
983 /// Here CopyLike has the following form:
984 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
985 /// Src1 has the same register class has dst, hence, there is
986 /// nothing to rewrite.
987 /// Src2.src2SubIdx, may not be register coalescer friendly.
988 /// Therefore, the first call to this method returns:
989 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
990 /// (TrackReg, TrackSubReg) = (dst, subIdx).
992 /// Subsequence calls will return false.
993 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
995 unsigned &TrackSubReg) override {
996 // If we already get the only source we can rewrite, return false.
997 if (CurrentSrcIdx == 2)
999 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
1001 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
1002 SrcReg = MOInsertedReg.getReg();
1003 SrcSubReg = MOInsertedReg.getSubReg();
1004 const MachineOperand &MODef = CopyLike.getOperand(0);
1006 // We want to track something that is compatible with the
1007 // partial definition.
1008 TrackReg = MODef.getReg();
1009 if (MODef.getSubReg())
1010 // Bail if we have to compose sub-register indices.
1012 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1015 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1016 if (CurrentSrcIdx != 2)
1018 // We are rewriting the inserted reg.
1019 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1021 MO.setSubReg(NewSubReg);
1026 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1027 class ExtractSubregRewriter : public CopyRewriter {
1028 const TargetInstrInfo &TII;
1031 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1032 : CopyRewriter(MI), TII(TII) {
1033 assert(MI.isExtractSubreg() && "Invalid instruction");
1036 /// \brief See CopyRewriter::getNextRewritableSource.
1037 /// Here CopyLike has the following form:
1038 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1039 /// There is only one rewritable source: Src.subIdx,
1040 /// which defines dst.dstSubIdx.
1041 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1043 unsigned &TrackSubReg) override {
1044 // If we already get the only source we can rewrite, return false.
1045 if (CurrentSrcIdx == 1)
1047 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1049 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1050 SrcReg = MOExtractedReg.getReg();
1051 // If we have to compose sub-register indices, bail out.
1052 if (MOExtractedReg.getSubReg())
1055 SrcSubReg = CopyLike.getOperand(2).getImm();
1057 // We want to track something that is compatible with the definition.
1058 const MachineOperand &MODef = CopyLike.getOperand(0);
1059 TrackReg = MODef.getReg();
1060 TrackSubReg = MODef.getSubReg();
1064 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1065 // The only source we can rewrite is the input register.
1066 if (CurrentSrcIdx != 1)
1069 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1071 // If we find a source that does not require to extract something,
1072 // rewrite the operation with a copy.
1074 // Move the current index to an invalid position.
1075 // We do not want another call to this method to be able
1076 // to do any change.
1078 // Rewrite the operation as a COPY.
1079 // Get rid of the sub-register index.
1080 CopyLike.RemoveOperand(2);
1081 // Morph the operation into a COPY.
1082 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1085 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1090 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1091 class RegSequenceRewriter : public CopyRewriter {
1093 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1094 assert(MI.isRegSequence() && "Invalid instruction");
1097 /// \brief See CopyRewriter::getNextRewritableSource.
1098 /// Here CopyLike has the following form:
1099 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1100 /// Each call will return a different source, walking all the available
1103 /// The first call returns:
1104 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1105 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1107 /// The second call returns:
1108 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1109 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1111 /// And so on, until all the sources have been traversed, then
1112 /// it returns false.
1113 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1115 unsigned &TrackSubReg) override {
1116 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1118 // If this is the first call, move to the first argument.
1119 if (CurrentSrcIdx == 0) {
1122 // Otherwise, move to the next argument and check that it is valid.
1124 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1127 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1128 SrcReg = MOInsertedReg.getReg();
1129 // If we have to compose sub-register indices, bail out.
1130 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1133 // We want to track something that is compatible with the related
1134 // partial definition.
1135 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1137 const MachineOperand &MODef = CopyLike.getOperand(0);
1138 TrackReg = MODef.getReg();
1139 // If we have to compose sub-registers, bail.
1140 return MODef.getSubReg() == 0;
1143 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1144 // We cannot rewrite out of bound operands.
1145 // Moreover, rewritable sources are at odd positions.
1146 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1149 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1151 MO.setSubReg(NewSubReg);
1157 /// \brief Get the appropriated CopyRewriter for \p MI.
1158 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1159 /// if no rewriter works for \p MI.
1160 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1161 const TargetInstrInfo &TII,
1162 MachineRegisterInfo &MRI) {
1163 // Handle uncoalescable copy-like instructions.
1164 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1165 MI.isExtractSubregLike()))
1166 return new UncoalescableRewriter(MI, TII, MRI);
1168 switch (MI.getOpcode()) {
1171 case TargetOpcode::COPY:
1172 return new CopyRewriter(MI);
1173 case TargetOpcode::INSERT_SUBREG:
1174 return new InsertSubregRewriter(MI);
1175 case TargetOpcode::EXTRACT_SUBREG:
1176 return new ExtractSubregRewriter(MI, TII);
1177 case TargetOpcode::REG_SEQUENCE:
1178 return new RegSequenceRewriter(MI);
1180 llvm_unreachable(nullptr);
1183 /// \brief Optimize generic copy instructions to avoid cross
1184 /// register bank copy. The optimization looks through a chain of
1185 /// copies and tries to find a source that has a compatible register
1187 /// Two register classes are considered to be compatible if they share
1188 /// the same register bank.
1189 /// New copies issued by this optimization are register allocator
1190 /// friendly. This optimization does not remove any copy as it may
1191 /// overconstrain the register allocator, but replaces some operands
1193 /// \pre isCoalescableCopy(*MI) is true.
1194 /// \return True, when \p MI has been rewritten. False otherwise.
1195 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1196 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1197 assert(MI->getDesc().getNumDefs() == 1 &&
1198 "Coalescer can understand multiple defs?!");
1199 const MachineOperand &MODef = MI->getOperand(0);
1200 // Do not rewrite physical definitions.
1201 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1204 bool Changed = false;
1205 // Get the right rewriter for the current copy.
1206 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1207 // If none exists, bail out.
1210 // Rewrite each rewritable source.
1211 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1212 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1214 // Keep track of PHI nodes and its incoming edges when looking for sources.
1215 RewriteMapTy RewriteMap;
1216 // Try to find a more suitable source. If we failed to do so, or get the
1217 // actual source, move to the next source.
1218 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1221 // Get the new source to rewrite. TODO: Only enable handling of multiple
1222 // sources (PHIs) once we have a motivating example and testcases for it.
1223 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1224 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1225 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1226 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1230 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1231 // We may have extended the live-range of NewSrc, account for that.
1232 MRI->clearKillFlags(NewSrc.Reg);
1236 // TODO: We could have a clean-up method to tidy the instruction.
1237 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1239 // Currently we haven't seen motivating example for that and we
1240 // want to avoid untested code.
1241 NumRewrittenCopies += Changed;
1245 /// \brief Optimize copy-like instructions to create
1246 /// register coalescer friendly instruction.
1247 /// The optimization tries to kill-off the \p MI by looking
1248 /// through a chain of copies to find a source that has a compatible
1250 /// If such a source is found, it replace \p MI by a generic COPY
1252 /// \pre isUncoalescableCopy(*MI) is true.
1253 /// \return True, when \p MI has been optimized. In that case, \p MI has
1254 /// been removed from its parent.
1255 /// All COPY instructions created, are inserted in \p LocalMIs.
1256 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1257 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1258 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1260 // Check if we can rewrite all the values defined by this instruction.
1261 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1262 // Get the right rewriter for the current copy.
1263 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1264 // If none exists, bail out.
1268 // Rewrite each rewritable source by generating new COPYs. This works
1269 // differently from optimizeCoalescableCopy since it first makes sure that all
1270 // definitions can be rewritten.
1271 RewriteMapTy RewriteMap;
1272 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1273 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1275 // If a physical register is here, this is probably for a good reason.
1276 // Do not rewrite that.
1277 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1280 // If we do not know how to rewrite this definition, there is no point
1281 // in trying to kill this instruction.
1282 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1283 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1286 RewritePairs.push_back(Def);
1289 // The change is possible for all defs, do it.
1290 for (const auto &Def : RewritePairs) {
1291 // Rewrite the "copy" in a way the register coalescer understands.
1292 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1293 assert(NewCopy && "Should be able to always generate a new copy");
1294 LocalMIs.insert(NewCopy);
1298 MI->eraseFromParent();
1299 ++NumUncoalescableCopies;
1303 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
1304 /// instruction. We only fold loads to virtual registers and the virtual
1305 /// register defined has a single use.
1306 bool PeepholeOptimizer::isLoadFoldable(
1308 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1309 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1311 const MCInstrDesc &MCID = MI->getDesc();
1312 if (MCID.getNumDefs() != 1)
1315 unsigned Reg = MI->getOperand(0).getReg();
1316 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1317 // loads. It should be checked when processing uses of the load, since
1318 // uses can be removed during peephole.
1319 if (!MI->getOperand(0).getSubReg() &&
1320 TargetRegisterInfo::isVirtualRegister(Reg) &&
1321 MRI->hasOneNonDBGUse(Reg)) {
1322 FoldAsLoadDefCandidates.insert(Reg);
1328 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1329 SmallSet<unsigned, 4> &ImmDefRegs,
1330 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1331 const MCInstrDesc &MCID = MI->getDesc();
1332 if (!MI->isMoveImmediate())
1334 if (MCID.getNumDefs() != 1)
1336 unsigned Reg = MI->getOperand(0).getReg();
1337 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1338 ImmDefMIs.insert(std::make_pair(Reg, MI));
1339 ImmDefRegs.insert(Reg);
1346 /// foldImmediate - Try folding register operands that are defined by move
1347 /// immediate instructions, i.e. a trivial constant folding optimization, if
1348 /// and only if the def and use are in the same BB.
1349 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1350 SmallSet<unsigned, 4> &ImmDefRegs,
1351 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1352 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1353 MachineOperand &MO = MI->getOperand(i);
1354 if (!MO.isReg() || MO.isDef())
1356 unsigned Reg = MO.getReg();
1357 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1359 if (ImmDefRegs.count(Reg) == 0)
1361 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1362 assert(II != ImmDefMIs.end());
1363 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1371 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1372 if (skipOptnoneFunction(*MF.getFunction()))
1375 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1376 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1378 if (DisablePeephole)
1381 TII = MF.getSubtarget().getInstrInfo();
1382 TRI = MF.getSubtarget().getRegisterInfo();
1383 MRI = &MF.getRegInfo();
1384 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1386 bool Changed = false;
1388 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1389 MachineBasicBlock *MBB = &*I;
1391 bool SeenMoveImm = false;
1393 // During this forward scan, at some point it needs to answer the question
1394 // "given a pointer to an MI in the current BB, is it located before or
1395 // after the current instruction".
1396 // To perform this, the following set keeps track of the MIs already seen
1397 // during the scan, if a MI is not in the set, it is assumed to be located
1398 // after. Newly created MIs have to be inserted in the set as well.
1399 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1400 SmallSet<unsigned, 4> ImmDefRegs;
1401 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1402 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1404 for (MachineBasicBlock::iterator
1405 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1406 MachineInstr *MI = &*MII;
1407 // We may be erasing MI below, increment MII now.
1409 LocalMIs.insert(MI);
1411 // Skip debug values. They should not affect this peephole optimization.
1412 if (MI->isDebugValue())
1415 // If we run into an instruction we can't fold across, discard
1416 // the load candidates.
1417 if (MI->isLoadFoldBarrier())
1418 FoldAsLoadDefCandidates.clear();
1420 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1421 MI->isKill() || MI->isInlineAsm() ||
1422 MI->hasUnmodeledSideEffects())
1425 if ((isUncoalescableCopy(*MI) &&
1426 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1427 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1428 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1435 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1440 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1441 // MI is just rewritten.
1446 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1449 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1450 // optimizeExtInstr might have created new instructions after MI
1451 // and before the already incremented MII. Adjust MII so that the
1452 // next iteration sees the new instructions.
1456 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1459 // Check whether MI is a load candidate for folding into a later
1460 // instruction. If MI is not a candidate, check whether we can fold an
1461 // earlier load into MI.
1462 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1463 !FoldAsLoadDefCandidates.empty()) {
1464 const MCInstrDesc &MIDesc = MI->getDesc();
1465 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1467 const MachineOperand &MOp = MI->getOperand(i);
1470 unsigned FoldAsLoadDefReg = MOp.getReg();
1471 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1472 // We need to fold load after optimizeCmpInstr, since
1473 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1474 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1475 // we need it for markUsesInDebugValueAsUndef().
1476 unsigned FoldedReg = FoldAsLoadDefReg;
1477 MachineInstr *DefMI = nullptr;
1478 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1482 // Update LocalMIs since we replaced MI with FoldMI and deleted
1484 DEBUG(dbgs() << "Replacing: " << *MI);
1485 DEBUG(dbgs() << " With: " << *FoldMI);
1487 LocalMIs.erase(DefMI);
1488 LocalMIs.insert(FoldMI);
1489 MI->eraseFromParent();
1490 DefMI->eraseFromParent();
1491 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1492 FoldAsLoadDefCandidates.erase(FoldedReg);
1494 // MI is replaced with FoldMI.
1507 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1508 assert(Def->isCopy() && "Invalid definition");
1509 // Copy instruction are supposed to be: Def = Src.
1510 // If someone breaks this assumption, bad things will happen everywhere.
1511 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1513 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1514 // If we look for a different subreg, it means we want a subreg of src.
1515 // Bails as we do not support composing subregs yet.
1516 return ValueTrackerResult();
1517 // Otherwise, we want the whole source.
1518 const MachineOperand &Src = Def->getOperand(1);
1519 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1522 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1523 assert(Def->isBitcast() && "Invalid definition");
1525 // Bail if there are effects that a plain copy will not expose.
1526 if (Def->hasUnmodeledSideEffects())
1527 return ValueTrackerResult();
1529 // Bitcasts with more than one def are not supported.
1530 if (Def->getDesc().getNumDefs() != 1)
1531 return ValueTrackerResult();
1532 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1533 // If we look for a different subreg, it means we want a subreg of the src.
1534 // Bails as we do not support composing subregs yet.
1535 return ValueTrackerResult();
1537 unsigned SrcIdx = Def->getNumOperands();
1538 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1540 const MachineOperand &MO = Def->getOperand(OpIdx);
1541 if (!MO.isReg() || !MO.getReg())
1543 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1544 if (SrcIdx != EndOpIdx)
1545 // Multiple sources?
1546 return ValueTrackerResult();
1549 const MachineOperand &Src = Def->getOperand(SrcIdx);
1550 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1553 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1554 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1555 "Invalid definition");
1557 if (Def->getOperand(DefIdx).getSubReg())
1558 // If we are composing subregs, bail out.
1559 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1560 // This should almost never happen as the SSA property is tracked at
1561 // the register level (as opposed to the subreg level).
1565 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1566 // Def. Thus, it must not be generated.
1567 // However, some code could theoretically generates a single
1568 // Def.sub0 (i.e, not defining the other subregs) and we would
1570 // If we can ascertain (or force) that this never happens, we could
1571 // turn that into an assertion.
1572 return ValueTrackerResult();
1575 // We could handle the REG_SEQUENCE here, but we do not want to
1576 // duplicate the code from the generic TII.
1577 return ValueTrackerResult();
1579 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1580 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1581 return ValueTrackerResult();
1583 // We are looking at:
1584 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1585 // Check if one of the operand defines the subreg we are interested in.
1586 for (auto &RegSeqInput : RegSeqInputRegs) {
1587 if (RegSeqInput.SubIdx == DefSubReg) {
1588 if (RegSeqInput.SubReg)
1589 // Bail if we have to compose sub registers.
1590 return ValueTrackerResult();
1592 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1596 // If the subreg we are tracking is super-defined by another subreg,
1597 // we could follow this value. However, this would require to compose
1598 // the subreg and we do not do that for now.
1599 return ValueTrackerResult();
1602 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1603 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1604 "Invalid definition");
1606 if (Def->getOperand(DefIdx).getSubReg())
1607 // If we are composing subreg, bail out.
1608 // Same remark as getNextSourceFromRegSequence.
1609 // I.e., this may be turned into an assert.
1610 return ValueTrackerResult();
1613 // We could handle the REG_SEQUENCE here, but we do not want to
1614 // duplicate the code from the generic TII.
1615 return ValueTrackerResult();
1617 TargetInstrInfo::RegSubRegPair BaseReg;
1618 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1619 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1620 return ValueTrackerResult();
1622 // We are looking at:
1623 // Def = INSERT_SUBREG v0, v1, sub1
1624 // There are two cases:
1625 // 1. DefSubReg == sub1, get v1.
1626 // 2. DefSubReg != sub1, the value may be available through v0.
1628 // #1 Check if the inserted register matches the required sub index.
1629 if (InsertedReg.SubIdx == DefSubReg) {
1630 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1632 // #2 Otherwise, if the sub register we are looking for is not partial
1633 // defined by the inserted element, we can look through the main
1635 const MachineOperand &MODef = Def->getOperand(DefIdx);
1636 // If the result register (Def) and the base register (v0) do not
1637 // have the same register class or if we have to compose
1638 // subregisters, bail out.
1639 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1641 return ValueTrackerResult();
1643 // Get the TRI and check if the inserted sub-register overlaps with the
1644 // sub-register we are tracking.
1645 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1647 (TRI->getSubRegIndexLaneMask(DefSubReg) &
1648 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1649 return ValueTrackerResult();
1650 // At this point, the value is available in v0 via the same subreg
1652 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1655 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1656 assert((Def->isExtractSubreg() ||
1657 Def->isExtractSubregLike()) && "Invalid definition");
1658 // We are looking at:
1659 // Def = EXTRACT_SUBREG v0, sub0
1661 // Bail if we have to compose sub registers.
1662 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1664 return ValueTrackerResult();
1667 // We could handle the EXTRACT_SUBREG here, but we do not want to
1668 // duplicate the code from the generic TII.
1669 return ValueTrackerResult();
1671 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1672 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1673 return ValueTrackerResult();
1675 // Bail if we have to compose sub registers.
1676 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1677 if (ExtractSubregInputReg.SubReg)
1678 return ValueTrackerResult();
1679 // Otherwise, the value is available in the v0.sub0.
1680 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
1683 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
1684 assert(Def->isSubregToReg() && "Invalid definition");
1685 // We are looking at:
1686 // Def = SUBREG_TO_REG Imm, v0, sub0
1688 // Bail if we have to compose sub registers.
1689 // If DefSubReg != sub0, we would have to check that all the bits
1690 // we track are included in sub0 and if yes, we would have to
1691 // determine the right subreg in v0.
1692 if (DefSubReg != Def->getOperand(3).getImm())
1693 return ValueTrackerResult();
1694 // Bail if we have to compose sub registers.
1695 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1696 if (Def->getOperand(2).getSubReg())
1697 return ValueTrackerResult();
1699 return ValueTrackerResult(Def->getOperand(2).getReg(),
1700 Def->getOperand(3).getImm());
1703 /// \brief Explore each PHI incoming operand and return its sources
1704 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1705 assert(Def->isPHI() && "Invalid definition");
1706 ValueTrackerResult Res;
1708 // If we look for a different subreg, bail as we do not support composing
1710 if (Def->getOperand(0).getSubReg() != DefSubReg)
1711 return ValueTrackerResult();
1713 // Return all register sources for PHI instructions.
1714 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1715 auto &MO = Def->getOperand(i);
1716 assert(MO.isReg() && "Invalid PHI instruction");
1717 Res.addSource(MO.getReg(), MO.getSubReg());
1723 ValueTrackerResult ValueTracker::getNextSourceImpl() {
1724 assert(Def && "This method needs a valid definition");
1727 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1728 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1730 return getNextSourceFromCopy();
1731 if (Def->isBitcast())
1732 return getNextSourceFromBitcast();
1733 // All the remaining cases involve "complex" instructions.
1734 // Bail if we did not ask for the advanced tracking.
1735 if (!UseAdvancedTracking)
1736 return ValueTrackerResult();
1737 if (Def->isRegSequence() || Def->isRegSequenceLike())
1738 return getNextSourceFromRegSequence();
1739 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1740 return getNextSourceFromInsertSubreg();
1741 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1742 return getNextSourceFromExtractSubreg();
1743 if (Def->isSubregToReg())
1744 return getNextSourceFromSubregToReg();
1746 return getNextSourceFromPHI();
1747 return ValueTrackerResult();
1750 ValueTrackerResult ValueTracker::getNextSource() {
1751 // If we reach a point where we cannot move up in the use-def chain,
1752 // there is nothing we can get.
1754 return ValueTrackerResult();
1756 ValueTrackerResult Res = getNextSourceImpl();
1757 if (Res.isValid()) {
1758 // Update definition, definition index, and subregister for the
1759 // next call of getNextSource.
1760 // Update the current register.
1761 bool OneRegSrc = Res.getNumSources() == 1;
1763 Reg = Res.getSrcReg(0);
1764 // Update the result before moving up in the use-def chain
1765 // with the instruction containing the last found sources.
1768 // If we can still move up in the use-def chain, move to the next
1770 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
1771 Def = MRI.getVRegDef(Reg);
1772 DefIdx = MRI.def_begin(Reg).getOperandNo();
1773 DefSubReg = Res.getSrcSubReg(0);
1777 // If we end up here, this means we will not be able to find another source
1778 // for the next iteration. Make sure any new call to getNextSource bails out
1779 // early by cutting the use-def chain.