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 optimizeCoalescableCopy(MachineInstr *MI);
153 bool optimizeUncoalescableCopy(MachineInstr *MI,
154 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
155 bool findNextSource(unsigned Reg, unsigned SubReg,
156 RewriteMapTy &RewriteMap);
157 bool isMoveImmediate(MachineInstr *MI,
158 SmallSet<unsigned, 4> &ImmDefRegs,
159 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
160 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
161 SmallSet<unsigned, 4> &ImmDefRegs,
162 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
164 /// \brief If copy instruction \p MI is a virtual register copy, track it in
165 /// the set \p CopiedFromRegs and \p CopyMIs. If this virtual register was
166 /// previously seen as a copy, replace the uses of this copy with the
167 /// previously seen copy's destination register.
168 bool foldRedundantCopy(MachineInstr *MI,
169 SmallSet<unsigned, 4> &CopiedFromRegs,
170 DenseMap<unsigned, MachineInstr*> &CopyMIs);
172 bool isLoadFoldable(MachineInstr *MI,
173 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
175 /// \brief Check whether \p MI is understood by the register coalescer
176 /// but may require some rewriting.
177 bool isCoalescableCopy(const MachineInstr &MI) {
178 // SubregToRegs are not interesting, because they are already register
179 // coalescer friendly.
180 return MI.isCopy() || (!DisableAdvCopyOpt &&
181 (MI.isRegSequence() || MI.isInsertSubreg() ||
182 MI.isExtractSubreg()));
185 /// \brief Check whether \p MI is a copy like instruction that is
186 /// not recognized by the register coalescer.
187 bool isUncoalescableCopy(const MachineInstr &MI) {
188 return MI.isBitcast() ||
189 (!DisableAdvCopyOpt &&
190 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
191 MI.isExtractSubregLike()));
195 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
196 /// returned sources for a given search and the instructions where the sources
197 /// were tracked from.
198 class ValueTrackerResult {
200 /// Track all sources found by one ValueTracker query.
201 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
203 /// Instruction using the sources in 'RegSrcs'.
204 const MachineInstr *Inst;
207 ValueTrackerResult() : Inst(nullptr) {}
208 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
209 addSource(Reg, SubReg);
212 bool isValid() const { return getNumSources() > 0; }
214 void setInst(const MachineInstr *I) { Inst = I; }
215 const MachineInstr *getInst() const { return Inst; }
222 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
223 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
226 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
227 assert(Idx < getNumSources() && "Reg pair source out of index");
228 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
231 int getNumSources() const { return RegSrcs.size(); }
233 unsigned getSrcReg(int Idx) const {
234 assert(Idx < getNumSources() && "Reg source out of index");
235 return RegSrcs[Idx].Reg;
238 unsigned getSrcSubReg(int Idx) const {
239 assert(Idx < getNumSources() && "SubReg source out of index");
240 return RegSrcs[Idx].SubReg;
243 bool operator==(const ValueTrackerResult &Other) {
244 if (Other.getInst() != getInst())
247 if (Other.getNumSources() != getNumSources())
250 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
251 if (Other.getSrcReg(i) != getSrcReg(i) ||
252 Other.getSrcSubReg(i) != getSrcSubReg(i))
258 /// \brief Helper class to track the possible sources of a value defined by
259 /// a (chain of) copy related instructions.
260 /// Given a definition (instruction and definition index), this class
261 /// follows the use-def chain to find successive suitable sources.
262 /// The given source can be used to rewrite the definition into
265 /// For instance, let us consider the following snippet:
267 /// v2 = INSERT_SUBREG v1, v0, sub0
268 /// def = COPY v2.sub0
270 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
271 /// suitable sources:
273 /// Then, def can be rewritten into def = COPY v0.
276 /// The current point into the use-def chain.
277 const MachineInstr *Def;
278 /// The index of the definition in Def.
280 /// The sub register index of the definition.
282 /// The register where the value can be found.
284 /// Specifiy whether or not the value tracking looks through
285 /// complex instructions. When this is false, the value tracker
286 /// bails on everything that is not a copy or a bitcast.
288 /// Note: This could have been implemented as a specialized version of
289 /// the ValueTracker class but that would have complicated the code of
290 /// the users of this class.
291 bool UseAdvancedTracking;
292 /// MachineRegisterInfo used to perform tracking.
293 const MachineRegisterInfo &MRI;
294 /// Optional TargetInstrInfo used to perform some complex
296 const TargetInstrInfo *TII;
298 /// \brief Dispatcher to the right underlying implementation of
300 ValueTrackerResult getNextSourceImpl();
301 /// \brief Specialized version of getNextSource for Copy instructions.
302 ValueTrackerResult getNextSourceFromCopy();
303 /// \brief Specialized version of getNextSource for Bitcast instructions.
304 ValueTrackerResult getNextSourceFromBitcast();
305 /// \brief Specialized version of getNextSource for RegSequence
307 ValueTrackerResult getNextSourceFromRegSequence();
308 /// \brief Specialized version of getNextSource for InsertSubreg
310 ValueTrackerResult getNextSourceFromInsertSubreg();
311 /// \brief Specialized version of getNextSource for ExtractSubreg
313 ValueTrackerResult getNextSourceFromExtractSubreg();
314 /// \brief Specialized version of getNextSource for SubregToReg
316 ValueTrackerResult getNextSourceFromSubregToReg();
317 /// \brief Specialized version of getNextSource for PHI instructions.
318 ValueTrackerResult getNextSourceFromPHI();
321 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
322 /// \p DefSubReg represents the sub register index the value tracker will
323 /// track. It does not need to match the sub register index used in the
324 /// definition of \p Reg.
325 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
326 /// through complex instructions. By default (false), it handles only copy
327 /// and bitcast instructions.
328 /// If \p Reg is a physical register, a value tracker constructed with
329 /// this constructor will not find any alternative source.
330 /// Indeed, when \p Reg is a physical register that constructor does not
331 /// know which definition of \p Reg it should track.
332 /// Use the next constructor to track a physical register.
333 ValueTracker(unsigned Reg, unsigned DefSubReg,
334 const MachineRegisterInfo &MRI,
335 bool UseAdvancedTracking = false,
336 const TargetInstrInfo *TII = nullptr)
337 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
338 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
339 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
340 Def = MRI.getVRegDef(Reg);
341 DefIdx = MRI.def_begin(Reg).getOperandNo();
345 /// \brief Create a ValueTracker instance for the value defined by
346 /// the pair \p MI, \p DefIdx.
347 /// Unlike the other constructor, the value tracker produced by this one
348 /// may be able to find a new source when the definition is a physical
350 /// This could be useful to rewrite target specific instructions into
351 /// generic copy instructions.
352 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
353 const MachineRegisterInfo &MRI,
354 bool UseAdvancedTracking = false,
355 const TargetInstrInfo *TII = nullptr)
356 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
357 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
358 assert(DefIdx < Def->getDesc().getNumDefs() &&
359 Def->getOperand(DefIdx).isReg() && "Invalid definition");
360 Reg = Def->getOperand(DefIdx).getReg();
363 /// \brief Following the use-def chain, get the next available source
364 /// for the tracked value.
365 /// \return A ValueTrackerResult containing a set of registers
366 /// and sub registers with tracked values. A ValueTrackerResult with
367 /// an empty set of registers means no source was found.
368 ValueTrackerResult getNextSource();
370 /// \brief Get the last register where the initial value can be found.
371 /// Initially this is the register of the definition.
372 /// Then, after each successful call to getNextSource, this is the
373 /// register of the last source.
374 unsigned getReg() const { return Reg; }
378 char PeepholeOptimizer::ID = 0;
379 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
380 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
381 "Peephole Optimizations", false, false)
382 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
383 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
384 "Peephole Optimizations", false, false)
386 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
387 /// a single register and writes a single register and it does not modify the
388 /// source, and if the source value is preserved as a sub-register of the
389 /// result, then replace all reachable uses of the source with the subreg of the
392 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
393 /// the code. Since this code does not currently share EXTRACTs, just ignore all
395 bool PeepholeOptimizer::
396 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
397 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
398 unsigned SrcReg, DstReg, SubIdx;
399 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
402 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
403 TargetRegisterInfo::isPhysicalRegister(SrcReg))
406 if (MRI->hasOneNonDBGUse(SrcReg))
410 // Ensure DstReg can get a register class that actually supports
411 // sub-registers. Don't change the class until we commit.
412 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
413 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
417 // The ext instr may be operating on a sub-register of SrcReg as well.
418 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
420 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
421 // SrcReg:SubIdx should be replaced.
423 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
425 // The source has other uses. See if we can replace the other uses with use of
426 // the result of the extension.
427 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
428 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
429 ReachedBBs.insert(UI.getParent());
431 // Uses that are in the same BB of uses of the result of the instruction.
432 SmallVector<MachineOperand*, 8> Uses;
434 // Uses that the result of the instruction can reach.
435 SmallVector<MachineOperand*, 8> ExtendedUses;
437 bool ExtendLife = true;
438 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
439 MachineInstr *UseMI = UseMO.getParent();
443 if (UseMI->isPHI()) {
448 // Only accept uses of SrcReg:SubIdx.
449 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
452 // It's an error to translate this:
454 // %reg1025 = <sext> %reg1024
456 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
460 // %reg1025 = <sext> %reg1024
462 // %reg1027 = COPY %reg1025:4
463 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
465 // The problem here is that SUBREG_TO_REG is there to assert that an
466 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
467 // the COPY here, it will give us the value after the <sext>, not the
468 // original value of %reg1024 before <sext>.
469 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
472 MachineBasicBlock *UseMBB = UseMI->getParent();
474 // Local uses that come after the extension.
475 if (!LocalMIs.count(UseMI))
476 Uses.push_back(&UseMO);
477 } else if (ReachedBBs.count(UseMBB)) {
478 // Non-local uses where the result of the extension is used. Always
479 // replace these unless it's a PHI.
480 Uses.push_back(&UseMO);
481 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
482 // We may want to extend the live range of the extension result in order
483 // to replace these uses.
484 ExtendedUses.push_back(&UseMO);
486 // Both will be live out of the def MBB anyway. Don't extend live range of
487 // the extension result.
493 if (ExtendLife && !ExtendedUses.empty())
494 // Extend the liveness of the extension result.
495 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
497 // Now replace all uses.
498 bool Changed = false;
500 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
502 // Look for PHI uses of the extended result, we don't want to extend the
503 // liveness of a PHI input. It breaks all kinds of assumptions down
504 // stream. A PHI use is expected to be the kill of its source values.
505 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
507 PHIBBs.insert(UI.getParent());
509 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
510 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
511 MachineOperand *UseMO = Uses[i];
512 MachineInstr *UseMI = UseMO->getParent();
513 MachineBasicBlock *UseMBB = UseMI->getParent();
514 if (PHIBBs.count(UseMBB))
517 // About to add uses of DstReg, clear DstReg's kill flags.
519 MRI->clearKillFlags(DstReg);
520 MRI->constrainRegClass(DstReg, DstRC);
523 unsigned NewVR = MRI->createVirtualRegister(RC);
524 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
525 TII->get(TargetOpcode::COPY), NewVR)
526 .addReg(DstReg, 0, SubIdx);
527 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
529 Copy->getOperand(0).setSubReg(SubIdx);
530 Copy->getOperand(0).setIsUndef();
532 UseMO->setReg(NewVR);
541 /// optimizeCmpInstr - If the instruction is a compare and the previous
542 /// instruction it's comparing against all ready sets (or could be modified to
543 /// set) the same flag as the compare, then we can remove the comparison and use
544 /// the flag from the previous instruction.
545 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
546 MachineBasicBlock *MBB) {
547 // If this instruction is a comparison against zero and isn't comparing a
548 // physical register, we can try to optimize it.
549 unsigned SrcReg, SrcReg2;
550 int CmpMask, CmpValue;
551 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
552 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
553 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
556 // Attempt to optimize the comparison instruction.
557 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
565 /// Optimize a select instruction.
566 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
567 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
569 unsigned FalseOp = 0;
570 bool Optimizable = false;
571 SmallVector<MachineOperand, 4> Cond;
572 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
576 if (!TII->optimizeSelect(MI, LocalMIs))
578 MI->eraseFromParent();
583 /// \brief Check if a simpler conditional branch can be
585 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
586 return TII->optimizeCondBranch(MI);
589 /// \brief Try to find the next source that share the same register file
590 /// for the value defined by \p Reg and \p SubReg.
591 /// When true is returned, the \p RewriteMap can be used by the client to
592 /// retrieve all Def -> Use along the way up to the next source. Any found
593 /// Use that is not itself a key for another entry, is the next source to
594 /// use. During the search for the next source, multiple sources can be found
595 /// given multiple incoming sources of a PHI instruction. In this case, we
596 /// look in each PHI source for the next source; all found next sources must
597 /// share the same register file as \p Reg and \p SubReg. The client should
598 /// then be capable to rewrite all intermediate PHIs to get the next source.
599 /// \return False if no alternative sources are available. True otherwise.
600 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
601 RewriteMapTy &RewriteMap) {
602 // Do not try to find a new source for a physical register.
603 // So far we do not have any motivating example for doing that.
604 // Thus, instead of maintaining untested code, we will revisit that if
605 // that changes at some point.
606 if (TargetRegisterInfo::isPhysicalRegister(Reg))
608 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
610 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
611 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
612 SrcToLook.push_back(CurSrcPair);
614 unsigned PHICount = 0;
615 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
616 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
617 // As explained above, do not handle physical registers
618 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
622 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
623 !DisableAdvCopyOpt, TII);
624 ValueTrackerResult Res;
625 bool ShouldRewrite = false;
628 // Follow the chain of copies until we reach the top of the use-def chain
629 // or find a more suitable source.
630 Res = ValTracker.getNextSource();
634 // Insert the Def -> Use entry for the recently found source.
635 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
636 if (CurSrcRes.isValid()) {
637 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
638 // An existent entry with multiple sources is a PHI cycle we must avoid.
639 // Otherwise it's an entry with a valid next source we already found.
640 if (CurSrcRes.getNumSources() > 1) {
641 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
646 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
648 // ValueTrackerResult usually have one source unless it's the result from
649 // a PHI instruction. Add the found PHI edges to be looked up further.
650 unsigned NumSrcs = Res.getNumSources();
653 for (unsigned i = 0; i < NumSrcs; ++i)
654 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
655 Res.getSrcReg(i), Res.getSrcSubReg(i)));
659 CurSrcPair.Reg = Res.getSrcReg(0);
660 CurSrcPair.SubReg = Res.getSrcSubReg(0);
661 // Do not extend the live-ranges of physical registers as they add
662 // constraints to the register allocator. Moreover, if we want to extend
663 // the live-range of a physical register, unlike SSA virtual register,
664 // we will have to check that they aren't redefine before the related use.
665 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
668 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
669 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
671 } while (!ShouldRewrite);
673 // Continue looking for new sources...
677 // Do not continue searching for a new source if the there's at least
678 // one use-def which cannot be rewritten.
683 if (PHICount >= RewritePHILimit) {
684 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
688 // If we did not find a more suitable source, there is nothing to optimize.
689 if (CurSrcPair.Reg == Reg)
695 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
696 /// guaranteed to have the same register class. This is necessary whenever we
697 /// successfully traverse a PHI instruction and find suitable sources coming
698 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
699 /// suitable to be used in a new COPY instruction.
700 static MachineInstr *
701 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
702 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
703 MachineInstr *OrigPHI) {
704 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
706 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
707 unsigned NewVR = MRI->createVirtualRegister(NewRC);
708 MachineBasicBlock *MBB = OrigPHI->getParent();
709 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
710 TII->get(TargetOpcode::PHI), NewVR);
712 unsigned MBBOpIdx = 2;
713 for (auto RegPair : SrcRegs) {
714 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
715 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
716 // Since we're extended the lifetime of RegPair.Reg, clear the
717 // kill flags to account for that and make RegPair.Reg reaches
719 MRI->clearKillFlags(RegPair.Reg);
727 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
730 /// The copy-like instruction.
731 MachineInstr &CopyLike;
732 /// The index of the source being rewritten.
733 unsigned CurrentSrcIdx;
736 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
738 virtual ~CopyRewriter() {}
740 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
741 /// the related value that it affects (TrackReg, TrackSubReg).
742 /// A source is considered rewritable if its register class and the
743 /// register class of the related TrackReg may not be register
744 /// coalescer friendly. In other words, given a copy-like instruction
745 /// not all the arguments may be returned at rewritable source, since
746 /// some arguments are none to be register coalescer friendly.
748 /// Each call of this method moves the current source to the next
749 /// rewritable source.
750 /// For instance, let CopyLike be the instruction to rewrite.
751 /// CopyLike has one definition and one source:
752 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
754 /// The first call will give the first rewritable source, i.e.,
755 /// the only source this instruction has:
756 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
757 /// This source defines the whole definition, i.e.,
758 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
760 /// The second and subsequent calls will return false, as there is only one
761 /// rewritable source.
763 /// \return True if a rewritable source has been found, false otherwise.
764 /// The output arguments are valid if and only if true is returned.
765 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
767 unsigned &TrackSubReg) {
768 // If CurrentSrcIdx == 1, this means this function has already been called
769 // once. CopyLike has one definition and one argument, thus, there is
770 // nothing else to rewrite.
771 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
773 // This is the first call to getNextRewritableSource.
774 // Move the CurrentSrcIdx to remember that we made that call.
776 // The rewritable source is the argument.
777 const MachineOperand &MOSrc = CopyLike.getOperand(1);
778 SrcReg = MOSrc.getReg();
779 SrcSubReg = MOSrc.getSubReg();
780 // What we track are the alternative sources of the definition.
781 const MachineOperand &MODef = CopyLike.getOperand(0);
782 TrackReg = MODef.getReg();
783 TrackSubReg = MODef.getSubReg();
787 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
789 /// \return True if the rewriting was possible, false otherwise.
790 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
791 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
793 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
794 MOSrc.setReg(NewReg);
795 MOSrc.setSubReg(NewSubReg);
799 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
800 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
801 /// multiple sources for a given \p Def are found along the way, we found a
802 /// PHI instructions that needs to be rewritten.
803 /// TODO: HandleMultipleSources should be removed once we test PHI handling
804 /// with coalescable copies.
805 TargetInstrInfo::RegSubRegPair
806 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
807 TargetInstrInfo::RegSubRegPair Def,
808 PeepholeOptimizer::RewriteMapTy &RewriteMap,
809 bool HandleMultipleSources = true) {
811 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
813 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
814 // If there are no entries on the map, LookupSrc is the new source.
818 // There's only one source for this definition, keep searching...
819 unsigned NumSrcs = Res.getNumSources();
821 LookupSrc.Reg = Res.getSrcReg(0);
822 LookupSrc.SubReg = Res.getSrcSubReg(0);
826 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
827 if (!HandleMultipleSources)
830 // Multiple sources, recurse into each source to find a new source
831 // for it. Then, rewrite the PHI accordingly to its new edges.
832 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
833 for (unsigned i = 0; i < NumSrcs; ++i) {
834 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
835 Res.getSrcSubReg(i));
836 NewPHISrcs.push_back(
837 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
840 // Build the new PHI node and return its def register as the new source.
841 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
842 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
843 DEBUG(dbgs() << "-- getNewSource\n");
844 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
845 DEBUG(dbgs() << " With: " << *NewPHI);
846 const MachineOperand &MODef = NewPHI->getOperand(0);
847 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
851 return TargetInstrInfo::RegSubRegPair(0, 0);
854 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
855 /// and create a new COPY instruction. More info about RewriteMap in
856 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
857 /// Uncoalescable copies, since they are copy like instructions that aren't
858 /// recognized by the register allocator.
859 virtual MachineInstr *
860 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
861 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
866 /// \brief Helper class to rewrite uncoalescable copy like instructions
867 /// into new COPY (coalescable friendly) instructions.
868 class UncoalescableRewriter : public CopyRewriter {
870 const TargetInstrInfo &TII;
871 MachineRegisterInfo &MRI;
872 /// The number of defs in the bitcast
876 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
877 MachineRegisterInfo &MRI)
878 : CopyRewriter(MI), TII(TII), MRI(MRI) {
879 NumDefs = MI.getDesc().getNumDefs();
882 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
883 /// All such sources need to be considered rewritable in order to
884 /// rewrite a uncoalescable copy-like instruction. This method return
885 /// each definition that must be checked if rewritable.
887 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
889 unsigned &TrackSubReg) override {
890 // Find the next non-dead definition and continue from there.
891 if (CurrentSrcIdx == NumDefs)
894 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
896 if (CurrentSrcIdx == NumDefs)
900 // What we track are the alternative sources of the definition.
901 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
902 TrackReg = MODef.getReg();
903 TrackSubReg = MODef.getSubReg();
909 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
910 /// and create a new COPY instruction. More info about RewriteMap in
911 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
912 /// Uncoalescable copies, since they are copy like instructions that aren't
913 /// recognized by the register allocator.
915 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
916 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
917 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
918 "We do not rewrite physical registers");
920 // Find the new source to use in the COPY rewrite.
921 TargetInstrInfo::RegSubRegPair NewSrc =
922 getNewSource(&MRI, &TII, Def, RewriteMap);
925 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
926 unsigned NewVR = MRI.createVirtualRegister(DefRC);
928 MachineInstr *NewCopy =
929 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
930 TII.get(TargetOpcode::COPY), NewVR)
931 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
933 NewCopy->getOperand(0).setSubReg(Def.SubReg);
935 NewCopy->getOperand(0).setIsUndef();
937 DEBUG(dbgs() << "-- RewriteSource\n");
938 DEBUG(dbgs() << " Replacing: " << CopyLike);
939 DEBUG(dbgs() << " With: " << *NewCopy);
940 MRI.replaceRegWith(Def.Reg, NewVR);
941 MRI.clearKillFlags(NewVR);
943 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
945 MRI.clearKillFlags(NewSrc.Reg);
951 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
952 class InsertSubregRewriter : public CopyRewriter {
954 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
955 assert(MI.isInsertSubreg() && "Invalid instruction");
958 /// \brief See CopyRewriter::getNextRewritableSource.
959 /// Here CopyLike has the following form:
960 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
961 /// Src1 has the same register class has dst, hence, there is
962 /// nothing to rewrite.
963 /// Src2.src2SubIdx, may not be register coalescer friendly.
964 /// Therefore, the first call to this method returns:
965 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
966 /// (TrackReg, TrackSubReg) = (dst, subIdx).
968 /// Subsequence calls will return false.
969 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
971 unsigned &TrackSubReg) override {
972 // If we already get the only source we can rewrite, return false.
973 if (CurrentSrcIdx == 2)
975 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
977 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
978 SrcReg = MOInsertedReg.getReg();
979 SrcSubReg = MOInsertedReg.getSubReg();
980 const MachineOperand &MODef = CopyLike.getOperand(0);
982 // We want to track something that is compatible with the
983 // partial definition.
984 TrackReg = MODef.getReg();
985 if (MODef.getSubReg())
986 // Bail if we have to compose sub-register indices.
988 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
991 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
992 if (CurrentSrcIdx != 2)
994 // We are rewriting the inserted reg.
995 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
997 MO.setSubReg(NewSubReg);
1002 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1003 class ExtractSubregRewriter : public CopyRewriter {
1004 const TargetInstrInfo &TII;
1007 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1008 : CopyRewriter(MI), TII(TII) {
1009 assert(MI.isExtractSubreg() && "Invalid instruction");
1012 /// \brief See CopyRewriter::getNextRewritableSource.
1013 /// Here CopyLike has the following form:
1014 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1015 /// There is only one rewritable source: Src.subIdx,
1016 /// which defines dst.dstSubIdx.
1017 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1019 unsigned &TrackSubReg) override {
1020 // If we already get the only source we can rewrite, return false.
1021 if (CurrentSrcIdx == 1)
1023 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1025 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1026 SrcReg = MOExtractedReg.getReg();
1027 // If we have to compose sub-register indices, bail out.
1028 if (MOExtractedReg.getSubReg())
1031 SrcSubReg = CopyLike.getOperand(2).getImm();
1033 // We want to track something that is compatible with the definition.
1034 const MachineOperand &MODef = CopyLike.getOperand(0);
1035 TrackReg = MODef.getReg();
1036 TrackSubReg = MODef.getSubReg();
1040 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1041 // The only source we can rewrite is the input register.
1042 if (CurrentSrcIdx != 1)
1045 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1047 // If we find a source that does not require to extract something,
1048 // rewrite the operation with a copy.
1050 // Move the current index to an invalid position.
1051 // We do not want another call to this method to be able
1052 // to do any change.
1054 // Rewrite the operation as a COPY.
1055 // Get rid of the sub-register index.
1056 CopyLike.RemoveOperand(2);
1057 // Morph the operation into a COPY.
1058 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1061 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1066 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1067 class RegSequenceRewriter : public CopyRewriter {
1069 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1070 assert(MI.isRegSequence() && "Invalid instruction");
1073 /// \brief See CopyRewriter::getNextRewritableSource.
1074 /// Here CopyLike has the following form:
1075 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1076 /// Each call will return a different source, walking all the available
1079 /// The first call returns:
1080 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1081 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1083 /// The second call returns:
1084 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1085 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1087 /// And so on, until all the sources have been traversed, then
1088 /// it returns false.
1089 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1091 unsigned &TrackSubReg) override {
1092 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1094 // If this is the first call, move to the first argument.
1095 if (CurrentSrcIdx == 0) {
1098 // Otherwise, move to the next argument and check that it is valid.
1100 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1103 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1104 SrcReg = MOInsertedReg.getReg();
1105 // If we have to compose sub-register indices, bail out.
1106 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1109 // We want to track something that is compatible with the related
1110 // partial definition.
1111 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1113 const MachineOperand &MODef = CopyLike.getOperand(0);
1114 TrackReg = MODef.getReg();
1115 // If we have to compose sub-registers, bail.
1116 return MODef.getSubReg() == 0;
1119 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1120 // We cannot rewrite out of bound operands.
1121 // Moreover, rewritable sources are at odd positions.
1122 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1125 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1127 MO.setSubReg(NewSubReg);
1133 /// \brief Get the appropriated CopyRewriter for \p MI.
1134 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1135 /// if no rewriter works for \p MI.
1136 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1137 const TargetInstrInfo &TII,
1138 MachineRegisterInfo &MRI) {
1139 // Handle uncoalescable copy-like instructions.
1140 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1141 MI.isExtractSubregLike()))
1142 return new UncoalescableRewriter(MI, TII, MRI);
1144 switch (MI.getOpcode()) {
1147 case TargetOpcode::COPY:
1148 return new CopyRewriter(MI);
1149 case TargetOpcode::INSERT_SUBREG:
1150 return new InsertSubregRewriter(MI);
1151 case TargetOpcode::EXTRACT_SUBREG:
1152 return new ExtractSubregRewriter(MI, TII);
1153 case TargetOpcode::REG_SEQUENCE:
1154 return new RegSequenceRewriter(MI);
1156 llvm_unreachable(nullptr);
1159 /// \brief Optimize generic copy instructions to avoid cross
1160 /// register bank copy. The optimization looks through a chain of
1161 /// copies and tries to find a source that has a compatible register
1163 /// Two register classes are considered to be compatible if they share
1164 /// the same register bank.
1165 /// New copies issued by this optimization are register allocator
1166 /// friendly. This optimization does not remove any copy as it may
1167 /// overconstrain the register allocator, but replaces some operands
1169 /// \pre isCoalescableCopy(*MI) is true.
1170 /// \return True, when \p MI has been rewritten. False otherwise.
1171 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1172 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1173 assert(MI->getDesc().getNumDefs() == 1 &&
1174 "Coalescer can understand multiple defs?!");
1175 const MachineOperand &MODef = MI->getOperand(0);
1176 // Do not rewrite physical definitions.
1177 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1180 bool Changed = false;
1181 // Get the right rewriter for the current copy.
1182 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1183 // If none exists, bail out.
1186 // Rewrite each rewritable source.
1187 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1188 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1190 // Keep track of PHI nodes and its incoming edges when looking for sources.
1191 RewriteMapTy RewriteMap;
1192 // Try to find a more suitable source. If we failed to do so, or get the
1193 // actual source, move to the next source.
1194 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1197 // Get the new source to rewrite. TODO: Only enable handling of multiple
1198 // sources (PHIs) once we have a motivating example and testcases for it.
1199 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1200 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1201 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1202 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1206 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1207 // We may have extended the live-range of NewSrc, account for that.
1208 MRI->clearKillFlags(NewSrc.Reg);
1212 // TODO: We could have a clean-up method to tidy the instruction.
1213 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1215 // Currently we haven't seen motivating example for that and we
1216 // want to avoid untested code.
1217 NumRewrittenCopies += Changed;
1221 /// \brief Optimize copy-like instructions to create
1222 /// register coalescer friendly instruction.
1223 /// The optimization tries to kill-off the \p MI by looking
1224 /// through a chain of copies to find a source that has a compatible
1226 /// If such a source is found, it replace \p MI by a generic COPY
1228 /// \pre isUncoalescableCopy(*MI) is true.
1229 /// \return True, when \p MI has been optimized. In that case, \p MI has
1230 /// been removed from its parent.
1231 /// All COPY instructions created, are inserted in \p LocalMIs.
1232 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1233 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1234 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1236 // Check if we can rewrite all the values defined by this instruction.
1237 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1238 // Get the right rewriter for the current copy.
1239 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1240 // If none exists, bail out.
1244 // Rewrite each rewritable source by generating new COPYs. This works
1245 // differently from optimizeCoalescableCopy since it first makes sure that all
1246 // definitions can be rewritten.
1247 RewriteMapTy RewriteMap;
1248 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1249 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1251 // If a physical register is here, this is probably for a good reason.
1252 // Do not rewrite that.
1253 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1256 // If we do not know how to rewrite this definition, there is no point
1257 // in trying to kill this instruction.
1258 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1259 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1262 RewritePairs.push_back(Def);
1265 // The change is possible for all defs, do it.
1266 for (const auto &Def : RewritePairs) {
1267 // Rewrite the "copy" in a way the register coalescer understands.
1268 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1269 assert(NewCopy && "Should be able to always generate a new copy");
1270 LocalMIs.insert(NewCopy);
1274 MI->eraseFromParent();
1275 ++NumUncoalescableCopies;
1279 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
1280 /// instruction. We only fold loads to virtual registers and the virtual
1281 /// register defined has a single use.
1282 bool PeepholeOptimizer::isLoadFoldable(
1284 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1285 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1287 const MCInstrDesc &MCID = MI->getDesc();
1288 if (MCID.getNumDefs() != 1)
1291 unsigned Reg = MI->getOperand(0).getReg();
1292 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1293 // loads. It should be checked when processing uses of the load, since
1294 // uses can be removed during peephole.
1295 if (!MI->getOperand(0).getSubReg() &&
1296 TargetRegisterInfo::isVirtualRegister(Reg) &&
1297 MRI->hasOneNonDBGUse(Reg)) {
1298 FoldAsLoadDefCandidates.insert(Reg);
1304 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1305 SmallSet<unsigned, 4> &ImmDefRegs,
1306 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1307 const MCInstrDesc &MCID = MI->getDesc();
1308 if (!MI->isMoveImmediate())
1310 if (MCID.getNumDefs() != 1)
1312 unsigned Reg = MI->getOperand(0).getReg();
1313 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1314 ImmDefMIs.insert(std::make_pair(Reg, MI));
1315 ImmDefRegs.insert(Reg);
1322 /// foldImmediate - Try folding register operands that are defined by move
1323 /// immediate instructions, i.e. a trivial constant folding optimization, if
1324 /// and only if the def and use are in the same BB.
1325 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1326 SmallSet<unsigned, 4> &ImmDefRegs,
1327 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1328 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1329 MachineOperand &MO = MI->getOperand(i);
1330 if (!MO.isReg() || MO.isDef())
1332 unsigned Reg = MO.getReg();
1333 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1335 if (ImmDefRegs.count(Reg) == 0)
1337 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1338 assert(II != ImmDefMIs.end());
1339 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1347 // FIXME: This is very simple and misses some cases which should be handled when
1348 // motivating examples are found.
1350 // The copy rewriting logic should look at uses as well as defs and be able to
1351 // eliminate copies across blocks.
1353 // Later copies that are subregister extracts will also not be eliminated since
1354 // only the first copy is considered.
1357 // %vreg1 = COPY %vreg0
1358 // %vreg2 = COPY %vreg0:sub1
1360 // Should replace %vreg2 uses with %vreg1:sub1
1361 bool PeepholeOptimizer::foldRedundantCopy(
1363 SmallSet<unsigned, 4> &CopySrcRegs,
1364 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1365 assert(MI->isCopy());
1367 unsigned SrcReg = MI->getOperand(1).getReg();
1368 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1371 unsigned DstReg = MI->getOperand(0).getReg();
1372 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1375 if (CopySrcRegs.insert(SrcReg).second) {
1376 // First copy of this reg seen.
1377 CopyMIs.insert(std::make_pair(SrcReg, MI));
1381 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1383 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1384 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1386 // Can't replace different subregister extracts.
1387 if (SrcSubReg != PrevSrcSubReg)
1390 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1392 // Only replace if the copy register class is the same.
1394 // TODO: If we have multiple copies to different register classes, we may want
1395 // to track multiple copies of the same source register.
1396 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1399 MRI->replaceRegWith(DstReg, PrevDstReg);
1401 // Lifetime of the previous copy has been extended.
1402 MRI->clearKillFlags(PrevDstReg);
1406 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1407 if (skipOptnoneFunction(*MF.getFunction()))
1410 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1411 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1413 if (DisablePeephole)
1416 TII = MF.getSubtarget().getInstrInfo();
1417 TRI = MF.getSubtarget().getRegisterInfo();
1418 MRI = &MF.getRegInfo();
1419 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1421 bool Changed = false;
1423 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1424 MachineBasicBlock *MBB = &*I;
1426 bool SeenMoveImm = false;
1428 // During this forward scan, at some point it needs to answer the question
1429 // "given a pointer to an MI in the current BB, is it located before or
1430 // after the current instruction".
1431 // To perform this, the following set keeps track of the MIs already seen
1432 // during the scan, if a MI is not in the set, it is assumed to be located
1433 // after. Newly created MIs have to be inserted in the set as well.
1434 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1435 SmallSet<unsigned, 4> ImmDefRegs;
1436 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1437 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1439 // Set of virtual registers that are copied from.
1440 SmallSet<unsigned, 4> CopySrcRegs;
1441 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1443 for (MachineBasicBlock::iterator
1444 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1445 MachineInstr *MI = &*MII;
1446 // We may be erasing MI below, increment MII now.
1448 LocalMIs.insert(MI);
1450 // Skip debug values. They should not affect this peephole optimization.
1451 if (MI->isDebugValue())
1454 // If we run into an instruction we can't fold across, discard
1455 // the load candidates.
1456 if (MI->isLoadFoldBarrier())
1457 FoldAsLoadDefCandidates.clear();
1459 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1460 MI->isKill() || MI->isInlineAsm() ||
1461 MI->hasUnmodeledSideEffects())
1464 if ((isUncoalescableCopy(*MI) &&
1465 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1466 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1467 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1474 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1479 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1480 // MI is just rewritten.
1485 if (MI->isCopy() && foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs)) {
1487 MI->eraseFromParent();
1492 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1495 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1496 // optimizeExtInstr might have created new instructions after MI
1497 // and before the already incremented MII. Adjust MII so that the
1498 // next iteration sees the new instructions.
1502 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1505 // Check whether MI is a load candidate for folding into a later
1506 // instruction. If MI is not a candidate, check whether we can fold an
1507 // earlier load into MI.
1508 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1509 !FoldAsLoadDefCandidates.empty()) {
1510 const MCInstrDesc &MIDesc = MI->getDesc();
1511 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1513 const MachineOperand &MOp = MI->getOperand(i);
1516 unsigned FoldAsLoadDefReg = MOp.getReg();
1517 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1518 // We need to fold load after optimizeCmpInstr, since
1519 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1520 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1521 // we need it for markUsesInDebugValueAsUndef().
1522 unsigned FoldedReg = FoldAsLoadDefReg;
1523 MachineInstr *DefMI = nullptr;
1524 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1528 // Update LocalMIs since we replaced MI with FoldMI and deleted
1530 DEBUG(dbgs() << "Replacing: " << *MI);
1531 DEBUG(dbgs() << " With: " << *FoldMI);
1533 LocalMIs.erase(DefMI);
1534 LocalMIs.insert(FoldMI);
1535 MI->eraseFromParent();
1536 DefMI->eraseFromParent();
1537 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1538 FoldAsLoadDefCandidates.erase(FoldedReg);
1540 // MI is replaced with FoldMI.
1553 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1554 assert(Def->isCopy() && "Invalid definition");
1555 // Copy instruction are supposed to be: Def = Src.
1556 // If someone breaks this assumption, bad things will happen everywhere.
1557 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1559 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1560 // If we look for a different subreg, it means we want a subreg of src.
1561 // Bails as we do not support composing subregs yet.
1562 return ValueTrackerResult();
1563 // Otherwise, we want the whole source.
1564 const MachineOperand &Src = Def->getOperand(1);
1565 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1568 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1569 assert(Def->isBitcast() && "Invalid definition");
1571 // Bail if there are effects that a plain copy will not expose.
1572 if (Def->hasUnmodeledSideEffects())
1573 return ValueTrackerResult();
1575 // Bitcasts with more than one def are not supported.
1576 if (Def->getDesc().getNumDefs() != 1)
1577 return ValueTrackerResult();
1578 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1579 // If we look for a different subreg, it means we want a subreg of the src.
1580 // Bails as we do not support composing subregs yet.
1581 return ValueTrackerResult();
1583 unsigned SrcIdx = Def->getNumOperands();
1584 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1586 const MachineOperand &MO = Def->getOperand(OpIdx);
1587 if (!MO.isReg() || !MO.getReg())
1589 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1590 if (SrcIdx != EndOpIdx)
1591 // Multiple sources?
1592 return ValueTrackerResult();
1595 const MachineOperand &Src = Def->getOperand(SrcIdx);
1596 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1599 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1600 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1601 "Invalid definition");
1603 if (Def->getOperand(DefIdx).getSubReg())
1604 // If we are composing subregs, bail out.
1605 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1606 // This should almost never happen as the SSA property is tracked at
1607 // the register level (as opposed to the subreg level).
1611 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1612 // Def. Thus, it must not be generated.
1613 // However, some code could theoretically generates a single
1614 // Def.sub0 (i.e, not defining the other subregs) and we would
1616 // If we can ascertain (or force) that this never happens, we could
1617 // turn that into an assertion.
1618 return ValueTrackerResult();
1621 // We could handle the REG_SEQUENCE here, but we do not want to
1622 // duplicate the code from the generic TII.
1623 return ValueTrackerResult();
1625 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1626 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1627 return ValueTrackerResult();
1629 // We are looking at:
1630 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1631 // Check if one of the operand defines the subreg we are interested in.
1632 for (auto &RegSeqInput : RegSeqInputRegs) {
1633 if (RegSeqInput.SubIdx == DefSubReg) {
1634 if (RegSeqInput.SubReg)
1635 // Bail if we have to compose sub registers.
1636 return ValueTrackerResult();
1638 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1642 // If the subreg we are tracking is super-defined by another subreg,
1643 // we could follow this value. However, this would require to compose
1644 // the subreg and we do not do that for now.
1645 return ValueTrackerResult();
1648 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1649 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1650 "Invalid definition");
1652 if (Def->getOperand(DefIdx).getSubReg())
1653 // If we are composing subreg, bail out.
1654 // Same remark as getNextSourceFromRegSequence.
1655 // I.e., this may be turned into an assert.
1656 return ValueTrackerResult();
1659 // We could handle the REG_SEQUENCE here, but we do not want to
1660 // duplicate the code from the generic TII.
1661 return ValueTrackerResult();
1663 TargetInstrInfo::RegSubRegPair BaseReg;
1664 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1665 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1666 return ValueTrackerResult();
1668 // We are looking at:
1669 // Def = INSERT_SUBREG v0, v1, sub1
1670 // There are two cases:
1671 // 1. DefSubReg == sub1, get v1.
1672 // 2. DefSubReg != sub1, the value may be available through v0.
1674 // #1 Check if the inserted register matches the required sub index.
1675 if (InsertedReg.SubIdx == DefSubReg) {
1676 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1678 // #2 Otherwise, if the sub register we are looking for is not partial
1679 // defined by the inserted element, we can look through the main
1681 const MachineOperand &MODef = Def->getOperand(DefIdx);
1682 // If the result register (Def) and the base register (v0) do not
1683 // have the same register class or if we have to compose
1684 // subregisters, bail out.
1685 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1687 return ValueTrackerResult();
1689 // Get the TRI and check if the inserted sub-register overlaps with the
1690 // sub-register we are tracking.
1691 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1693 (TRI->getSubRegIndexLaneMask(DefSubReg) &
1694 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1695 return ValueTrackerResult();
1696 // At this point, the value is available in v0 via the same subreg
1698 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1701 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1702 assert((Def->isExtractSubreg() ||
1703 Def->isExtractSubregLike()) && "Invalid definition");
1704 // We are looking at:
1705 // Def = EXTRACT_SUBREG v0, sub0
1707 // Bail if we have to compose sub registers.
1708 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1710 return ValueTrackerResult();
1713 // We could handle the EXTRACT_SUBREG here, but we do not want to
1714 // duplicate the code from the generic TII.
1715 return ValueTrackerResult();
1717 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1718 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1719 return ValueTrackerResult();
1721 // Bail if we have to compose sub registers.
1722 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1723 if (ExtractSubregInputReg.SubReg)
1724 return ValueTrackerResult();
1725 // Otherwise, the value is available in the v0.sub0.
1726 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
1729 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
1730 assert(Def->isSubregToReg() && "Invalid definition");
1731 // We are looking at:
1732 // Def = SUBREG_TO_REG Imm, v0, sub0
1734 // Bail if we have to compose sub registers.
1735 // If DefSubReg != sub0, we would have to check that all the bits
1736 // we track are included in sub0 and if yes, we would have to
1737 // determine the right subreg in v0.
1738 if (DefSubReg != Def->getOperand(3).getImm())
1739 return ValueTrackerResult();
1740 // Bail if we have to compose sub registers.
1741 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1742 if (Def->getOperand(2).getSubReg())
1743 return ValueTrackerResult();
1745 return ValueTrackerResult(Def->getOperand(2).getReg(),
1746 Def->getOperand(3).getImm());
1749 /// \brief Explore each PHI incoming operand and return its sources
1750 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1751 assert(Def->isPHI() && "Invalid definition");
1752 ValueTrackerResult Res;
1754 // If we look for a different subreg, bail as we do not support composing
1756 if (Def->getOperand(0).getSubReg() != DefSubReg)
1757 return ValueTrackerResult();
1759 // Return all register sources for PHI instructions.
1760 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1761 auto &MO = Def->getOperand(i);
1762 assert(MO.isReg() && "Invalid PHI instruction");
1763 Res.addSource(MO.getReg(), MO.getSubReg());
1769 ValueTrackerResult ValueTracker::getNextSourceImpl() {
1770 assert(Def && "This method needs a valid definition");
1773 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1774 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1776 return getNextSourceFromCopy();
1777 if (Def->isBitcast())
1778 return getNextSourceFromBitcast();
1779 // All the remaining cases involve "complex" instructions.
1780 // Bail if we did not ask for the advanced tracking.
1781 if (!UseAdvancedTracking)
1782 return ValueTrackerResult();
1783 if (Def->isRegSequence() || Def->isRegSequenceLike())
1784 return getNextSourceFromRegSequence();
1785 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1786 return getNextSourceFromInsertSubreg();
1787 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1788 return getNextSourceFromExtractSubreg();
1789 if (Def->isSubregToReg())
1790 return getNextSourceFromSubregToReg();
1792 return getNextSourceFromPHI();
1793 return ValueTrackerResult();
1796 ValueTrackerResult ValueTracker::getNextSource() {
1797 // If we reach a point where we cannot move up in the use-def chain,
1798 // there is nothing we can get.
1800 return ValueTrackerResult();
1802 ValueTrackerResult Res = getNextSourceImpl();
1803 if (Res.isValid()) {
1804 // Update definition, definition index, and subregister for the
1805 // next call of getNextSource.
1806 // Update the current register.
1807 bool OneRegSrc = Res.getNumSources() == 1;
1809 Reg = Res.getSrcReg(0);
1810 // Update the result before moving up in the use-def chain
1811 // with the instruction containing the last found sources.
1814 // If we can still move up in the use-def chain, move to the next
1816 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
1817 Def = MRI.getVRegDef(Reg);
1818 DefIdx = MRI.def_begin(Reg).getOperandNo();
1819 DefSubReg = Res.getSrcSubReg(0);
1823 // If we end up here, this means we will not be able to find another source
1824 // for the next iteration. Make sure any new call to getNextSource bails out
1825 // early by cutting the use-def chain.