1 //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Perform peephole optimizations on the machine code:
11 // - Optimize Extensions
13 // Optimization of sign / zero extension instructions. It may be extended to
14 // handle other instructions with similar properties.
16 // On some targets, some instructions, e.g. X86 sign / zero extension, may
17 // leave the source value in the lower part of the result. This optimization
18 // will replace some uses of the pre-extension value with uses of the
19 // sub-register of the results.
21 // - Optimize Comparisons
23 // Optimization of comparison instructions. For instance, in this code:
29 // If the "sub" instruction all ready sets (or could be modified to set) the
30 // same flag that the "cmp" instruction sets and that "bz" uses, then we can
31 // eliminate the "cmp" instruction.
33 // Another instance, in this code:
35 // sub r1, r3 | sub r1, imm
36 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
39 // If the branch instruction can use flag from "sub", then we can replace
40 // "sub" with "subs" and eliminate the "cmp" instruction.
44 // Loads that can be folded into a later instruction. A load is foldable
45 // if it loads to virtual registers and the virtual register defined has
48 // - Optimize Copies and Bitcast (more generally, target specific copies):
50 // Rewrite copies and bitcasts to avoid cross register bank copies
52 // E.g., Consider the following example, where capital and lower
53 // letters denote different register file:
54 // b = copy A <-- cross-bank copy
55 // C = copy b <-- cross-bank copy
57 // b = copy A <-- cross-bank copy
58 // C = copy A <-- same-bank copy
61 // b = bitcast A <-- cross-bank copy
62 // C = bitcast b <-- cross-bank copy
64 // b = bitcast A <-- cross-bank copy
65 // C = copy A <-- same-bank copy
66 //===----------------------------------------------------------------------===//
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/SmallPtrSet.h"
70 #include "llvm/ADT/SmallSet.h"
71 #include "llvm/ADT/SmallVector.h"
72 #include "llvm/ADT/Statistic.h"
73 #include "llvm/CodeGen/MachineBasicBlock.h"
74 #include "llvm/CodeGen/MachineDominators.h"
75 #include "llvm/CodeGen/MachineFunction.h"
76 #include "llvm/CodeGen/MachineFunctionPass.h"
77 #include "llvm/CodeGen/MachineInstr.h"
78 #include "llvm/CodeGen/MachineInstrBuilder.h"
79 #include "llvm/CodeGen/MachineLoopInfo.h"
80 #include "llvm/CodeGen/MachineOperand.h"
81 #include "llvm/CodeGen/MachineRegisterInfo.h"
82 #include "llvm/CodeGen/TargetInstrInfo.h"
83 #include "llvm/CodeGen/TargetOpcodes.h"
84 #include "llvm/CodeGen/TargetRegisterInfo.h"
85 #include "llvm/CodeGen/TargetSubtargetInfo.h"
86 #include "llvm/InitializePasses.h"
87 #include "llvm/MC/LaneBitmask.h"
88 #include "llvm/MC/MCInstrDesc.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/raw_ostream.h"
99 using RegSubRegPair
= TargetInstrInfo::RegSubRegPair
;
100 using RegSubRegPairAndIdx
= TargetInstrInfo::RegSubRegPairAndIdx
;
102 #define DEBUG_TYPE "peephole-opt"
104 // Optimize Extensions
106 Aggressive("aggressive-ext-opt", cl::Hidden
,
107 cl::desc("Aggressive extension optimization"));
110 DisablePeephole("disable-peephole", cl::Hidden
, cl::init(false),
111 cl::desc("Disable the peephole optimizer"));
113 /// Specifiy whether or not the value tracking looks through
114 /// complex instructions. When this is true, the value tracker
115 /// bails on everything that is not a copy or a bitcast.
117 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden
, cl::init(false),
118 cl::desc("Disable advanced copy optimization"));
120 static cl::opt
<bool> DisableNAPhysCopyOpt(
121 "disable-non-allocatable-phys-copy-opt", cl::Hidden
, cl::init(false),
122 cl::desc("Disable non-allocatable physical register copy optimization"));
124 // Limit the number of PHI instructions to process
125 // in PeepholeOptimizer::getNextSource.
126 static cl::opt
<unsigned> RewritePHILimit(
127 "rewrite-phi-limit", cl::Hidden
, cl::init(10),
128 cl::desc("Limit the length of PHI chains to lookup"));
130 // Limit the length of recurrence chain when evaluating the benefit of
131 // commuting operands.
132 static cl::opt
<unsigned> MaxRecurrenceChain(
133 "recurrence-chain-limit", cl::Hidden
, cl::init(3),
134 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
135 "of commuting operands"));
138 STATISTIC(NumReuse
, "Number of extension results reused");
139 STATISTIC(NumCmps
, "Number of compares eliminated");
140 STATISTIC(NumImmFold
, "Number of move immediate folded");
141 STATISTIC(NumLoadFold
, "Number of loads folded");
142 STATISTIC(NumSelects
, "Number of selects optimized");
143 STATISTIC(NumUncoalescableCopies
, "Number of uncoalescable copies optimized");
144 STATISTIC(NumRewrittenCopies
, "Number of copies rewritten");
145 STATISTIC(NumNAPhysCopies
, "Number of non-allocatable physical copies removed");
149 class ValueTrackerResult
;
150 class RecurrenceInstr
;
152 class PeepholeOptimizer
: public MachineFunctionPass
,
153 private MachineFunction::Delegate
{
154 const TargetInstrInfo
*TII
= nullptr;
155 const TargetRegisterInfo
*TRI
= nullptr;
156 MachineRegisterInfo
*MRI
= nullptr;
157 MachineDominatorTree
*DT
= nullptr; // Machine dominator tree
158 MachineLoopInfo
*MLI
= nullptr;
161 static char ID
; // Pass identification
163 PeepholeOptimizer() : MachineFunctionPass(ID
) {
164 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
167 bool runOnMachineFunction(MachineFunction
&MF
) override
;
169 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
170 AU
.setPreservesCFG();
171 MachineFunctionPass::getAnalysisUsage(AU
);
172 AU
.addRequired
<MachineLoopInfoWrapperPass
>();
173 AU
.addPreserved
<MachineLoopInfoWrapperPass
>();
175 AU
.addRequired
<MachineDominatorTreeWrapperPass
>();
176 AU
.addPreserved
<MachineDominatorTreeWrapperPass
>();
180 MachineFunctionProperties
getRequiredProperties() const override
{
181 return MachineFunctionProperties()
182 .set(MachineFunctionProperties::Property::IsSSA
);
185 /// Track Def -> Use info used for rewriting copies.
186 using RewriteMapTy
= SmallDenseMap
<RegSubRegPair
, ValueTrackerResult
>;
188 /// Sequence of instructions that formulate recurrence cycle.
189 using RecurrenceCycle
= SmallVector
<RecurrenceInstr
, 4>;
192 bool optimizeCmpInstr(MachineInstr
&MI
);
193 bool optimizeExtInstr(MachineInstr
&MI
, MachineBasicBlock
&MBB
,
194 SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
);
195 bool optimizeSelect(MachineInstr
&MI
,
196 SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
);
197 bool optimizeCondBranch(MachineInstr
&MI
);
198 bool optimizeCoalescableCopy(MachineInstr
&MI
);
199 bool optimizeUncoalescableCopy(MachineInstr
&MI
,
200 SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
);
201 bool optimizeRecurrence(MachineInstr
&PHI
);
202 bool findNextSource(RegSubRegPair RegSubReg
, RewriteMapTy
&RewriteMap
);
203 bool isMoveImmediate(MachineInstr
&MI
, SmallSet
<Register
, 4> &ImmDefRegs
,
204 DenseMap
<Register
, MachineInstr
*> &ImmDefMIs
);
205 bool foldImmediate(MachineInstr
&MI
, SmallSet
<Register
, 4> &ImmDefRegs
,
206 DenseMap
<Register
, MachineInstr
*> &ImmDefMIs
,
209 /// Finds recurrence cycles, but only ones that formulated around
210 /// a def operand and a use operand that are tied. If there is a use
211 /// operand commutable with the tied use operand, find recurrence cycle
212 /// along that operand as well.
213 bool findTargetRecurrence(Register Reg
,
214 const SmallSet
<Register
, 2> &TargetReg
,
215 RecurrenceCycle
&RC
);
217 /// If copy instruction \p MI is a virtual register copy or a copy of a
218 /// constant physical register to a virtual register, track it in the
219 /// set CopySrcMIs. If this virtual register was previously seen as a
220 /// copy, replace the uses of this copy with the previously seen copy's
221 /// destination register.
222 bool foldRedundantCopy(MachineInstr
&MI
);
224 /// Is the register \p Reg a non-allocatable physical register?
225 bool isNAPhysCopy(Register Reg
);
227 /// If copy instruction \p MI is a non-allocatable virtual<->physical
228 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
229 /// non-allocatable physical register was previously copied to a virtual
230 /// registered and hasn't been clobbered, the virt->phys copy can be
232 bool foldRedundantNAPhysCopy(
233 MachineInstr
&MI
, DenseMap
<Register
, MachineInstr
*> &NAPhysToVirtMIs
);
235 bool isLoadFoldable(MachineInstr
&MI
,
236 SmallSet
<Register
, 16> &FoldAsLoadDefCandidates
);
238 /// Check whether \p MI is understood by the register coalescer
239 /// but may require some rewriting.
240 bool isCoalescableCopy(const MachineInstr
&MI
) {
241 // SubregToRegs are not interesting, because they are already register
242 // coalescer friendly.
243 return MI
.isCopy() || (!DisableAdvCopyOpt
&&
244 (MI
.isRegSequence() || MI
.isInsertSubreg() ||
245 MI
.isExtractSubreg()));
248 /// Check whether \p MI is a copy like instruction that is
249 /// not recognized by the register coalescer.
250 bool isUncoalescableCopy(const MachineInstr
&MI
) {
251 return MI
.isBitcast() ||
252 (!DisableAdvCopyOpt
&&
253 (MI
.isRegSequenceLike() || MI
.isInsertSubregLike() ||
254 MI
.isExtractSubregLike()));
257 MachineInstr
&rewriteSource(MachineInstr
&CopyLike
,
258 RegSubRegPair Def
, RewriteMapTy
&RewriteMap
);
260 // Set of copies to virtual registers keyed by source register. Never
261 // holds any physreg which requires def tracking.
262 DenseMap
<RegSubRegPair
, MachineInstr
*> CopySrcMIs
;
264 // MachineFunction::Delegate implementation. Used to maintain CopySrcMIs.
265 void MF_HandleInsertion(MachineInstr
&MI
) override
{
269 bool getCopySrc(MachineInstr
&MI
, RegSubRegPair
&SrcPair
) {
273 Register SrcReg
= MI
.getOperand(1).getReg();
274 unsigned SrcSubReg
= MI
.getOperand(1).getSubReg();
275 if (!SrcReg
.isVirtual() && !MRI
->isConstantPhysReg(SrcReg
))
278 SrcPair
= RegSubRegPair(SrcReg
, SrcSubReg
);
282 // If a COPY instruction is to be deleted or changed, we should also remove
283 // it from CopySrcMIs.
284 void deleteChangedCopy(MachineInstr
&MI
) {
285 RegSubRegPair SrcPair
;
286 if (!getCopySrc(MI
, SrcPair
))
289 auto It
= CopySrcMIs
.find(SrcPair
);
290 if (It
!= CopySrcMIs
.end() && It
->second
== &MI
)
291 CopySrcMIs
.erase(It
);
294 void MF_HandleRemoval(MachineInstr
&MI
) override
{
295 deleteChangedCopy(MI
);
298 void MF_HandleChangeDesc(MachineInstr
&MI
, const MCInstrDesc
&TID
) override
300 deleteChangedCopy(MI
);
304 /// Helper class to hold instructions that are inside recurrence cycles.
305 /// The recurrence cycle is formulated around 1) a def operand and its
306 /// tied use operand, or 2) a def operand and a use operand that is commutable
307 /// with another use operand which is tied to the def operand. In the latter
308 /// case, index of the tied use operand and the commutable use operand are
309 /// maintained with CommutePair.
310 class RecurrenceInstr
{
312 using IndexPair
= std::pair
<unsigned, unsigned>;
314 RecurrenceInstr(MachineInstr
*MI
) : MI(MI
) {}
315 RecurrenceInstr(MachineInstr
*MI
, unsigned Idx1
, unsigned Idx2
)
316 : MI(MI
), CommutePair(std::make_pair(Idx1
, Idx2
)) {}
318 MachineInstr
*getMI() const { return MI
; }
319 std::optional
<IndexPair
> getCommutePair() const { return CommutePair
; }
323 std::optional
<IndexPair
> CommutePair
;
326 /// Helper class to hold a reply for ValueTracker queries.
327 /// Contains the returned sources for a given search and the instructions
328 /// where the sources were tracked from.
329 class ValueTrackerResult
{
331 /// Track all sources found by one ValueTracker query.
332 SmallVector
<RegSubRegPair
, 2> RegSrcs
;
334 /// Instruction using the sources in 'RegSrcs'.
335 const MachineInstr
*Inst
= nullptr;
338 ValueTrackerResult() = default;
340 ValueTrackerResult(Register Reg
, unsigned SubReg
) {
341 addSource(Reg
, SubReg
);
344 bool isValid() const { return getNumSources() > 0; }
346 void setInst(const MachineInstr
*I
) { Inst
= I
; }
347 const MachineInstr
*getInst() const { return Inst
; }
354 void addSource(Register SrcReg
, unsigned SrcSubReg
) {
355 RegSrcs
.push_back(RegSubRegPair(SrcReg
, SrcSubReg
));
358 void setSource(int Idx
, Register SrcReg
, unsigned SrcSubReg
) {
359 assert(Idx
< getNumSources() && "Reg pair source out of index");
360 RegSrcs
[Idx
] = RegSubRegPair(SrcReg
, SrcSubReg
);
363 int getNumSources() const { return RegSrcs
.size(); }
365 RegSubRegPair
getSrc(int Idx
) const {
369 Register
getSrcReg(int Idx
) const {
370 assert(Idx
< getNumSources() && "Reg source out of index");
371 return RegSrcs
[Idx
].Reg
;
374 unsigned getSrcSubReg(int Idx
) const {
375 assert(Idx
< getNumSources() && "SubReg source out of index");
376 return RegSrcs
[Idx
].SubReg
;
379 bool operator==(const ValueTrackerResult
&Other
) const {
380 if (Other
.getInst() != getInst())
383 if (Other
.getNumSources() != getNumSources())
386 for (int i
= 0, e
= Other
.getNumSources(); i
!= e
; ++i
)
387 if (Other
.getSrcReg(i
) != getSrcReg(i
) ||
388 Other
.getSrcSubReg(i
) != getSrcSubReg(i
))
394 /// Helper class to track the possible sources of a value defined by
395 /// a (chain of) copy related instructions.
396 /// Given a definition (instruction and definition index), this class
397 /// follows the use-def chain to find successive suitable sources.
398 /// The given source can be used to rewrite the definition into
401 /// For instance, let us consider the following snippet:
403 /// v2 = INSERT_SUBREG v1, v0, sub0
404 /// def = COPY v2.sub0
406 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
407 /// suitable sources:
409 /// Then, def can be rewritten into def = COPY v0.
412 /// The current point into the use-def chain.
413 const MachineInstr
*Def
= nullptr;
415 /// The index of the definition in Def.
418 /// The sub register index of the definition.
421 /// The register where the value can be found.
424 /// MachineRegisterInfo used to perform tracking.
425 const MachineRegisterInfo
&MRI
;
427 /// Optional TargetInstrInfo used to perform some complex tracking.
428 const TargetInstrInfo
*TII
;
430 /// Dispatcher to the right underlying implementation of getNextSource.
431 ValueTrackerResult
getNextSourceImpl();
433 /// Specialized version of getNextSource for Copy instructions.
434 ValueTrackerResult
getNextSourceFromCopy();
436 /// Specialized version of getNextSource for Bitcast instructions.
437 ValueTrackerResult
getNextSourceFromBitcast();
439 /// Specialized version of getNextSource for RegSequence instructions.
440 ValueTrackerResult
getNextSourceFromRegSequence();
442 /// Specialized version of getNextSource for InsertSubreg instructions.
443 ValueTrackerResult
getNextSourceFromInsertSubreg();
445 /// Specialized version of getNextSource for ExtractSubreg instructions.
446 ValueTrackerResult
getNextSourceFromExtractSubreg();
448 /// Specialized version of getNextSource for SubregToReg instructions.
449 ValueTrackerResult
getNextSourceFromSubregToReg();
451 /// Specialized version of getNextSource for PHI instructions.
452 ValueTrackerResult
getNextSourceFromPHI();
455 /// Create a ValueTracker instance for the value defined by \p Reg.
456 /// \p DefSubReg represents the sub register index the value tracker will
457 /// track. It does not need to match the sub register index used in the
458 /// definition of \p Reg.
459 /// If \p Reg is a physical register, a value tracker constructed with
460 /// this constructor will not find any alternative source.
461 /// Indeed, when \p Reg is a physical register that constructor does not
462 /// know which definition of \p Reg it should track.
463 /// Use the next constructor to track a physical register.
464 ValueTracker(Register Reg
, unsigned DefSubReg
,
465 const MachineRegisterInfo
&MRI
,
466 const TargetInstrInfo
*TII
= nullptr)
467 : DefSubReg(DefSubReg
), Reg(Reg
), MRI(MRI
), TII(TII
) {
468 if (!Reg
.isPhysical()) {
469 Def
= MRI
.getVRegDef(Reg
);
470 DefIdx
= MRI
.def_begin(Reg
).getOperandNo();
474 /// Following the use-def chain, get the next available source
475 /// for the tracked value.
476 /// \return A ValueTrackerResult containing a set of registers
477 /// and sub registers with tracked values. A ValueTrackerResult with
478 /// an empty set of registers means no source was found.
479 ValueTrackerResult
getNextSource();
482 } // end anonymous namespace
484 char PeepholeOptimizer::ID
= 0;
486 char &llvm::PeepholeOptimizerID
= PeepholeOptimizer::ID
;
488 INITIALIZE_PASS_BEGIN(PeepholeOptimizer
, DEBUG_TYPE
,
489 "Peephole Optimizations", false, false)
490 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass
)
491 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass
)
492 INITIALIZE_PASS_END(PeepholeOptimizer
, DEBUG_TYPE
,
493 "Peephole Optimizations", false, false)
495 /// If instruction is a copy-like instruction, i.e. it reads a single register
496 /// and writes a single register and it does not modify the source, and if the
497 /// source value is preserved as a sub-register of the result, then replace all
498 /// reachable uses of the source with the subreg of the result.
500 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
501 /// the code. Since this code does not currently share EXTRACTs, just ignore all
503 bool PeepholeOptimizer::
504 optimizeExtInstr(MachineInstr
&MI
, MachineBasicBlock
&MBB
,
505 SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
) {
506 Register SrcReg
, DstReg
;
508 if (!TII
->isCoalescableExtInstr(MI
, SrcReg
, DstReg
, SubIdx
))
511 if (DstReg
.isPhysical() || SrcReg
.isPhysical())
514 if (MRI
->hasOneNonDBGUse(SrcReg
))
518 // Ensure DstReg can get a register class that actually supports
519 // sub-registers. Don't change the class until we commit.
520 const TargetRegisterClass
*DstRC
= MRI
->getRegClass(DstReg
);
521 DstRC
= TRI
->getSubClassWithSubReg(DstRC
, SubIdx
);
525 // The ext instr may be operating on a sub-register of SrcReg as well.
526 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
528 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
529 // SrcReg:SubIdx should be replaced.
531 TRI
->getSubClassWithSubReg(MRI
->getRegClass(SrcReg
), SubIdx
) != nullptr;
533 // The source has other uses. See if we can replace the other uses with use of
534 // the result of the extension.
535 SmallPtrSet
<MachineBasicBlock
*, 4> ReachedBBs
;
536 for (MachineInstr
&UI
: MRI
->use_nodbg_instructions(DstReg
))
537 ReachedBBs
.insert(UI
.getParent());
539 // Uses that are in the same BB of uses of the result of the instruction.
540 SmallVector
<MachineOperand
*, 8> Uses
;
542 // Uses that the result of the instruction can reach.
543 SmallVector
<MachineOperand
*, 8> ExtendedUses
;
545 bool ExtendLife
= true;
546 for (MachineOperand
&UseMO
: MRI
->use_nodbg_operands(SrcReg
)) {
547 MachineInstr
*UseMI
= UseMO
.getParent();
551 if (UseMI
->isPHI()) {
556 // Only accept uses of SrcReg:SubIdx.
557 if (UseSrcSubIdx
&& UseMO
.getSubReg() != SubIdx
)
560 // It's an error to translate this:
562 // %reg1025 = <sext> %reg1024
564 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
568 // %reg1025 = <sext> %reg1024
570 // %reg1027 = COPY %reg1025:4
571 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
573 // The problem here is that SUBREG_TO_REG is there to assert that an
574 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
575 // the COPY here, it will give us the value after the <sext>, not the
576 // original value of %reg1024 before <sext>.
577 if (UseMI
->getOpcode() == TargetOpcode::SUBREG_TO_REG
)
580 MachineBasicBlock
*UseMBB
= UseMI
->getParent();
581 if (UseMBB
== &MBB
) {
582 // Local uses that come after the extension.
583 if (!LocalMIs
.count(UseMI
))
584 Uses
.push_back(&UseMO
);
585 } else if (ReachedBBs
.count(UseMBB
)) {
586 // Non-local uses where the result of the extension is used. Always
587 // replace these unless it's a PHI.
588 Uses
.push_back(&UseMO
);
589 } else if (Aggressive
&& DT
->dominates(&MBB
, UseMBB
)) {
590 // We may want to extend the live range of the extension result in order
591 // to replace these uses.
592 ExtendedUses
.push_back(&UseMO
);
594 // Both will be live out of the def MBB anyway. Don't extend live range of
595 // the extension result.
601 if (ExtendLife
&& !ExtendedUses
.empty())
602 // Extend the liveness of the extension result.
603 Uses
.append(ExtendedUses
.begin(), ExtendedUses
.end());
605 // Now replace all uses.
606 bool Changed
= false;
608 SmallPtrSet
<MachineBasicBlock
*, 4> PHIBBs
;
610 // Look for PHI uses of the extended result, we don't want to extend the
611 // liveness of a PHI input. It breaks all kinds of assumptions down
612 // stream. A PHI use is expected to be the kill of its source values.
613 for (MachineInstr
&UI
: MRI
->use_nodbg_instructions(DstReg
))
615 PHIBBs
.insert(UI
.getParent());
617 const TargetRegisterClass
*RC
= MRI
->getRegClass(SrcReg
);
618 for (MachineOperand
*UseMO
: Uses
) {
619 MachineInstr
*UseMI
= UseMO
->getParent();
620 MachineBasicBlock
*UseMBB
= UseMI
->getParent();
621 if (PHIBBs
.count(UseMBB
))
624 // About to add uses of DstReg, clear DstReg's kill flags.
626 MRI
->clearKillFlags(DstReg
);
627 MRI
->constrainRegClass(DstReg
, DstRC
);
630 // SubReg defs are illegal in machine SSA phase,
631 // we should not generate SubReg defs.
633 // For example, for the instructions:
635 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
636 // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
638 // We should generate:
640 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
641 // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
642 // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
645 RC
= MRI
->getRegClass(UseMI
->getOperand(0).getReg());
647 Register NewVR
= MRI
->createVirtualRegister(RC
);
648 BuildMI(*UseMBB
, UseMI
, UseMI
->getDebugLoc(),
649 TII
->get(TargetOpcode::COPY
), NewVR
)
650 .addReg(DstReg
, 0, SubIdx
);
654 UseMO
->setReg(NewVR
);
663 /// If the instruction is a compare and the previous instruction it's comparing
664 /// against already sets (or could be modified to set) the same flag as the
665 /// compare, then we can remove the comparison and use the flag from the
666 /// previous instruction.
667 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr
&MI
) {
668 // If this instruction is a comparison against zero and isn't comparing a
669 // physical register, we can try to optimize it.
670 Register SrcReg
, SrcReg2
;
671 int64_t CmpMask
, CmpValue
;
672 if (!TII
->analyzeCompare(MI
, SrcReg
, SrcReg2
, CmpMask
, CmpValue
) ||
673 SrcReg
.isPhysical() || SrcReg2
.isPhysical())
676 // Attempt to optimize the comparison instruction.
677 LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI
);
678 if (TII
->optimizeCompareInstr(MI
, SrcReg
, SrcReg2
, CmpMask
, CmpValue
, MRI
)) {
679 LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n");
687 /// Optimize a select instruction.
688 bool PeepholeOptimizer::optimizeSelect(MachineInstr
&MI
,
689 SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
) {
691 unsigned FalseOp
= 0;
692 bool Optimizable
= false;
693 SmallVector
<MachineOperand
, 4> Cond
;
694 if (TII
->analyzeSelect(MI
, Cond
, TrueOp
, FalseOp
, Optimizable
))
698 if (!TII
->optimizeSelect(MI
, LocalMIs
))
700 LLVM_DEBUG(dbgs() << "Deleting select: " << MI
);
701 MI
.eraseFromParent();
706 /// Check if a simpler conditional branch can be generated.
707 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr
&MI
) {
708 return TII
->optimizeCondBranch(MI
);
711 /// Try to find the next source that share the same register file
712 /// for the value defined by \p Reg and \p SubReg.
713 /// When true is returned, the \p RewriteMap can be used by the client to
714 /// retrieve all Def -> Use along the way up to the next source. Any found
715 /// Use that is not itself a key for another entry, is the next source to
716 /// use. During the search for the next source, multiple sources can be found
717 /// given multiple incoming sources of a PHI instruction. In this case, we
718 /// look in each PHI source for the next source; all found next sources must
719 /// share the same register file as \p Reg and \p SubReg. The client should
720 /// then be capable to rewrite all intermediate PHIs to get the next source.
721 /// \return False if no alternative sources are available. True otherwise.
722 bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg
,
723 RewriteMapTy
&RewriteMap
) {
724 // Do not try to find a new source for a physical register.
725 // So far we do not have any motivating example for doing that.
726 // Thus, instead of maintaining untested code, we will revisit that if
727 // that changes at some point.
728 Register Reg
= RegSubReg
.Reg
;
729 if (Reg
.isPhysical())
731 const TargetRegisterClass
*DefRC
= MRI
->getRegClass(Reg
);
733 SmallVector
<RegSubRegPair
, 4> SrcToLook
;
734 RegSubRegPair CurSrcPair
= RegSubReg
;
735 SrcToLook
.push_back(CurSrcPair
);
737 unsigned PHICount
= 0;
739 CurSrcPair
= SrcToLook
.pop_back_val();
740 // As explained above, do not handle physical registers
741 if (CurSrcPair
.Reg
.isPhysical())
744 ValueTracker
ValTracker(CurSrcPair
.Reg
, CurSrcPair
.SubReg
, *MRI
, TII
);
746 // Follow the chain of copies until we find a more suitable source, a phi
749 ValueTrackerResult Res
= ValTracker
.getNextSource();
750 // Abort at the end of a chain (without finding a suitable source).
754 // Insert the Def -> Use entry for the recently found source.
755 ValueTrackerResult CurSrcRes
= RewriteMap
.lookup(CurSrcPair
);
756 if (CurSrcRes
.isValid()) {
757 assert(CurSrcRes
== Res
&& "ValueTrackerResult found must match");
758 // An existent entry with multiple sources is a PHI cycle we must avoid.
759 // Otherwise it's an entry with a valid next source we already found.
760 if (CurSrcRes
.getNumSources() > 1) {
762 << "findNextSource: found PHI cycle, aborting...\n");
767 RewriteMap
.insert(std::make_pair(CurSrcPair
, Res
));
769 // ValueTrackerResult usually have one source unless it's the result from
770 // a PHI instruction. Add the found PHI edges to be looked up further.
771 unsigned NumSrcs
= Res
.getNumSources();
774 if (PHICount
>= RewritePHILimit
) {
775 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
779 for (unsigned i
= 0; i
< NumSrcs
; ++i
)
780 SrcToLook
.push_back(Res
.getSrc(i
));
784 CurSrcPair
= Res
.getSrc(0);
785 // Do not extend the live-ranges of physical registers as they add
786 // constraints to the register allocator. Moreover, if we want to extend
787 // the live-range of a physical register, unlike SSA virtual register,
788 // we will have to check that they aren't redefine before the related use.
789 if (CurSrcPair
.Reg
.isPhysical())
792 // Keep following the chain if the value isn't any better yet.
793 const TargetRegisterClass
*SrcRC
= MRI
->getRegClass(CurSrcPair
.Reg
);
794 if (!TRI
->shouldRewriteCopySrc(DefRC
, RegSubReg
.SubReg
, SrcRC
,
798 // We currently cannot deal with subreg operands on PHI instructions
799 // (see insertPHI()).
800 if (PHICount
> 0 && CurSrcPair
.SubReg
!= 0)
803 // We found a suitable source, and are done with this chain.
806 } while (!SrcToLook
.empty());
808 // If we did not find a more suitable source, there is nothing to optimize.
809 return CurSrcPair
.Reg
!= Reg
;
812 /// Insert a PHI instruction with incoming edges \p SrcRegs that are
813 /// guaranteed to have the same register class. This is necessary whenever we
814 /// successfully traverse a PHI instruction and find suitable sources coming
815 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
816 /// suitable to be used in a new COPY instruction.
817 static MachineInstr
&
818 insertPHI(MachineRegisterInfo
&MRI
, const TargetInstrInfo
&TII
,
819 const SmallVectorImpl
<RegSubRegPair
> &SrcRegs
,
820 MachineInstr
&OrigPHI
) {
821 assert(!SrcRegs
.empty() && "No sources to create a PHI instruction?");
823 const TargetRegisterClass
*NewRC
= MRI
.getRegClass(SrcRegs
[0].Reg
);
824 // NewRC is only correct if no subregisters are involved. findNextSource()
825 // should have rejected those cases already.
826 assert(SrcRegs
[0].SubReg
== 0 && "should not have subreg operand");
827 Register NewVR
= MRI
.createVirtualRegister(NewRC
);
828 MachineBasicBlock
*MBB
= OrigPHI
.getParent();
829 MachineInstrBuilder MIB
= BuildMI(*MBB
, &OrigPHI
, OrigPHI
.getDebugLoc(),
830 TII
.get(TargetOpcode::PHI
), NewVR
);
832 unsigned MBBOpIdx
= 2;
833 for (const RegSubRegPair
&RegPair
: SrcRegs
) {
834 MIB
.addReg(RegPair
.Reg
, 0, RegPair
.SubReg
);
835 MIB
.addMBB(OrigPHI
.getOperand(MBBOpIdx
).getMBB());
836 // Since we're extended the lifetime of RegPair.Reg, clear the
837 // kill flags to account for that and make RegPair.Reg reaches
839 MRI
.clearKillFlags(RegPair
.Reg
);
848 /// Interface to query instructions amenable to copy rewriting.
851 MachineInstr
&CopyLike
;
852 unsigned CurrentSrcIdx
= 0; ///< The index of the source being rewritten.
854 Rewriter(MachineInstr
&CopyLike
) : CopyLike(CopyLike
) {}
855 virtual ~Rewriter() = default;
857 /// Get the next rewritable source (SrcReg, SrcSubReg) and
858 /// the related value that it affects (DstReg, DstSubReg).
859 /// A source is considered rewritable if its register class and the
860 /// register class of the related DstReg may not be register
861 /// coalescer friendly. In other words, given a copy-like instruction
862 /// not all the arguments may be returned at rewritable source, since
863 /// some arguments are none to be register coalescer friendly.
865 /// Each call of this method moves the current source to the next
866 /// rewritable source.
867 /// For instance, let CopyLike be the instruction to rewrite.
868 /// CopyLike has one definition and one source:
869 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
871 /// The first call will give the first rewritable source, i.e.,
872 /// the only source this instruction has:
873 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
874 /// This source defines the whole definition, i.e.,
875 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
877 /// The second and subsequent calls will return false, as there is only one
878 /// rewritable source.
880 /// \return True if a rewritable source has been found, false otherwise.
881 /// The output arguments are valid if and only if true is returned.
882 virtual bool getNextRewritableSource(RegSubRegPair
&Src
,
883 RegSubRegPair
&Dst
) = 0;
885 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
886 /// \return True if the rewriting was possible, false otherwise.
887 virtual bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) = 0;
890 /// Rewriter for COPY instructions.
891 class CopyRewriter
: public Rewriter
{
893 CopyRewriter(MachineInstr
&MI
) : Rewriter(MI
) {
894 assert(MI
.isCopy() && "Expected copy instruction");
896 virtual ~CopyRewriter() = default;
898 bool getNextRewritableSource(RegSubRegPair
&Src
,
899 RegSubRegPair
&Dst
) override
{
900 // CurrentSrcIdx > 0 means this function has already been called.
901 if (CurrentSrcIdx
> 0)
903 // This is the first call to getNextRewritableSource.
904 // Move the CurrentSrcIdx to remember that we made that call.
906 // The rewritable source is the argument.
907 const MachineOperand
&MOSrc
= CopyLike
.getOperand(1);
908 Src
= RegSubRegPair(MOSrc
.getReg(), MOSrc
.getSubReg());
909 // What we track are the alternative sources of the definition.
910 const MachineOperand
&MODef
= CopyLike
.getOperand(0);
911 Dst
= RegSubRegPair(MODef
.getReg(), MODef
.getSubReg());
915 bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) override
{
916 if (CurrentSrcIdx
!= 1)
918 MachineOperand
&MOSrc
= CopyLike
.getOperand(CurrentSrcIdx
);
919 MOSrc
.setReg(NewReg
);
920 MOSrc
.setSubReg(NewSubReg
);
925 /// Helper class to rewrite uncoalescable copy like instructions
926 /// into new COPY (coalescable friendly) instructions.
927 class UncoalescableRewriter
: public Rewriter
{
928 unsigned NumDefs
; ///< Number of defs in the bitcast.
931 UncoalescableRewriter(MachineInstr
&MI
) : Rewriter(MI
) {
932 NumDefs
= MI
.getDesc().getNumDefs();
935 /// \see See Rewriter::getNextRewritableSource()
936 /// All such sources need to be considered rewritable in order to
937 /// rewrite a uncoalescable copy-like instruction. This method return
938 /// each definition that must be checked if rewritable.
939 bool getNextRewritableSource(RegSubRegPair
&Src
,
940 RegSubRegPair
&Dst
) override
{
941 // Find the next non-dead definition and continue from there.
942 if (CurrentSrcIdx
== NumDefs
)
945 while (CopyLike
.getOperand(CurrentSrcIdx
).isDead()) {
947 if (CurrentSrcIdx
== NumDefs
)
951 // What we track are the alternative sources of the definition.
952 Src
= RegSubRegPair(0, 0);
953 const MachineOperand
&MODef
= CopyLike
.getOperand(CurrentSrcIdx
);
954 Dst
= RegSubRegPair(MODef
.getReg(), MODef
.getSubReg());
960 bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) override
{
965 /// Specialized rewriter for INSERT_SUBREG instruction.
966 class InsertSubregRewriter
: public Rewriter
{
968 InsertSubregRewriter(MachineInstr
&MI
) : Rewriter(MI
) {
969 assert(MI
.isInsertSubreg() && "Invalid instruction");
972 /// \see See Rewriter::getNextRewritableSource()
973 /// Here CopyLike has the following form:
974 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
975 /// Src1 has the same register class has dst, hence, there is
976 /// nothing to rewrite.
977 /// Src2.src2SubIdx, may not be register coalescer friendly.
978 /// Therefore, the first call to this method returns:
979 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
980 /// (DstReg, DstSubReg) = (dst, subIdx).
982 /// Subsequence calls will return false.
983 bool getNextRewritableSource(RegSubRegPair
&Src
,
984 RegSubRegPair
&Dst
) override
{
985 // If we already get the only source we can rewrite, return false.
986 if (CurrentSrcIdx
== 2)
988 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
990 const MachineOperand
&MOInsertedReg
= CopyLike
.getOperand(2);
991 Src
= RegSubRegPair(MOInsertedReg
.getReg(), MOInsertedReg
.getSubReg());
992 const MachineOperand
&MODef
= CopyLike
.getOperand(0);
994 // We want to track something that is compatible with the
995 // partial definition.
996 if (MODef
.getSubReg())
997 // Bail if we have to compose sub-register indices.
999 Dst
= RegSubRegPair(MODef
.getReg(),
1000 (unsigned)CopyLike
.getOperand(3).getImm());
1004 bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) override
{
1005 if (CurrentSrcIdx
!= 2)
1007 // We are rewriting the inserted reg.
1008 MachineOperand
&MO
= CopyLike
.getOperand(CurrentSrcIdx
);
1010 MO
.setSubReg(NewSubReg
);
1015 /// Specialized rewriter for EXTRACT_SUBREG instruction.
1016 class ExtractSubregRewriter
: public Rewriter
{
1017 const TargetInstrInfo
&TII
;
1020 ExtractSubregRewriter(MachineInstr
&MI
, const TargetInstrInfo
&TII
)
1021 : Rewriter(MI
), TII(TII
) {
1022 assert(MI
.isExtractSubreg() && "Invalid instruction");
1025 /// \see Rewriter::getNextRewritableSource()
1026 /// Here CopyLike has the following form:
1027 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1028 /// There is only one rewritable source: Src.subIdx,
1029 /// which defines dst.dstSubIdx.
1030 bool getNextRewritableSource(RegSubRegPair
&Src
,
1031 RegSubRegPair
&Dst
) override
{
1032 // If we already get the only source we can rewrite, return false.
1033 if (CurrentSrcIdx
== 1)
1035 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1037 const MachineOperand
&MOExtractedReg
= CopyLike
.getOperand(1);
1038 // If we have to compose sub-register indices, bail out.
1039 if (MOExtractedReg
.getSubReg())
1042 Src
= RegSubRegPair(MOExtractedReg
.getReg(),
1043 CopyLike
.getOperand(2).getImm());
1045 // We want to track something that is compatible with the definition.
1046 const MachineOperand
&MODef
= CopyLike
.getOperand(0);
1047 Dst
= RegSubRegPair(MODef
.getReg(), MODef
.getSubReg());
1051 bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) override
{
1052 // The only source we can rewrite is the input register.
1053 if (CurrentSrcIdx
!= 1)
1056 CopyLike
.getOperand(CurrentSrcIdx
).setReg(NewReg
);
1058 // If we find a source that does not require to extract something,
1059 // rewrite the operation with a copy.
1061 // Move the current index to an invalid position.
1062 // We do not want another call to this method to be able
1063 // to do any change.
1065 // Rewrite the operation as a COPY.
1066 // Get rid of the sub-register index.
1067 CopyLike
.removeOperand(2);
1068 // Morph the operation into a COPY.
1069 CopyLike
.setDesc(TII
.get(TargetOpcode::COPY
));
1072 CopyLike
.getOperand(CurrentSrcIdx
+ 1).setImm(NewSubReg
);
1077 /// Specialized rewriter for REG_SEQUENCE instruction.
1078 class RegSequenceRewriter
: public Rewriter
{
1080 RegSequenceRewriter(MachineInstr
&MI
) : Rewriter(MI
) {
1081 assert(MI
.isRegSequence() && "Invalid instruction");
1084 /// \see Rewriter::getNextRewritableSource()
1085 /// Here CopyLike has the following form:
1086 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1087 /// Each call will return a different source, walking all the available
1090 /// The first call returns:
1091 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1092 /// (DstReg, DstSubReg) = (dst, subIdx1).
1094 /// The second call returns:
1095 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1096 /// (DstReg, DstSubReg) = (dst, subIdx2).
1098 /// And so on, until all the sources have been traversed, then
1099 /// it returns false.
1100 bool getNextRewritableSource(RegSubRegPair
&Src
,
1101 RegSubRegPair
&Dst
) override
{
1102 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1104 // If this is the first call, move to the first argument.
1105 if (CurrentSrcIdx
== 0) {
1108 // Otherwise, move to the next argument and check that it is valid.
1110 if (CurrentSrcIdx
>= CopyLike
.getNumOperands())
1113 const MachineOperand
&MOInsertedReg
= CopyLike
.getOperand(CurrentSrcIdx
);
1114 Src
.Reg
= MOInsertedReg
.getReg();
1115 // If we have to compose sub-register indices, bail out.
1116 if ((Src
.SubReg
= MOInsertedReg
.getSubReg()))
1119 // We want to track something that is compatible with the related
1120 // partial definition.
1121 Dst
.SubReg
= CopyLike
.getOperand(CurrentSrcIdx
+ 1).getImm();
1123 const MachineOperand
&MODef
= CopyLike
.getOperand(0);
1124 Dst
.Reg
= MODef
.getReg();
1125 // If we have to compose sub-registers, bail.
1126 return MODef
.getSubReg() == 0;
1129 bool RewriteCurrentSource(Register NewReg
, unsigned NewSubReg
) override
{
1130 // We cannot rewrite out of bound operands.
1131 // Moreover, rewritable sources are at odd positions.
1132 if ((CurrentSrcIdx
& 1) != 1 || CurrentSrcIdx
> CopyLike
.getNumOperands())
1135 MachineOperand
&MO
= CopyLike
.getOperand(CurrentSrcIdx
);
1137 MO
.setSubReg(NewSubReg
);
1142 } // end anonymous namespace
1144 /// Get the appropriated Rewriter for \p MI.
1145 /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
1146 /// rewriter works for \p MI.
1147 static Rewriter
*getCopyRewriter(MachineInstr
&MI
, const TargetInstrInfo
&TII
) {
1148 // Handle uncoalescable copy-like instructions.
1149 if (MI
.isBitcast() || MI
.isRegSequenceLike() || MI
.isInsertSubregLike() ||
1150 MI
.isExtractSubregLike())
1151 return new UncoalescableRewriter(MI
);
1153 switch (MI
.getOpcode()) {
1156 case TargetOpcode::COPY
:
1157 return new CopyRewriter(MI
);
1158 case TargetOpcode::INSERT_SUBREG
:
1159 return new InsertSubregRewriter(MI
);
1160 case TargetOpcode::EXTRACT_SUBREG
:
1161 return new ExtractSubregRewriter(MI
, TII
);
1162 case TargetOpcode::REG_SEQUENCE
:
1163 return new RegSequenceRewriter(MI
);
1167 /// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1168 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
1169 /// multiple sources for a given \p Def are found along the way, we found a
1170 /// PHI instructions that needs to be rewritten.
1171 /// TODO: HandleMultipleSources should be removed once we test PHI handling
1172 /// with coalescable copies.
1173 static RegSubRegPair
1174 getNewSource(MachineRegisterInfo
*MRI
, const TargetInstrInfo
*TII
,
1176 const PeepholeOptimizer::RewriteMapTy
&RewriteMap
,
1177 bool HandleMultipleSources
= true) {
1178 RegSubRegPair
LookupSrc(Def
.Reg
, Def
.SubReg
);
1180 ValueTrackerResult Res
= RewriteMap
.lookup(LookupSrc
);
1181 // If there are no entries on the map, LookupSrc is the new source.
1185 // There's only one source for this definition, keep searching...
1186 unsigned NumSrcs
= Res
.getNumSources();
1188 LookupSrc
.Reg
= Res
.getSrcReg(0);
1189 LookupSrc
.SubReg
= Res
.getSrcSubReg(0);
1193 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1194 if (!HandleMultipleSources
)
1197 // Multiple sources, recurse into each source to find a new source
1198 // for it. Then, rewrite the PHI accordingly to its new edges.
1199 SmallVector
<RegSubRegPair
, 4> NewPHISrcs
;
1200 for (unsigned i
= 0; i
< NumSrcs
; ++i
) {
1201 RegSubRegPair
PHISrc(Res
.getSrcReg(i
), Res
.getSrcSubReg(i
));
1202 NewPHISrcs
.push_back(
1203 getNewSource(MRI
, TII
, PHISrc
, RewriteMap
, HandleMultipleSources
));
1206 // Build the new PHI node and return its def register as the new source.
1207 MachineInstr
&OrigPHI
= const_cast<MachineInstr
&>(*Res
.getInst());
1208 MachineInstr
&NewPHI
= insertPHI(*MRI
, *TII
, NewPHISrcs
, OrigPHI
);
1209 LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1210 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI
);
1211 LLVM_DEBUG(dbgs() << " With: " << NewPHI
);
1212 const MachineOperand
&MODef
= NewPHI
.getOperand(0);
1213 return RegSubRegPair(MODef
.getReg(), MODef
.getSubReg());
1216 return RegSubRegPair(0, 0);
1219 /// Optimize generic copy instructions to avoid cross register bank copy.
1220 /// The optimization looks through a chain of copies and tries to find a source
1221 /// that has a compatible register class.
1222 /// Two register classes are considered to be compatible if they share the same
1224 /// New copies issued by this optimization are register allocator
1225 /// friendly. This optimization does not remove any copy as it may
1226 /// overconstrain the register allocator, but replaces some operands
1228 /// \pre isCoalescableCopy(*MI) is true.
1229 /// \return True, when \p MI has been rewritten. False otherwise.
1230 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr
&MI
) {
1231 assert(isCoalescableCopy(MI
) && "Invalid argument");
1232 assert(MI
.getDesc().getNumDefs() == 1 &&
1233 "Coalescer can understand multiple defs?!");
1234 const MachineOperand
&MODef
= MI
.getOperand(0);
1235 // Do not rewrite physical definitions.
1236 if (MODef
.getReg().isPhysical())
1239 bool Changed
= false;
1240 // Get the right rewriter for the current copy.
1241 std::unique_ptr
<Rewriter
> CpyRewriter(getCopyRewriter(MI
, *TII
));
1242 // If none exists, bail out.
1245 // Rewrite each rewritable source.
1247 RegSubRegPair TrackPair
;
1248 while (CpyRewriter
->getNextRewritableSource(Src
, TrackPair
)) {
1249 // Keep track of PHI nodes and its incoming edges when looking for sources.
1250 RewriteMapTy RewriteMap
;
1251 // Try to find a more suitable source. If we failed to do so, or get the
1252 // actual source, move to the next source.
1253 if (!findNextSource(TrackPair
, RewriteMap
))
1256 // Get the new source to rewrite. TODO: Only enable handling of multiple
1257 // sources (PHIs) once we have a motivating example and testcases for it.
1258 RegSubRegPair NewSrc
= getNewSource(MRI
, TII
, TrackPair
, RewriteMap
,
1259 /*HandleMultipleSources=*/false);
1260 if (Src
.Reg
== NewSrc
.Reg
|| NewSrc
.Reg
== 0)
1264 if (CpyRewriter
->RewriteCurrentSource(NewSrc
.Reg
, NewSrc
.SubReg
)) {
1265 // We may have extended the live-range of NewSrc, account for that.
1266 MRI
->clearKillFlags(NewSrc
.Reg
);
1270 // TODO: We could have a clean-up method to tidy the instruction.
1271 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1273 // Currently we haven't seen motivating example for that and we
1274 // want to avoid untested code.
1275 NumRewrittenCopies
+= Changed
;
1279 /// Rewrite the source found through \p Def, by using the \p RewriteMap
1280 /// and create a new COPY instruction. More info about RewriteMap in
1281 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1282 /// Uncoalescable copies, since they are copy like instructions that aren't
1283 /// recognized by the register allocator.
1285 PeepholeOptimizer::rewriteSource(MachineInstr
&CopyLike
,
1286 RegSubRegPair Def
, RewriteMapTy
&RewriteMap
) {
1287 assert(!Def
.Reg
.isPhysical() && "We do not rewrite physical registers");
1289 // Find the new source to use in the COPY rewrite.
1290 RegSubRegPair NewSrc
= getNewSource(MRI
, TII
, Def
, RewriteMap
);
1293 const TargetRegisterClass
*DefRC
= MRI
->getRegClass(Def
.Reg
);
1294 Register NewVReg
= MRI
->createVirtualRegister(DefRC
);
1296 MachineInstr
*NewCopy
=
1297 BuildMI(*CopyLike
.getParent(), &CopyLike
, CopyLike
.getDebugLoc(),
1298 TII
->get(TargetOpcode::COPY
), NewVReg
)
1299 .addReg(NewSrc
.Reg
, 0, NewSrc
.SubReg
);
1302 NewCopy
->getOperand(0).setSubReg(Def
.SubReg
);
1303 NewCopy
->getOperand(0).setIsUndef();
1306 LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1307 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike
);
1308 LLVM_DEBUG(dbgs() << " With: " << *NewCopy
);
1309 MRI
->replaceRegWith(Def
.Reg
, NewVReg
);
1310 MRI
->clearKillFlags(NewVReg
);
1312 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1313 // account for that.
1314 MRI
->clearKillFlags(NewSrc
.Reg
);
1319 /// Optimize copy-like instructions to create
1320 /// register coalescer friendly instruction.
1321 /// The optimization tries to kill-off the \p MI by looking
1322 /// through a chain of copies to find a source that has a compatible
1324 /// If such a source is found, it replace \p MI by a generic COPY
1326 /// \pre isUncoalescableCopy(*MI) is true.
1327 /// \return True, when \p MI has been optimized. In that case, \p MI has
1328 /// been removed from its parent.
1329 /// All COPY instructions created, are inserted in \p LocalMIs.
1330 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1331 MachineInstr
&MI
, SmallPtrSetImpl
<MachineInstr
*> &LocalMIs
) {
1332 assert(isUncoalescableCopy(MI
) && "Invalid argument");
1333 UncoalescableRewriter
CpyRewriter(MI
);
1335 // Rewrite each rewritable source by generating new COPYs. This works
1336 // differently from optimizeCoalescableCopy since it first makes sure that all
1337 // definitions can be rewritten.
1338 RewriteMapTy RewriteMap
;
1341 SmallVector
<RegSubRegPair
, 4> RewritePairs
;
1342 while (CpyRewriter
.getNextRewritableSource(Src
, Def
)) {
1343 // If a physical register is here, this is probably for a good reason.
1344 // Do not rewrite that.
1345 if (Def
.Reg
.isPhysical())
1348 // If we do not know how to rewrite this definition, there is no point
1349 // in trying to kill this instruction.
1350 if (!findNextSource(Def
, RewriteMap
))
1353 RewritePairs
.push_back(Def
);
1356 // The change is possible for all defs, do it.
1357 for (const RegSubRegPair
&Def
: RewritePairs
) {
1358 // Rewrite the "copy" in a way the register coalescer understands.
1359 MachineInstr
&NewCopy
= rewriteSource(MI
, Def
, RewriteMap
);
1360 LocalMIs
.insert(&NewCopy
);
1364 LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI
);
1365 MI
.eraseFromParent();
1366 ++NumUncoalescableCopies
;
1370 /// Check whether MI is a candidate for folding into a later instruction.
1371 /// We only fold loads to virtual registers and the virtual register defined
1372 /// has a single user.
1373 bool PeepholeOptimizer::isLoadFoldable(
1374 MachineInstr
&MI
, SmallSet
<Register
, 16> &FoldAsLoadDefCandidates
) {
1375 if (!MI
.canFoldAsLoad() || !MI
.mayLoad())
1377 const MCInstrDesc
&MCID
= MI
.getDesc();
1378 if (MCID
.getNumDefs() != 1)
1381 Register Reg
= MI
.getOperand(0).getReg();
1382 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1383 // loads. It should be checked when processing uses of the load, since
1384 // uses can be removed during peephole.
1385 if (Reg
.isVirtual() && !MI
.getOperand(0).getSubReg() &&
1386 MRI
->hasOneNonDBGUser(Reg
)) {
1387 FoldAsLoadDefCandidates
.insert(Reg
);
1393 bool PeepholeOptimizer::isMoveImmediate(
1394 MachineInstr
&MI
, SmallSet
<Register
, 4> &ImmDefRegs
,
1395 DenseMap
<Register
, MachineInstr
*> &ImmDefMIs
) {
1396 const MCInstrDesc
&MCID
= MI
.getDesc();
1397 if (MCID
.getNumDefs() != 1 || !MI
.getOperand(0).isReg())
1399 Register Reg
= MI
.getOperand(0).getReg();
1400 if (!Reg
.isVirtual())
1404 if (!MI
.isMoveImmediate() && !TII
->getConstValDefinedInReg(MI
, Reg
, ImmVal
))
1407 ImmDefMIs
.insert(std::make_pair(Reg
, &MI
));
1408 ImmDefRegs
.insert(Reg
);
1412 /// Try folding register operands that are defined by move immediate
1413 /// instructions, i.e. a trivial constant folding optimization, if
1414 /// and only if the def and use are in the same BB.
1415 bool PeepholeOptimizer::foldImmediate(
1416 MachineInstr
&MI
, SmallSet
<Register
, 4> &ImmDefRegs
,
1417 DenseMap
<Register
, MachineInstr
*> &ImmDefMIs
, bool &Deleted
) {
1419 for (unsigned i
= 0, e
= MI
.getDesc().getNumOperands(); i
!= e
; ++i
) {
1420 MachineOperand
&MO
= MI
.getOperand(i
);
1421 if (!MO
.isReg() || MO
.isDef())
1423 Register Reg
= MO
.getReg();
1424 if (!Reg
.isVirtual())
1426 if (ImmDefRegs
.count(Reg
) == 0)
1428 DenseMap
<Register
, MachineInstr
*>::iterator II
= ImmDefMIs
.find(Reg
);
1429 assert(II
!= ImmDefMIs
.end() && "couldn't find immediate definition");
1430 if (TII
->foldImmediate(MI
, *II
->second
, Reg
, MRI
)) {
1432 // foldImmediate can delete ImmDefMI if MI was its only user. If ImmDefMI
1433 // is not deleted, and we happened to get a same MI, we can delete MI and
1434 // replace its users.
1435 if (MRI
->getVRegDef(Reg
) &&
1436 MI
.isIdenticalTo(*II
->second
, MachineInstr::IgnoreVRegDefs
)) {
1437 Register DstReg
= MI
.getOperand(0).getReg();
1438 if (DstReg
.isVirtual() &&
1439 MRI
->getRegClass(DstReg
) == MRI
->getRegClass(Reg
)) {
1440 MRI
->replaceRegWith(DstReg
, Reg
);
1441 MI
.eraseFromParent();
1451 // FIXME: This is very simple and misses some cases which should be handled when
1452 // motivating examples are found.
1454 // The copy rewriting logic should look at uses as well as defs and be able to
1455 // eliminate copies across blocks.
1457 // Later copies that are subregister extracts will also not be eliminated since
1458 // only the first copy is considered.
1462 // %2 = COPY %0:sub1
1464 // Should replace %2 uses with %1:sub1
1465 bool PeepholeOptimizer::foldRedundantCopy(MachineInstr
&MI
) {
1466 assert(MI
.isCopy() && "expected a COPY machine instruction");
1468 RegSubRegPair SrcPair
;
1469 if (!getCopySrc(MI
, SrcPair
))
1472 Register DstReg
= MI
.getOperand(0).getReg();
1473 if (!DstReg
.isVirtual())
1476 if (CopySrcMIs
.insert(std::make_pair(SrcPair
, &MI
)).second
) {
1477 // First copy of this reg seen.
1481 MachineInstr
*PrevCopy
= CopySrcMIs
.find(SrcPair
)->second
;
1483 assert(SrcPair
.SubReg
== PrevCopy
->getOperand(1).getSubReg() &&
1484 "Unexpected mismatching subreg!");
1486 Register PrevDstReg
= PrevCopy
->getOperand(0).getReg();
1488 // Only replace if the copy register class is the same.
1490 // TODO: If we have multiple copies to different register classes, we may want
1491 // to track multiple copies of the same source register.
1492 if (MRI
->getRegClass(DstReg
) != MRI
->getRegClass(PrevDstReg
))
1495 MRI
->replaceRegWith(DstReg
, PrevDstReg
);
1497 // Lifetime of the previous copy has been extended.
1498 MRI
->clearKillFlags(PrevDstReg
);
1502 bool PeepholeOptimizer::isNAPhysCopy(Register Reg
) {
1503 return Reg
.isPhysical() && !MRI
->isAllocatable(Reg
);
1506 bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1507 MachineInstr
&MI
, DenseMap
<Register
, MachineInstr
*> &NAPhysToVirtMIs
) {
1508 assert(MI
.isCopy() && "expected a COPY machine instruction");
1510 if (DisableNAPhysCopyOpt
)
1513 Register DstReg
= MI
.getOperand(0).getReg();
1514 Register SrcReg
= MI
.getOperand(1).getReg();
1515 if (isNAPhysCopy(SrcReg
) && DstReg
.isVirtual()) {
1516 // %vreg = COPY $physreg
1517 // Avoid using a datastructure which can track multiple live non-allocatable
1518 // phys->virt copies since LLVM doesn't seem to do this.
1519 NAPhysToVirtMIs
.insert({SrcReg
, &MI
});
1523 if (!(SrcReg
.isVirtual() && isNAPhysCopy(DstReg
)))
1526 // $physreg = COPY %vreg
1527 auto PrevCopy
= NAPhysToVirtMIs
.find(DstReg
);
1528 if (PrevCopy
== NAPhysToVirtMIs
.end()) {
1529 // We can't remove the copy: there was an intervening clobber of the
1530 // non-allocatable physical register after the copy to virtual.
1531 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1536 Register PrevDstReg
= PrevCopy
->second
->getOperand(0).getReg();
1537 if (PrevDstReg
== SrcReg
) {
1538 // Remove the virt->phys copy: we saw the virtual register definition, and
1539 // the non-allocatable physical register's state hasn't changed since then.
1540 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI
);
1545 // Potential missed optimization opportunity: we saw a different virtual
1546 // register get a copy of the non-allocatable physical register, and we only
1547 // track one such copy. Avoid getting confused by this new non-allocatable
1548 // physical register definition, and remove it from the tracked copies.
1549 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI
);
1550 NAPhysToVirtMIs
.erase(PrevCopy
);
1554 /// \bried Returns true if \p MO is a virtual register operand.
1555 static bool isVirtualRegisterOperand(MachineOperand
&MO
) {
1556 return MO
.isReg() && MO
.getReg().isVirtual();
1559 bool PeepholeOptimizer::findTargetRecurrence(
1560 Register Reg
, const SmallSet
<Register
, 2> &TargetRegs
,
1561 RecurrenceCycle
&RC
) {
1562 // Recurrence found if Reg is in TargetRegs.
1563 if (TargetRegs
.count(Reg
))
1566 // TODO: Curerntly, we only allow the last instruction of the recurrence
1567 // cycle (the instruction that feeds the PHI instruction) to have more than
1568 // one uses to guarantee that commuting operands does not tie registers
1569 // with overlapping live range. Once we have actual live range info of
1570 // each register, this constraint can be relaxed.
1571 if (!MRI
->hasOneNonDBGUse(Reg
))
1574 // Give up if the reccurrence chain length is longer than the limit.
1575 if (RC
.size() >= MaxRecurrenceChain
)
1578 MachineInstr
&MI
= *(MRI
->use_instr_nodbg_begin(Reg
));
1579 unsigned Idx
= MI
.findRegisterUseOperandIdx(Reg
, /*TRI=*/nullptr);
1581 // Only interested in recurrences whose instructions have only one def, which
1582 // is a virtual register.
1583 if (MI
.getDesc().getNumDefs() != 1)
1586 MachineOperand
&DefOp
= MI
.getOperand(0);
1587 if (!isVirtualRegisterOperand(DefOp
))
1590 // Check if def operand of MI is tied to any use operand. We are only
1591 // interested in the case that all the instructions in the recurrence chain
1592 // have there def operand tied with one of the use operand.
1593 unsigned TiedUseIdx
;
1594 if (!MI
.isRegTiedToUseOperand(0, &TiedUseIdx
))
1597 if (Idx
== TiedUseIdx
) {
1598 RC
.push_back(RecurrenceInstr(&MI
));
1599 return findTargetRecurrence(DefOp
.getReg(), TargetRegs
, RC
);
1601 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1602 unsigned CommIdx
= TargetInstrInfo::CommuteAnyOperandIndex
;
1603 if (TII
->findCommutedOpIndices(MI
, Idx
, CommIdx
) && CommIdx
== TiedUseIdx
) {
1604 RC
.push_back(RecurrenceInstr(&MI
, Idx
, CommIdx
));
1605 return findTargetRecurrence(DefOp
.getReg(), TargetRegs
, RC
);
1612 /// Phi instructions will eventually be lowered to copy instructions.
1613 /// If phi is in a loop header, a recurrence may formulated around the source
1614 /// and destination of the phi. For such case commuting operands of the
1615 /// instructions in the recurrence may enable coalescing of the copy instruction
1616 /// generated from the phi. For example, if there is a recurrence of
1619 /// %1 = phi(%0, %100)
1621 /// %0<def, tied1> = ADD %2<def, tied0>, %1
1623 /// , the fact that %0 and %2 are in the same tied operands set makes
1624 /// the coalescing of copy instruction generated from the phi in
1625 /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1626 /// %2 have overlapping live range. This introduces additional move
1627 /// instruction to the final assembly. However, if we commute %2 and
1628 /// %1 of ADD instruction, the redundant move instruction can be
1630 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr
&PHI
) {
1631 SmallSet
<Register
, 2> TargetRegs
;
1632 for (unsigned Idx
= 1; Idx
< PHI
.getNumOperands(); Idx
+= 2) {
1633 MachineOperand
&MO
= PHI
.getOperand(Idx
);
1634 assert(isVirtualRegisterOperand(MO
) && "Invalid PHI instruction");
1635 TargetRegs
.insert(MO
.getReg());
1638 bool Changed
= false;
1640 if (findTargetRecurrence(PHI
.getOperand(0).getReg(), TargetRegs
, RC
)) {
1641 // Commutes operands of instructions in RC if necessary so that the copy to
1642 // be generated from PHI can be coalesced.
1643 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI
);
1644 for (auto &RI
: RC
) {
1645 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI
.getMI()));
1646 auto CP
= RI
.getCommutePair();
1649 TII
->commuteInstruction(*(RI
.getMI()), false, (*CP
).first
,
1651 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI
.getMI()));
1659 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction
&MF
) {
1660 if (skipFunction(MF
.getFunction()))
1663 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1664 LLVM_DEBUG(dbgs() << "********** Function: " << MF
.getName() << '\n');
1666 if (DisablePeephole
)
1669 TII
= MF
.getSubtarget().getInstrInfo();
1670 TRI
= MF
.getSubtarget().getRegisterInfo();
1671 MRI
= &MF
.getRegInfo();
1672 DT
= Aggressive
? &getAnalysis
<MachineDominatorTreeWrapperPass
>().getDomTree()
1674 MLI
= &getAnalysis
<MachineLoopInfoWrapperPass
>().getLI();
1675 MF
.setDelegate(this);
1677 bool Changed
= false;
1679 for (MachineBasicBlock
&MBB
: MF
) {
1680 bool SeenMoveImm
= false;
1682 // During this forward scan, at some point it needs to answer the question
1683 // "given a pointer to an MI in the current BB, is it located before or
1684 // after the current instruction".
1685 // To perform this, the following set keeps track of the MIs already seen
1686 // during the scan, if a MI is not in the set, it is assumed to be located
1687 // after. Newly created MIs have to be inserted in the set as well.
1688 SmallPtrSet
<MachineInstr
*, 16> LocalMIs
;
1689 SmallSet
<Register
, 4> ImmDefRegs
;
1690 DenseMap
<Register
, MachineInstr
*> ImmDefMIs
;
1691 SmallSet
<Register
, 16> FoldAsLoadDefCandidates
;
1693 // Track when a non-allocatable physical register is copied to a virtual
1694 // register so that useless moves can be removed.
1696 // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
1697 // without any intervening re-definition of $physreg.
1698 DenseMap
<Register
, MachineInstr
*> NAPhysToVirtMIs
;
1702 bool IsLoopHeader
= MLI
->isLoopHeader(&MBB
);
1704 for (MachineBasicBlock::iterator MII
= MBB
.begin(), MIE
= MBB
.end();
1706 MachineInstr
*MI
= &*MII
;
1707 // We may be erasing MI below, increment MII now.
1709 LocalMIs
.insert(MI
);
1711 // Skip debug instructions. They should not affect this peephole
1713 if (MI
->isDebugInstr())
1716 if (MI
->isPosition())
1719 if (IsLoopHeader
&& MI
->isPHI()) {
1720 if (optimizeRecurrence(*MI
)) {
1726 if (!MI
->isCopy()) {
1727 for (const MachineOperand
&MO
: MI
->operands()) {
1728 // Visit all operands: definitions can be implicit or explicit.
1730 Register Reg
= MO
.getReg();
1731 if (MO
.isDef() && isNAPhysCopy(Reg
)) {
1732 const auto &Def
= NAPhysToVirtMIs
.find(Reg
);
1733 if (Def
!= NAPhysToVirtMIs
.end()) {
1734 // A new definition of the non-allocatable physical register
1735 // invalidates previous copies.
1737 << "NAPhysCopy: invalidating because of " << *MI
);
1738 NAPhysToVirtMIs
.erase(Def
);
1741 } else if (MO
.isRegMask()) {
1742 const uint32_t *RegMask
= MO
.getRegMask();
1743 for (auto &RegMI
: NAPhysToVirtMIs
) {
1744 Register Def
= RegMI
.first
;
1745 if (MachineOperand::clobbersPhysReg(RegMask
, Def
)) {
1747 << "NAPhysCopy: invalidating because of " << *MI
);
1748 NAPhysToVirtMIs
.erase(Def
);
1755 if (MI
->isImplicitDef() || MI
->isKill())
1758 if (MI
->isInlineAsm() || MI
->hasUnmodeledSideEffects()) {
1759 // Blow away all non-allocatable physical registers knowledge since we
1760 // don't know what's correct anymore.
1762 // FIXME: handle explicit asm clobbers.
1763 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1765 NAPhysToVirtMIs
.clear();
1768 if ((isUncoalescableCopy(*MI
) &&
1769 optimizeUncoalescableCopy(*MI
, LocalMIs
)) ||
1770 (MI
->isCompare() && optimizeCmpInstr(*MI
)) ||
1771 (MI
->isSelect() && optimizeSelect(*MI
, LocalMIs
))) {
1778 if (MI
->isConditionalBranch() && optimizeCondBranch(*MI
)) {
1783 if (isCoalescableCopy(*MI
) && optimizeCoalescableCopy(*MI
)) {
1784 // MI is just rewritten.
1789 if (MI
->isCopy() && (foldRedundantCopy(*MI
) ||
1790 foldRedundantNAPhysCopy(*MI
, NAPhysToVirtMIs
))) {
1792 LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI
<< "\n");
1793 MI
->eraseFromParent();
1798 if (isMoveImmediate(*MI
, ImmDefRegs
, ImmDefMIs
)) {
1801 Changed
|= optimizeExtInstr(*MI
, MBB
, LocalMIs
);
1802 // optimizeExtInstr might have created new instructions after MI
1803 // and before the already incremented MII. Adjust MII so that the
1804 // next iteration sees the new instructions.
1809 Changed
|= foldImmediate(*MI
, ImmDefRegs
, ImmDefMIs
, Deleted
);
1817 // Check whether MI is a load candidate for folding into a later
1818 // instruction. If MI is not a candidate, check whether we can fold an
1819 // earlier load into MI.
1820 if (!isLoadFoldable(*MI
, FoldAsLoadDefCandidates
) &&
1821 !FoldAsLoadDefCandidates
.empty()) {
1823 // We visit each operand even after successfully folding a previous
1824 // one. This allows us to fold multiple loads into a single
1825 // instruction. We do assume that optimizeLoadInstr doesn't insert
1826 // foldable uses earlier in the argument list. Since we don't restart
1827 // iteration, we'd miss such cases.
1828 const MCInstrDesc
&MIDesc
= MI
->getDesc();
1829 for (unsigned i
= MIDesc
.getNumDefs(); i
!= MI
->getNumOperands();
1831 const MachineOperand
&MOp
= MI
->getOperand(i
);
1834 Register FoldAsLoadDefReg
= MOp
.getReg();
1835 if (FoldAsLoadDefCandidates
.count(FoldAsLoadDefReg
)) {
1836 // We need to fold load after optimizeCmpInstr, since
1837 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1838 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1839 // we need it for markUsesInDebugValueAsUndef().
1840 Register FoldedReg
= FoldAsLoadDefReg
;
1841 MachineInstr
*DefMI
= nullptr;
1842 if (MachineInstr
*FoldMI
=
1843 TII
->optimizeLoadInstr(*MI
, MRI
, FoldAsLoadDefReg
, DefMI
)) {
1844 // Update LocalMIs since we replaced MI with FoldMI and deleted
1846 LLVM_DEBUG(dbgs() << "Replacing: " << *MI
);
1847 LLVM_DEBUG(dbgs() << " With: " << *FoldMI
);
1849 LocalMIs
.erase(DefMI
);
1850 LocalMIs
.insert(FoldMI
);
1851 // Update the call site info.
1852 if (MI
->shouldUpdateCallSiteInfo())
1853 MI
->getMF()->moveCallSiteInfo(MI
, FoldMI
);
1854 MI
->eraseFromParent();
1855 DefMI
->eraseFromParent();
1856 MRI
->markUsesInDebugValueAsUndef(FoldedReg
);
1857 FoldAsLoadDefCandidates
.erase(FoldedReg
);
1860 // MI is replaced with FoldMI so we can continue trying to fold
1868 // If we run into an instruction we can't fold across, discard
1869 // the load candidates. Note: We might be able to fold *into* this
1870 // instruction, so this needs to be after the folding logic.
1871 if (MI
->isLoadFoldBarrier()) {
1872 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI
);
1873 FoldAsLoadDefCandidates
.clear();
1878 MF
.resetDelegate(this);
1882 ValueTrackerResult
ValueTracker::getNextSourceFromCopy() {
1883 assert(Def
->isCopy() && "Invalid definition");
1884 // Copy instruction are supposed to be: Def = Src.
1885 // If someone breaks this assumption, bad things will happen everywhere.
1886 // There may be implicit uses preventing the copy to be moved across
1887 // some target specific register definitions
1888 assert(Def
->getNumOperands() - Def
->getNumImplicitOperands() == 2 &&
1889 "Invalid number of operands");
1890 assert(!Def
->hasImplicitDef() && "Only implicit uses are allowed");
1892 if (Def
->getOperand(DefIdx
).getSubReg() != DefSubReg
)
1893 // If we look for a different subreg, it means we want a subreg of src.
1894 // Bails as we do not support composing subregs yet.
1895 return ValueTrackerResult();
1896 // Otherwise, we want the whole source.
1897 const MachineOperand
&Src
= Def
->getOperand(1);
1899 return ValueTrackerResult();
1900 return ValueTrackerResult(Src
.getReg(), Src
.getSubReg());
1903 ValueTrackerResult
ValueTracker::getNextSourceFromBitcast() {
1904 assert(Def
->isBitcast() && "Invalid definition");
1906 // Bail if there are effects that a plain copy will not expose.
1907 if (Def
->mayRaiseFPException() || Def
->hasUnmodeledSideEffects())
1908 return ValueTrackerResult();
1910 // Bitcasts with more than one def are not supported.
1911 if (Def
->getDesc().getNumDefs() != 1)
1912 return ValueTrackerResult();
1913 const MachineOperand DefOp
= Def
->getOperand(DefIdx
);
1914 if (DefOp
.getSubReg() != DefSubReg
)
1915 // If we look for a different subreg, it means we want a subreg of the src.
1916 // Bails as we do not support composing subregs yet.
1917 return ValueTrackerResult();
1919 unsigned SrcIdx
= Def
->getNumOperands();
1920 for (unsigned OpIdx
= DefIdx
+ 1, EndOpIdx
= SrcIdx
; OpIdx
!= EndOpIdx
;
1922 const MachineOperand
&MO
= Def
->getOperand(OpIdx
);
1923 if (!MO
.isReg() || !MO
.getReg())
1925 // Ignore dead implicit defs.
1926 if (MO
.isImplicit() && MO
.isDead())
1928 assert(!MO
.isDef() && "We should have skipped all the definitions by now");
1929 if (SrcIdx
!= EndOpIdx
)
1930 // Multiple sources?
1931 return ValueTrackerResult();
1935 // In some rare case, Def has no input, SrcIdx is out of bound,
1936 // getOperand(SrcIdx) will fail below.
1937 if (SrcIdx
>= Def
->getNumOperands())
1938 return ValueTrackerResult();
1940 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1941 // will break the assumed guarantees for the upper bits.
1942 for (const MachineInstr
&UseMI
: MRI
.use_nodbg_instructions(DefOp
.getReg())) {
1943 if (UseMI
.isSubregToReg())
1944 return ValueTrackerResult();
1947 const MachineOperand
&Src
= Def
->getOperand(SrcIdx
);
1949 return ValueTrackerResult();
1950 return ValueTrackerResult(Src
.getReg(), Src
.getSubReg());
1953 ValueTrackerResult
ValueTracker::getNextSourceFromRegSequence() {
1954 assert((Def
->isRegSequence() || Def
->isRegSequenceLike()) &&
1955 "Invalid definition");
1957 if (Def
->getOperand(DefIdx
).getSubReg())
1958 // If we are composing subregs, bail out.
1959 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1960 // This should almost never happen as the SSA property is tracked at
1961 // the register level (as opposed to the subreg level).
1965 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1966 // Def. Thus, it must not be generated.
1967 // However, some code could theoretically generates a single
1968 // Def.sub0 (i.e, not defining the other subregs) and we would
1970 // If we can ascertain (or force) that this never happens, we could
1971 // turn that into an assertion.
1972 return ValueTrackerResult();
1975 // We could handle the REG_SEQUENCE here, but we do not want to
1976 // duplicate the code from the generic TII.
1977 return ValueTrackerResult();
1979 SmallVector
<RegSubRegPairAndIdx
, 8> RegSeqInputRegs
;
1980 if (!TII
->getRegSequenceInputs(*Def
, DefIdx
, RegSeqInputRegs
))
1981 return ValueTrackerResult();
1983 // We are looking at:
1984 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1985 // Check if one of the operand defines the subreg we are interested in.
1986 for (const RegSubRegPairAndIdx
&RegSeqInput
: RegSeqInputRegs
) {
1987 if (RegSeqInput
.SubIdx
== DefSubReg
)
1988 return ValueTrackerResult(RegSeqInput
.Reg
, RegSeqInput
.SubReg
);
1991 // If the subreg we are tracking is super-defined by another subreg,
1992 // we could follow this value. However, this would require to compose
1993 // the subreg and we do not do that for now.
1994 return ValueTrackerResult();
1997 ValueTrackerResult
ValueTracker::getNextSourceFromInsertSubreg() {
1998 assert((Def
->isInsertSubreg() || Def
->isInsertSubregLike()) &&
1999 "Invalid definition");
2001 if (Def
->getOperand(DefIdx
).getSubReg())
2002 // If we are composing subreg, bail out.
2003 // Same remark as getNextSourceFromRegSequence.
2004 // I.e., this may be turned into an assert.
2005 return ValueTrackerResult();
2008 // We could handle the REG_SEQUENCE here, but we do not want to
2009 // duplicate the code from the generic TII.
2010 return ValueTrackerResult();
2012 RegSubRegPair BaseReg
;
2013 RegSubRegPairAndIdx InsertedReg
;
2014 if (!TII
->getInsertSubregInputs(*Def
, DefIdx
, BaseReg
, InsertedReg
))
2015 return ValueTrackerResult();
2017 // We are looking at:
2018 // Def = INSERT_SUBREG v0, v1, sub1
2019 // There are two cases:
2020 // 1. DefSubReg == sub1, get v1.
2021 // 2. DefSubReg != sub1, the value may be available through v0.
2023 // #1 Check if the inserted register matches the required sub index.
2024 if (InsertedReg
.SubIdx
== DefSubReg
) {
2025 return ValueTrackerResult(InsertedReg
.Reg
, InsertedReg
.SubReg
);
2027 // #2 Otherwise, if the sub register we are looking for is not partial
2028 // defined by the inserted element, we can look through the main
2030 const MachineOperand
&MODef
= Def
->getOperand(DefIdx
);
2031 // If the result register (Def) and the base register (v0) do not
2032 // have the same register class or if we have to compose
2033 // subregisters, bail out.
2034 if (MRI
.getRegClass(MODef
.getReg()) != MRI
.getRegClass(BaseReg
.Reg
) ||
2036 return ValueTrackerResult();
2038 // Get the TRI and check if the inserted sub-register overlaps with the
2039 // sub-register we are tracking.
2040 const TargetRegisterInfo
*TRI
= MRI
.getTargetRegisterInfo();
2042 !(TRI
->getSubRegIndexLaneMask(DefSubReg
) &
2043 TRI
->getSubRegIndexLaneMask(InsertedReg
.SubIdx
)).none())
2044 return ValueTrackerResult();
2045 // At this point, the value is available in v0 via the same subreg
2047 return ValueTrackerResult(BaseReg
.Reg
, DefSubReg
);
2050 ValueTrackerResult
ValueTracker::getNextSourceFromExtractSubreg() {
2051 assert((Def
->isExtractSubreg() ||
2052 Def
->isExtractSubregLike()) && "Invalid definition");
2053 // We are looking at:
2054 // Def = EXTRACT_SUBREG v0, sub0
2056 // Bail if we have to compose sub registers.
2057 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2059 return ValueTrackerResult();
2062 // We could handle the EXTRACT_SUBREG here, but we do not want to
2063 // duplicate the code from the generic TII.
2064 return ValueTrackerResult();
2066 RegSubRegPairAndIdx ExtractSubregInputReg
;
2067 if (!TII
->getExtractSubregInputs(*Def
, DefIdx
, ExtractSubregInputReg
))
2068 return ValueTrackerResult();
2070 // Bail if we have to compose sub registers.
2071 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2072 if (ExtractSubregInputReg
.SubReg
)
2073 return ValueTrackerResult();
2074 // Otherwise, the value is available in the v0.sub0.
2075 return ValueTrackerResult(ExtractSubregInputReg
.Reg
,
2076 ExtractSubregInputReg
.SubIdx
);
2079 ValueTrackerResult
ValueTracker::getNextSourceFromSubregToReg() {
2080 assert(Def
->isSubregToReg() && "Invalid definition");
2081 // We are looking at:
2082 // Def = SUBREG_TO_REG Imm, v0, sub0
2084 // Bail if we have to compose sub registers.
2085 // If DefSubReg != sub0, we would have to check that all the bits
2086 // we track are included in sub0 and if yes, we would have to
2087 // determine the right subreg in v0.
2088 if (DefSubReg
!= Def
->getOperand(3).getImm())
2089 return ValueTrackerResult();
2090 // Bail if we have to compose sub registers.
2091 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2092 if (Def
->getOperand(2).getSubReg())
2093 return ValueTrackerResult();
2095 return ValueTrackerResult(Def
->getOperand(2).getReg(),
2096 Def
->getOperand(3).getImm());
2099 /// Explore each PHI incoming operand and return its sources.
2100 ValueTrackerResult
ValueTracker::getNextSourceFromPHI() {
2101 assert(Def
->isPHI() && "Invalid definition");
2102 ValueTrackerResult Res
;
2104 // If we look for a different subreg, bail as we do not support composing
2106 if (Def
->getOperand(0).getSubReg() != DefSubReg
)
2107 return ValueTrackerResult();
2109 // Return all register sources for PHI instructions.
2110 for (unsigned i
= 1, e
= Def
->getNumOperands(); i
< e
; i
+= 2) {
2111 const MachineOperand
&MO
= Def
->getOperand(i
);
2112 assert(MO
.isReg() && "Invalid PHI instruction");
2113 // We have no code to deal with undef operands. They shouldn't happen in
2114 // normal programs anyway.
2116 return ValueTrackerResult();
2117 Res
.addSource(MO
.getReg(), MO
.getSubReg());
2123 ValueTrackerResult
ValueTracker::getNextSourceImpl() {
2124 assert(Def
&& "This method needs a valid definition");
2126 assert(((Def
->getOperand(DefIdx
).isDef() &&
2127 (DefIdx
< Def
->getDesc().getNumDefs() ||
2128 Def
->getDesc().isVariadic())) ||
2129 Def
->getOperand(DefIdx
).isImplicit()) &&
2132 return getNextSourceFromCopy();
2133 if (Def
->isBitcast())
2134 return getNextSourceFromBitcast();
2135 // All the remaining cases involve "complex" instructions.
2136 // Bail if we did not ask for the advanced tracking.
2137 if (DisableAdvCopyOpt
)
2138 return ValueTrackerResult();
2139 if (Def
->isRegSequence() || Def
->isRegSequenceLike())
2140 return getNextSourceFromRegSequence();
2141 if (Def
->isInsertSubreg() || Def
->isInsertSubregLike())
2142 return getNextSourceFromInsertSubreg();
2143 if (Def
->isExtractSubreg() || Def
->isExtractSubregLike())
2144 return getNextSourceFromExtractSubreg();
2145 if (Def
->isSubregToReg())
2146 return getNextSourceFromSubregToReg();
2148 return getNextSourceFromPHI();
2149 return ValueTrackerResult();
2152 ValueTrackerResult
ValueTracker::getNextSource() {
2153 // If we reach a point where we cannot move up in the use-def chain,
2154 // there is nothing we can get.
2156 return ValueTrackerResult();
2158 ValueTrackerResult Res
= getNextSourceImpl();
2159 if (Res
.isValid()) {
2160 // Update definition, definition index, and subregister for the
2161 // next call of getNextSource.
2162 // Update the current register.
2163 bool OneRegSrc
= Res
.getNumSources() == 1;
2165 Reg
= Res
.getSrcReg(0);
2166 // Update the result before moving up in the use-def chain
2167 // with the instruction containing the last found sources.
2170 // If we can still move up in the use-def chain, move to the next
2172 if (!Reg
.isPhysical() && OneRegSrc
) {
2173 MachineRegisterInfo::def_iterator DI
= MRI
.def_begin(Reg
);
2174 if (DI
!= MRI
.def_end()) {
2175 Def
= DI
->getParent();
2176 DefIdx
= DI
.getOperandNo();
2177 DefSubReg
= Res
.getSrcSubReg(0);
2184 // If we end up here, this means we will not be able to find another source
2185 // for the next iteration. Make sure any new call to getNextSource bails out
2186 // early by cutting the use-def chain.