1//===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Perform peephole optimizations on the machine code:
10//
11// - Optimize Extensions
12//
13// Optimization of sign / zero extension instructions. It may be extended to
14// handle other instructions with similar properties.
15//
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.
20//
21// - Optimize Comparisons
22//
23// Optimization of comparison instructions. For instance, in this code:
24//
25// sub r1, 1
26// cmp r1, 0
27// bz L1
28//
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.
32//
33// Another instance, in this code:
34//
35// sub r1, r3 | sub r1, imm
36// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37// bge L1
38//
39// If the branch instruction can use flag from "sub", then we can replace
40// "sub" with "subs" and eliminate the "cmp" instruction.
41//
42// - Optimize Loads:
43//
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
46// a single use.
47//
48// - Optimize Copies and Bitcast (more generally, target specific copies):
49//
50// Rewrite copies and bitcasts to avoid cross register bank copies
51// when possible.
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
56// =>
57// b = copy A <-- cross-bank copy
58// C = copy A <-- same-bank copy
59//
60// E.g., for bitcast:
61// b = bitcast A <-- cross-bank copy
62// C = bitcast b <-- cross-bank copy
63// =>
64// b = bitcast A <-- cross-bank copy
65// C = copy A <-- same-bank copy
66//===----------------------------------------------------------------------===//
67
68#include "llvm/CodeGen/PeepholeOptimizer.h"
69#include "llvm/ADT/DenseMap.h"
70#include "llvm/ADT/SmallPtrSet.h"
71#include "llvm/ADT/SmallSet.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/Statistic.h"
74#include "llvm/CodeGen/MachineBasicBlock.h"
75#include "llvm/CodeGen/MachineDominators.h"
76#include "llvm/CodeGen/MachineFunction.h"
77#include "llvm/CodeGen/MachineFunctionPass.h"
78#include "llvm/CodeGen/MachineInstr.h"
79#include "llvm/CodeGen/MachineInstrBuilder.h"
80#include "llvm/CodeGen/MachineLoopInfo.h"
81#include "llvm/CodeGen/MachineOperand.h"
82#include "llvm/CodeGen/MachinePassManager.h"
83#include "llvm/CodeGen/MachineRegisterInfo.h"
84#include "llvm/CodeGen/TargetInstrInfo.h"
85#include "llvm/CodeGen/TargetOpcodes.h"
86#include "llvm/CodeGen/TargetRegisterInfo.h"
87#include "llvm/CodeGen/TargetSubtargetInfo.h"
88#include "llvm/InitializePasses.h"
89#include "llvm/MC/LaneBitmask.h"
90#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/Pass.h"
92#include "llvm/Support/CommandLine.h"
93#include "llvm/Support/Debug.h"
94#include "llvm/Support/raw_ostream.h"
95#include <cassert>
96#include <cstdint>
97#include <utility>
98
99using namespace llvm;
100using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
101using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
102
103#define DEBUG_TYPE "peephole-opt"
104
105// Optimize Extensions
106static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
107 cl::desc("Aggressive extension optimization"));
108
109static cl::opt<bool>
110 DisablePeephole("disable-peephole", cl::Hidden, cl::init(Val: false),
111 cl::desc("Disable the peephole optimizer"));
112
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.
116static cl::opt<bool>
117 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(Val: false),
118 cl::desc("Disable advanced copy optimization"));
119
120static cl::opt<bool> DisableNAPhysCopyOpt(
121 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(Val: false),
122 cl::desc("Disable non-allocatable physical register copy optimization"));
123
124// Limit the number of PHI instructions to process
125// in PeepholeOptimizer::getNextSource.
126static cl::opt<unsigned>
127 RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(Val: 10),
128 cl::desc("Limit the length of PHI chains to lookup"));
129
130// Limit the length of recurrence chain when evaluating the benefit of
131// commuting operands.
132static cl::opt<unsigned> MaxRecurrenceChain(
133 "recurrence-chain-limit", cl::Hidden, cl::init(Val: 3),
134 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
135 "of commuting operands"));
136
137STATISTIC(NumReuse, "Number of extension results reused");
138STATISTIC(NumCmps, "Number of compares eliminated");
139STATISTIC(NumImmFold, "Number of move immediate folded");
140STATISTIC(NumLoadFold, "Number of loads folded");
141STATISTIC(NumSelects, "Number of selects optimized");
142STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
143STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
144STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
145
146namespace {
147
148class ValueTrackerResult;
149class RecurrenceInstr;
150
151/// Interface to query instructions amenable to copy rewriting.
152class Rewriter {
153protected:
154 MachineInstr &CopyLike;
155 int CurrentSrcIdx = 0; ///< The index of the source being rewritten.
156public:
157 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
158 virtual ~Rewriter() = default;
159
160 /// Get the next rewritable source (SrcReg, SrcSubReg) and
161 /// the related value that it affects (DstReg, DstSubReg).
162 /// A source is considered rewritable if its register class and the
163 /// register class of the related DstReg may not be register
164 /// coalescer friendly. In other words, given a copy-like instruction
165 /// not all the arguments may be returned at rewritable source, since
166 /// some arguments are none to be register coalescer friendly.
167 ///
168 /// Each call of this method moves the current source to the next
169 /// rewritable source.
170 /// For instance, let CopyLike be the instruction to rewrite.
171 /// CopyLike has one definition and one source:
172 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
173 ///
174 /// The first call will give the first rewritable source, i.e.,
175 /// the only source this instruction has:
176 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
177 /// This source defines the whole definition, i.e.,
178 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
179 ///
180 /// The second and subsequent calls will return false, as there is only one
181 /// rewritable source.
182 ///
183 /// \return True if a rewritable source has been found, false otherwise.
184 /// The output arguments are valid if and only if true is returned.
185 virtual bool getNextRewritableSource(RegSubRegPair &Src,
186 RegSubRegPair &Dst) = 0;
187
188 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
189 /// \return True if the rewriting was possible, false otherwise.
190 virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0;
191};
192
193/// Rewriter for COPY instructions.
194class CopyRewriter : public Rewriter {
195public:
196 CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
197 assert(MI.isCopy() && "Expected copy instruction");
198 }
199 ~CopyRewriter() override = default;
200
201 bool getNextRewritableSource(RegSubRegPair &Src,
202 RegSubRegPair &Dst) override {
203 if (++CurrentSrcIdx > 1)
204 return false;
205
206 // The rewritable source is the argument.
207 const MachineOperand &MOSrc = CopyLike.getOperand(i: CurrentSrcIdx);
208 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
209 // What we track are the alternative sources of the definition.
210 const MachineOperand &MODef = CopyLike.getOperand(i: 0);
211 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
212 return true;
213 }
214
215 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
216 MachineOperand &MOSrc = CopyLike.getOperand(i: CurrentSrcIdx);
217 MOSrc.setReg(NewReg);
218 MOSrc.setSubReg(NewSubReg);
219 return true;
220 }
221};
222
223/// Helper class to rewrite uncoalescable copy like instructions
224/// into new COPY (coalescable friendly) instructions.
225class UncoalescableRewriter : public Rewriter {
226 int NumDefs; ///< Number of defs in the bitcast.
227
228public:
229 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
230 NumDefs = MI.getDesc().getNumDefs();
231 }
232
233 /// \see See Rewriter::getNextRewritableSource()
234 /// All such sources need to be considered rewritable in order to
235 /// rewrite a uncoalescable copy-like instruction. This method return
236 /// each definition that must be checked if rewritable.
237 bool getNextRewritableSource(RegSubRegPair &Src,
238 RegSubRegPair &Dst) override {
239 // Find the next non-dead definition and continue from there.
240 if (CurrentSrcIdx == NumDefs)
241 return false;
242
243 while (CopyLike.getOperand(i: CurrentSrcIdx).isDead()) {
244 ++CurrentSrcIdx;
245 if (CurrentSrcIdx == NumDefs)
246 return false;
247 }
248
249 // What we track are the alternative sources of the definition.
250 Src = RegSubRegPair(0, 0);
251 const MachineOperand &MODef = CopyLike.getOperand(i: CurrentSrcIdx);
252 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
253
254 CurrentSrcIdx++;
255 return true;
256 }
257
258 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
259 return false;
260 }
261};
262
263/// Specialized rewriter for INSERT_SUBREG instruction.
264class InsertSubregRewriter : public Rewriter {
265public:
266 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
267 assert(MI.isInsertSubreg() && "Invalid instruction");
268 }
269
270 /// \see See Rewriter::getNextRewritableSource()
271 /// Here CopyLike has the following form:
272 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
273 /// Src1 has the same register class has dst, hence, there is
274 /// nothing to rewrite.
275 /// Src2.src2SubIdx, may not be register coalescer friendly.
276 /// Therefore, the first call to this method returns:
277 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
278 /// (DstReg, DstSubReg) = (dst, subIdx).
279 ///
280 /// Subsequence calls will return false.
281 bool getNextRewritableSource(RegSubRegPair &Src,
282 RegSubRegPair &Dst) override {
283 // If we already get the only source we can rewrite, return false.
284 if (CurrentSrcIdx == 2)
285 return false;
286 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
287 CurrentSrcIdx = 2;
288 const MachineOperand &MOInsertedReg = CopyLike.getOperand(i: 2);
289 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
290 const MachineOperand &MODef = CopyLike.getOperand(i: 0);
291
292 // We want to track something that is compatible with the
293 // partial definition.
294 if (MODef.getSubReg())
295 // Bail if we have to compose sub-register indices.
296 return false;
297 Dst = RegSubRegPair(MODef.getReg(),
298 (unsigned)CopyLike.getOperand(i: 3).getImm());
299 return true;
300 }
301
302 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
303 if (CurrentSrcIdx != 2)
304 return false;
305 // We are rewriting the inserted reg.
306 MachineOperand &MO = CopyLike.getOperand(i: CurrentSrcIdx);
307 MO.setReg(NewReg);
308 MO.setSubReg(NewSubReg);
309 return true;
310 }
311};
312
313/// Specialized rewriter for EXTRACT_SUBREG instruction.
314class ExtractSubregRewriter : public Rewriter {
315 const TargetInstrInfo &TII;
316
317public:
318 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
319 : Rewriter(MI), TII(TII) {
320 assert(MI.isExtractSubreg() && "Invalid instruction");
321 }
322
323 /// \see Rewriter::getNextRewritableSource()
324 /// Here CopyLike has the following form:
325 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
326 /// There is only one rewritable source: Src.subIdx,
327 /// which defines dst.dstSubIdx.
328 bool getNextRewritableSource(RegSubRegPair &Src,
329 RegSubRegPair &Dst) override {
330 // If we already get the only source we can rewrite, return false.
331 if (CurrentSrcIdx == 1)
332 return false;
333 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
334 CurrentSrcIdx = 1;
335 const MachineOperand &MOExtractedReg = CopyLike.getOperand(i: 1);
336 // If we have to compose sub-register indices, bail out.
337 if (MOExtractedReg.getSubReg())
338 return false;
339
340 Src =
341 RegSubRegPair(MOExtractedReg.getReg(), CopyLike.getOperand(i: 2).getImm());
342
343 // We want to track something that is compatible with the definition.
344 const MachineOperand &MODef = CopyLike.getOperand(i: 0);
345 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
346 return true;
347 }
348
349 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
350 // The only source we can rewrite is the input register.
351 if (CurrentSrcIdx != 1)
352 return false;
353
354 CopyLike.getOperand(i: CurrentSrcIdx).setReg(NewReg);
355
356 // If we find a source that does not require to extract something,
357 // rewrite the operation with a copy.
358 if (!NewSubReg) {
359 // Move the current index to an invalid position.
360 // We do not want another call to this method to be able
361 // to do any change.
362 CurrentSrcIdx = -1;
363 // Rewrite the operation as a COPY.
364 // Get rid of the sub-register index.
365 CopyLike.removeOperand(OpNo: 2);
366 // Morph the operation into a COPY.
367 CopyLike.setDesc(TII.get(Opcode: TargetOpcode::COPY));
368 return true;
369 }
370 CopyLike.getOperand(i: CurrentSrcIdx + 1).setImm(NewSubReg);
371 return true;
372 }
373};
374
375/// Specialized rewriter for REG_SEQUENCE instruction.
376class RegSequenceRewriter : public Rewriter {
377public:
378 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
379 assert(MI.isRegSequence() && "Invalid instruction");
380 CurrentSrcIdx = -1;
381 }
382
383 /// \see Rewriter::getNextRewritableSource()
384 /// Here CopyLike has the following form:
385 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
386 /// Each call will return a different source, walking all the available
387 /// source.
388 ///
389 /// The first call returns:
390 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
391 /// (DstReg, DstSubReg) = (dst, subIdx1).
392 ///
393 /// The second call returns:
394 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
395 /// (DstReg, DstSubReg) = (dst, subIdx2).
396 ///
397 /// And so on, until all the sources have been traversed, then
398 /// it returns false.
399 bool getNextRewritableSource(RegSubRegPair &Src,
400 RegSubRegPair &Dst) override {
401 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
402 CurrentSrcIdx += 2;
403 if (static_cast<unsigned>(CurrentSrcIdx) >= CopyLike.getNumOperands())
404 return false;
405
406 const MachineOperand &MOInsertedReg = CopyLike.getOperand(i: CurrentSrcIdx);
407 Src.Reg = MOInsertedReg.getReg();
408 Src.SubReg = MOInsertedReg.getSubReg();
409
410 // We want to track something that is compatible with the related
411 // partial definition.
412 Dst.SubReg = CopyLike.getOperand(i: CurrentSrcIdx + 1).getImm();
413
414 const MachineOperand &MODef = CopyLike.getOperand(i: 0);
415 Dst.Reg = MODef.getReg();
416 assert(MODef.getSubReg() == 0 && "cannot have subregister def in SSA");
417 return true;
418 }
419
420 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
421 MachineOperand &MO = CopyLike.getOperand(i: CurrentSrcIdx);
422 MO.setReg(NewReg);
423 MO.setSubReg(NewSubReg);
424 return true;
425 }
426};
427
428class PeepholeOptimizer : private MachineFunction::Delegate {
429 const TargetInstrInfo *TII = nullptr;
430 const TargetRegisterInfo *TRI = nullptr;
431 MachineRegisterInfo *MRI = nullptr;
432 MachineDominatorTree *DT = nullptr; // Machine dominator tree
433 MachineLoopInfo *MLI = nullptr;
434
435public:
436 PeepholeOptimizer(MachineDominatorTree *DT, MachineLoopInfo *MLI)
437 : DT(DT), MLI(MLI) {}
438
439 bool run(MachineFunction &MF);
440 /// Track Def -> Use info used for rewriting copies.
441 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
442
443 /// Sequence of instructions that formulate recurrence cycle.
444 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
445
446private:
447 bool optimizeCmpInstr(MachineInstr &MI, MachineFunction &MF,
448 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
449 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
450 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
451 bool optimizeSelect(MachineInstr &MI,
452 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
453 bool optimizeCondBranch(MachineInstr &MI);
454
455 bool optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter);
456 bool optimizeCoalescableCopy(MachineInstr &MI);
457 bool optimizeUncoalescableCopy(MachineInstr &MI,
458 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
459 bool optimizeRecurrence(MachineInstr &PHI);
460 bool findNextSource(const TargetRegisterClass *DefRC, unsigned DefSubReg,
461 RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
462 bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
463 DenseMap<Register, MachineInstr *> &ImmDefMIs);
464 bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
465 DenseMap<Register, MachineInstr *> &ImmDefMIs,
466 bool &Deleted);
467
468 /// Finds recurrence cycles, but only ones that formulated around
469 /// a def operand and a use operand that are tied. If there is a use
470 /// operand commutable with the tied use operand, find recurrence cycle
471 /// along that operand as well.
472 bool findTargetRecurrence(Register Reg,
473 const SmallSet<Register, 2> &TargetReg,
474 RecurrenceCycle &RC);
475
476 /// If copy instruction \p MI is a virtual register copy or a copy of a
477 /// constant physical register to a virtual register, track it in the
478 /// set CopySrcMIs. If this virtual register was previously seen as a
479 /// copy, replace the uses of this copy with the previously seen copy's
480 /// destination register.
481 bool foldRedundantCopy(MachineInstr &MI);
482
483 /// Is the register \p Reg a non-allocatable physical register?
484 bool isNAPhysCopy(Register Reg);
485
486 /// If copy instruction \p MI is a non-allocatable virtual<->physical
487 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
488 /// non-allocatable physical register was previously copied to a virtual
489 /// registered and hasn't been clobbered, the virt->phys copy can be
490 /// deleted.
491 bool
492 foldRedundantNAPhysCopy(MachineInstr &MI,
493 DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs);
494
495 bool isLoadFoldable(MachineInstr &MI,
496 SmallSet<Register, 16> &FoldAsLoadDefCandidates);
497
498 /// Try to fold the load defined by \p FoldReg into \p MI using
499 /// TII->optimizeLoadInstr. On success, updates \p LocalMIs, erases the old
500 /// instructions, and returns the replacement; returns nullptr otherwise.
501 MachineInstr *foldLoadInto(MachineFunction &MF, MachineInstr &MI,
502 Register FoldReg,
503 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
504
505 /// Check whether \p MI is understood by the register coalescer
506 /// but may require some rewriting.
507 static bool isCoalescableCopy(const MachineInstr &MI) {
508 // SubregToRegs are not interesting, because they are already register
509 // coalescer friendly.
510 return MI.isCopy() ||
511 (!DisableAdvCopyOpt && (MI.isRegSequence() || MI.isInsertSubreg() ||
512 MI.isExtractSubreg()));
513 }
514
515 /// Check whether \p MI is a copy like instruction that is
516 /// not recognized by the register coalescer.
517 static bool isUncoalescableCopy(const MachineInstr &MI) {
518 return MI.isBitcast() || (!DisableAdvCopyOpt && (MI.isRegSequenceLike() ||
519 MI.isInsertSubregLike() ||
520 MI.isExtractSubregLike()));
521 }
522
523 MachineInstr &rewriteSource(MachineInstr &CopyLike, RegSubRegPair Def,
524 RewriteMapTy &RewriteMap);
525
526 // Set of copies to virtual registers keyed by source register. Never
527 // holds any physreg which requires def tracking.
528 DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs;
529
530 // MachineFunction::Delegate implementation. Used to maintain CopySrcMIs.
531 void MF_HandleInsertion(MachineInstr &MI) override {}
532
533 bool getCopySrc(MachineInstr &MI, RegSubRegPair &SrcPair) {
534 if (!MI.isCopy())
535 return false;
536
537 Register SrcReg = MI.getOperand(i: 1).getReg();
538 unsigned SrcSubReg = MI.getOperand(i: 1).getSubReg();
539 if (!SrcReg.isVirtual() && !MRI->isConstantPhysReg(PhysReg: SrcReg))
540 return false;
541
542 SrcPair = RegSubRegPair(SrcReg, SrcSubReg);
543 return true;
544 }
545
546 // If a COPY instruction is to be deleted or changed, we should also remove
547 // it from CopySrcMIs.
548 void deleteChangedCopy(MachineInstr &MI) {
549 RegSubRegPair SrcPair;
550 if (!getCopySrc(MI, SrcPair))
551 return;
552
553 auto It = CopySrcMIs.find(Val: SrcPair);
554 if (It != CopySrcMIs.end() && It->second == &MI)
555 CopySrcMIs.erase(I: It);
556 }
557
558 void MF_HandleRemoval(MachineInstr &MI) override { deleteChangedCopy(MI); }
559
560 void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID) override {
561 deleteChangedCopy(MI);
562 }
563};
564
565class PeepholeOptimizerLegacy : public MachineFunctionPass {
566public:
567 static char ID; // Pass identification
568
569 PeepholeOptimizerLegacy() : MachineFunctionPass(ID) {}
570
571 bool runOnMachineFunction(MachineFunction &MF) override;
572
573 void getAnalysisUsage(AnalysisUsage &AU) const override {
574 AU.setPreservesCFG();
575 MachineFunctionPass::getAnalysisUsage(AU);
576 AU.addRequired<MachineLoopInfoWrapperPass>();
577 if (Aggressive) {
578 AU.addRequired<MachineDominatorTreeWrapperPass>();
579 }
580 }
581
582 MachineFunctionProperties getRequiredProperties() const override {
583 return MachineFunctionProperties().setIsSSA();
584 }
585};
586
587/// Helper class to hold instructions that are inside recurrence cycles.
588/// The recurrence cycle is formulated around 1) a def operand and its
589/// tied use operand, or 2) a def operand and a use operand that is commutable
590/// with another use operand which is tied to the def operand. In the latter
591/// case, index of the tied use operand and the commutable use operand are
592/// maintained with CommutePair.
593class RecurrenceInstr {
594public:
595 using IndexPair = std::pair<unsigned, unsigned>;
596
597 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
598 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
599 : MI(MI), CommutePair(std::make_pair(x&: Idx1, y&: Idx2)) {}
600
601 MachineInstr *getMI() const { return MI; }
602 std::optional<IndexPair> getCommutePair() const { return CommutePair; }
603
604private:
605 MachineInstr *MI;
606 std::optional<IndexPair> CommutePair;
607};
608
609/// Helper class to hold a reply for ValueTracker queries.
610/// Contains the returned sources for a given search and the instructions
611/// where the sources were tracked from.
612class ValueTrackerResult {
613private:
614 /// Track all sources found by one ValueTracker query.
615 SmallVector<RegSubRegPair, 2> RegSrcs;
616
617 /// Instruction using the sources in 'RegSrcs'.
618 const MachineInstr *Inst = nullptr;
619
620public:
621 ValueTrackerResult() = default;
622
623 ValueTrackerResult(Register Reg, unsigned SubReg) { addSource(SrcReg: Reg, SrcSubReg: SubReg); }
624
625 bool isValid() const { return getNumSources() > 0; }
626
627 void setInst(const MachineInstr *I) { Inst = I; }
628 const MachineInstr *getInst() const { return Inst; }
629
630 void clear() {
631 RegSrcs.clear();
632 Inst = nullptr;
633 }
634
635 void addSource(Register SrcReg, unsigned SrcSubReg) {
636 RegSrcs.push_back(Elt: RegSubRegPair(SrcReg, SrcSubReg));
637 }
638
639 void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) {
640 assert(Idx < getNumSources() && "Reg pair source out of index");
641 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
642 }
643
644 int getNumSources() const { return RegSrcs.size(); }
645
646 RegSubRegPair getSrc(int Idx) const { return RegSrcs[Idx]; }
647
648 Register getSrcReg(int Idx) const {
649 assert(Idx < getNumSources() && "Reg source out of index");
650 return RegSrcs[Idx].Reg;
651 }
652
653 unsigned getSrcSubReg(int Idx) const {
654 assert(Idx < getNumSources() && "SubReg source out of index");
655 return RegSrcs[Idx].SubReg;
656 }
657
658 bool operator==(const ValueTrackerResult &Other) const {
659 if (Other.getInst() != getInst())
660 return false;
661
662 if (Other.getNumSources() != getNumSources())
663 return false;
664
665 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
666 if (Other.getSrcReg(Idx: i) != getSrcReg(Idx: i) ||
667 Other.getSrcSubReg(Idx: i) != getSrcSubReg(Idx: i))
668 return false;
669 return true;
670 }
671};
672
673/// Helper class to track the possible sources of a value defined by
674/// a (chain of) copy related instructions.
675/// Given a definition (instruction and definition index), this class
676/// follows the use-def chain to find successive suitable sources.
677/// The given source can be used to rewrite the definition into
678/// def = COPY src.
679///
680/// For instance, let us consider the following snippet:
681/// v0 =
682/// v2 = INSERT_SUBREG v1, v0, sub0
683/// def = COPY v2.sub0
684///
685/// Using a ValueTracker for def = COPY v2.sub0 will give the following
686/// suitable sources:
687/// v2.sub0 and v0.
688/// Then, def can be rewritten into def = COPY v0.
689class ValueTracker {
690private:
691 /// The current point into the use-def chain.
692 const MachineInstr *Def = nullptr;
693
694 /// The index of the definition in Def.
695 unsigned DefIdx = 0;
696
697 /// The sub register index of the definition.
698 unsigned DefSubReg;
699
700 /// The register where the value can be found.
701 Register Reg;
702
703 /// MachineRegisterInfo used to perform tracking.
704 const MachineRegisterInfo &MRI;
705
706 /// Optional TargetInstrInfo used to perform some complex tracking.
707 const TargetInstrInfo *TII;
708
709 /// Dispatcher to the right underlying implementation of getNextSource.
710 ValueTrackerResult getNextSourceImpl();
711
712 /// Specialized version of getNextSource for Copy instructions.
713 ValueTrackerResult getNextSourceFromCopy();
714
715 /// Specialized version of getNextSource for Bitcast instructions.
716 ValueTrackerResult getNextSourceFromBitcast();
717
718 /// Specialized version of getNextSource for RegSequence instructions.
719 ValueTrackerResult getNextSourceFromRegSequence();
720
721 /// Specialized version of getNextSource for InsertSubreg instructions.
722 ValueTrackerResult getNextSourceFromInsertSubreg();
723
724 /// Specialized version of getNextSource for ExtractSubreg instructions.
725 ValueTrackerResult getNextSourceFromExtractSubreg();
726
727 /// Specialized version of getNextSource for SubregToReg instructions.
728 ValueTrackerResult getNextSourceFromSubregToReg();
729
730 /// Specialized version of getNextSource for PHI instructions.
731 ValueTrackerResult getNextSourceFromPHI();
732
733public:
734 /// Create a ValueTracker instance for the value defined by \p Reg.
735 /// \p DefSubReg represents the sub register index the value tracker will
736 /// track. It does not need to match the sub register index used in the
737 /// definition of \p Reg.
738 /// If \p Reg is a physical register, a value tracker constructed with
739 /// this constructor will not find any alternative source.
740 /// Indeed, when \p Reg is a physical register that constructor does not
741 /// know which definition of \p Reg it should track.
742 /// Use the next constructor to track a physical register.
743 ValueTracker(Register Reg, unsigned DefSubReg, const MachineRegisterInfo &MRI,
744 const TargetInstrInfo *TII = nullptr)
745 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
746 if (!Reg.isPhysical()) {
747 MachineRegisterInfo::def_iterator DI = MRI.def_begin(RegNo: Reg);
748 if (DI != MRI.def_end()) {
749 Def = DI->getParent();
750 DefIdx = DI.getOperandNo();
751 }
752 }
753 }
754
755 /// Following the use-def chain, get the next available source
756 /// for the tracked value.
757 /// \return A ValueTrackerResult containing a set of registers
758 /// and sub registers with tracked values. A ValueTrackerResult with
759 /// an empty set of registers means no source was found.
760 ValueTrackerResult getNextSource();
761};
762
763} // end anonymous namespace
764
765char PeepholeOptimizerLegacy::ID = 0;
766
767char &llvm::PeepholeOptimizerLegacyID = PeepholeOptimizerLegacy::ID;
768
769INITIALIZE_PASS_BEGIN(PeepholeOptimizerLegacy, DEBUG_TYPE,
770 "Peephole Optimizations", false, false)
771INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
772INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
773INITIALIZE_PASS_END(PeepholeOptimizerLegacy, DEBUG_TYPE,
774 "Peephole Optimizations", false, false)
775
776/// If instruction is a copy-like instruction, i.e. it reads a single register
777/// and writes a single register and it does not modify the source, and if the
778/// source value is preserved as a sub-register of the result, then replace all
779/// reachable uses of the source with the subreg of the result.
780///
781/// Do not generate an EXTRACT that is used only in a debug use, as this changes
782/// the code. Since this code does not currently share EXTRACTs, just ignore all
783/// debug uses.
784bool PeepholeOptimizer::optimizeExtInstr(
785 MachineInstr &MI, MachineBasicBlock &MBB,
786 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
787 Register SrcReg, DstReg;
788 unsigned SubIdx;
789 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
790 return false;
791
792 if (DstReg.isPhysical() || SrcReg.isPhysical())
793 return false;
794
795 if (MRI->hasOneNonDBGUse(RegNo: SrcReg))
796 // No other uses.
797 return false;
798
799 // Ensure DstReg can get a register class that actually supports
800 // sub-registers. Don't change the class until we commit.
801 const TargetRegisterClass *DstRC = MRI->getRegClass(Reg: DstReg);
802 DstRC = TRI->getSubClassWithSubReg(RC: DstRC, Idx: SubIdx);
803 if (!DstRC)
804 return false;
805
806 // The ext instr may be operating on a sub-register of SrcReg as well.
807 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
808 // register.
809 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
810 // SrcReg:SubIdx should be replaced.
811 bool UseSrcSubIdx =
812 TRI->getSubClassWithSubReg(RC: MRI->getRegClass(Reg: SrcReg), Idx: SubIdx) != nullptr;
813
814 // The source has other uses. See if we can replace the other uses with use of
815 // the result of the extension.
816 SmallPtrSet<MachineBasicBlock *, 4> ReachedBBs;
817 for (MachineInstr &UI : MRI->use_nodbg_instructions(Reg: DstReg))
818 ReachedBBs.insert(Ptr: UI.getParent());
819
820 // Uses that are in the same BB of uses of the result of the instruction.
821 SmallVector<MachineOperand *, 8> Uses;
822
823 // Uses that the result of the instruction can reach.
824 SmallVector<MachineOperand *, 8> ExtendedUses;
825
826 bool ExtendLife = true;
827 for (MachineOperand &UseMO : MRI->use_nodbg_operands(Reg: SrcReg)) {
828 MachineInstr *UseMI = UseMO.getParent();
829 if (UseMI == &MI)
830 continue;
831
832 if (UseMI->isPHI()) {
833 ExtendLife = false;
834 continue;
835 }
836
837 // Only accept uses of SrcReg:SubIdx.
838 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
839 continue;
840
841 // It's an error to translate this:
842 //
843 // %reg1025 = <sext> %reg1024
844 // ...
845 // %reg1026 = SUBREG_TO_REG %reg1024, 4
846 //
847 // into this:
848 //
849 // %reg1025 = <sext> %reg1024
850 // ...
851 // %reg1027 = COPY %reg1025:4
852 // %reg1026 = SUBREG_TO_REG %reg1027, 4
853 //
854 // The problem here is that SUBREG_TO_REG is there to assert that an
855 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
856 // the COPY here, it will give us the value after the <sext>, not the
857 // original value of %reg1024 before <sext>.
858 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
859 continue;
860
861 MachineBasicBlock *UseMBB = UseMI->getParent();
862 if (UseMBB == &MBB) {
863 // Local uses that come after the extension.
864 if (!LocalMIs.count(Ptr: UseMI))
865 Uses.push_back(Elt: &UseMO);
866 } else if (ReachedBBs.count(Ptr: UseMBB)) {
867 // Non-local uses where the result of the extension is used. Always
868 // replace these unless it's a PHI.
869 Uses.push_back(Elt: &UseMO);
870 } else if (Aggressive && DT->dominates(A: &MBB, B: UseMBB)) {
871 // We may want to extend the live range of the extension result in order
872 // to replace these uses.
873 ExtendedUses.push_back(Elt: &UseMO);
874 } else {
875 // Both will be live out of the def MBB anyway. Don't extend live range of
876 // the extension result.
877 ExtendLife = false;
878 break;
879 }
880 }
881
882 if (ExtendLife && !ExtendedUses.empty())
883 // Extend the liveness of the extension result.
884 Uses.append(in_start: ExtendedUses.begin(), in_end: ExtendedUses.end());
885
886 // Now replace all uses.
887 bool Changed = false;
888 if (!Uses.empty()) {
889 SmallPtrSet<MachineBasicBlock *, 4> PHIBBs;
890
891 // Look for PHI uses of the extended result, we don't want to extend the
892 // liveness of a PHI input. It breaks all kinds of assumptions down
893 // stream. A PHI use is expected to be the kill of its source values.
894 for (MachineInstr &UI : MRI->use_nodbg_instructions(Reg: DstReg))
895 if (UI.isPHI())
896 PHIBBs.insert(Ptr: UI.getParent());
897
898 const TargetRegisterClass *RC = MRI->getRegClass(Reg: SrcReg);
899 for (MachineOperand *UseMO : Uses) {
900 MachineInstr *UseMI = UseMO->getParent();
901 MachineBasicBlock *UseMBB = UseMI->getParent();
902 if (PHIBBs.count(Ptr: UseMBB))
903 continue;
904
905 // About to add uses of DstReg, clear DstReg's kill flags.
906 if (!Changed) {
907 MRI->clearKillFlags(Reg: DstReg);
908 MRI->constrainRegClass(Reg: DstReg, RC: DstRC);
909 }
910
911 // SubReg defs are illegal in machine SSA phase,
912 // we should not generate SubReg defs.
913 //
914 // For example, for the instructions:
915 //
916 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
917 // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
918 //
919 // We should generate:
920 //
921 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
922 // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
923 // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
924 //
925 if (UseSrcSubIdx) {
926 RC = MRI->getRegClass(Reg: UseMO->getReg());
927 if (UseMO->getSubReg())
928 RC = TRI->getSubRegisterClass(SuperRC: RC, SubRegIdx: UseMO->getSubReg());
929 }
930
931 Register NewVR = MRI->createVirtualRegister(RegClass: RC);
932 [[maybe_unused]] auto Copy = BuildMI(BB&: *UseMBB, I: UseMI, MIMD: UseMI->getDebugLoc(),
933 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: NewVR)
934 .addReg(RegNo: DstReg, Flags: {}, SubReg: SubIdx);
935 LLVM_DEBUG(dbgs() << " Build new copy: " << *Copy
936 << " Changing: " << *UseMI);
937 if (UseSrcSubIdx)
938 UseMO->setSubReg(0);
939
940 UseMO->setReg(NewVR);
941 LLVM_DEBUG(dbgs() << " to: " << *UseMI);
942 ++NumReuse;
943 Changed = true;
944 }
945 }
946
947 return Changed;
948}
949
950/// If the instruction is a compare and the previous instruction it's comparing
951/// against already sets (or could be modified to set) the same flag as the
952/// compare, then we can remove the comparison and use the flag from the
953/// previous instruction.
954bool PeepholeOptimizer::optimizeCmpInstr(
955 MachineInstr &MI, MachineFunction &MF,
956 SmallPtrSet<MachineInstr *, 16> &LocalMIs) {
957 // If this instruction is a comparison against zero and isn't comparing a
958 // physical register, we can try to optimize it.
959 Register SrcReg, SrcReg2;
960 int64_t CmpMask, CmpValue;
961 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, Mask&: CmpMask, Value&: CmpValue) ||
962 SrcReg.isPhysical() || SrcReg2.isPhysical())
963 return false;
964
965 // Attempt to optimize the comparison instruction.
966 LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
967 if (!TII->optimizeCompareInstr(CmpInstr&: MI, SrcReg, SrcReg2, Mask: CmpMask, Value: CmpValue, MRI))
968 return false;
969
970 LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n");
971 LocalMIs.erase(Ptr: &MI);
972 ++NumCmps;
973
974 // The eliminated compare may have been the extra use preventing a
975 // load from being folded into the flag-setting instruction.
976 if (MachineInstr *FlagProducer =
977 SrcReg.isVirtual() ? MRI->getOneNonDBGUser(RegNo: SrcReg) : nullptr) {
978 MachineInstr *LoadMI = MRI->getVRegDef(Reg: SrcReg);
979 // No store between LoadMI and FlagProducer that could change the value.
980 if (LocalMIs.count(Ptr: FlagProducer) && LoadMI && LoadMI->canFoldAsLoad() &&
981 LoadMI->mayLoad() && LocalMIs.count(Ptr: LoadMI) &&
982 llvm::none_of(
983 Range: make_range(x: std::next(x: LoadMI->getIterator()),
984 y: FlagProducer->getIterator()),
985 P: [](const MachineInstr &I) { return I.isLoadFoldBarrier(); }))
986 foldLoadInto(MF, MI&: *FlagProducer, FoldReg: SrcReg, LocalMIs);
987 }
988
989 return true;
990}
991
992/// Optimize a select instruction.
993bool PeepholeOptimizer::optimizeSelect(
994 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
995 assert(MI.isSelect() && "Should only be called when MI->isSelect() is true");
996 if (!TII->optimizeSelect(MI, NewMIs&: LocalMIs))
997 return false;
998 LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
999 MI.eraseFromParent();
1000 ++NumSelects;
1001 return true;
1002}
1003
1004/// Check if a simpler conditional branch can be generated.
1005bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
1006 return TII->optimizeCondBranch(MI);
1007}
1008
1009/// Try to find a better source value that shares the same register file to
1010/// replace \p RegSubReg in an instruction like
1011/// `DefRC.DefSubReg = COPY RegSubReg`
1012///
1013/// When true is returned, the \p RewriteMap can be used by the client to
1014/// retrieve all Def -> Use along the way up to the next source. Any found
1015/// Use that is not itself a key for another entry, is the next source to
1016/// use. During the search for the next source, multiple sources can be found
1017/// given multiple incoming sources of a PHI instruction. In this case, we
1018/// look in each PHI source for the next source; all found next sources must
1019/// share the same register file as \p Reg and \p SubReg. The client should
1020/// then be capable to rewrite all intermediate PHIs to get the next source.
1021/// \return False if no alternative sources are available. True otherwise.
1022bool PeepholeOptimizer::findNextSource(const TargetRegisterClass *DefRC,
1023 unsigned DefSubReg,
1024 RegSubRegPair RegSubReg,
1025 RewriteMapTy &RewriteMap) {
1026 // Do not try to find a new source for a physical register.
1027 // So far we do not have any motivating example for doing that.
1028 // Thus, instead of maintaining untested code, we will revisit that if
1029 // that changes at some point.
1030 Register Reg = RegSubReg.Reg;
1031 RegSubRegPair CurSrcPair = RegSubReg;
1032 SmallVector<RegSubRegPair, 4> SrcToLook = {CurSrcPair};
1033
1034 unsigned PHICount = 0;
1035
1036 // Remember the last suitable source in case the search meets an invalid
1037 // source.
1038 bool FoundSuitable = false;
1039 RegSubRegPair SuitablePair = RegSubReg;
1040 bool Aborted = false;
1041 do {
1042 CurSrcPair = SrcToLook.pop_back_val();
1043 // As explained above, do not handle physical registers
1044 if (CurSrcPair.Reg.isPhysical()) {
1045 Aborted = true;
1046 break;
1047 }
1048
1049 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
1050
1051 // Follow the chain of copies until we find a more suitable source, a phi
1052 // or have to abort.
1053 while (true) {
1054 ValueTrackerResult Res = ValTracker.getNextSource();
1055 // Abort at the end of a chain (without finding a suitable source).
1056 if (!Res.isValid()) {
1057 Aborted = true;
1058 break;
1059 }
1060
1061 // Insert the Def -> Use entry for the recently found source.
1062 auto [InsertPt, WasInserted] = RewriteMap.try_emplace(Key: CurSrcPair, Args&: Res);
1063
1064 if (!WasInserted) {
1065 const ValueTrackerResult &CurSrcRes = InsertPt->second;
1066
1067 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
1068 // An existent entry with multiple sources is a PHI cycle we must avoid.
1069 // Otherwise it's an entry with a valid next source we already found.
1070 if (CurSrcRes.getNumSources() > 1) {
1071 LLVM_DEBUG(dbgs()
1072 << "findNextSource: found PHI cycle, aborting...\n");
1073 Aborted = true;
1074 }
1075 break;
1076 }
1077
1078 // ValueTrackerResult usually have one source unless it's the result from
1079 // a PHI instruction. Add the found PHI edges to be looked up further.
1080 unsigned NumSrcs = Res.getNumSources();
1081 if (NumSrcs > 1) {
1082 PHICount++;
1083 if (PHICount >= RewritePHILimit) {
1084 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
1085 Aborted = true;
1086 break;
1087 }
1088
1089 for (unsigned i = 0; i < NumSrcs; ++i)
1090 SrcToLook.push_back(Elt: Res.getSrc(Idx: i));
1091 break;
1092 }
1093
1094 CurSrcPair = Res.getSrc(Idx: 0);
1095 // Do not extend the live-ranges of physical registers as they add
1096 // constraints to the register allocator. Moreover, if we want to extend
1097 // the live-range of a physical register, unlike SSA virtual register,
1098 // we will have to check that they aren't redefine before the related use.
1099 if (CurSrcPair.Reg.isPhysical()) {
1100 Aborted = true;
1101 break;
1102 }
1103
1104 // Keep following the chain if the value isn't any better yet.
1105 const TargetRegisterClass *SrcRC = MRI->getRegClass(Reg: CurSrcPair.Reg);
1106 if (!TRI->shouldRewriteCopySrc(DefRC, DefSubReg, SrcRC,
1107 SrcSubReg: CurSrcPair.SubReg))
1108 continue;
1109
1110 // We currently cannot deal with subreg operands on PHI instructions
1111 // (see insertPHI()).
1112 if (PHICount > 0 && CurSrcPair.SubReg != 0)
1113 continue;
1114
1115 // Don't stop at the first suitable source if it is still a subregister;
1116 // keep tracing to try to reach a deeper source. Remember it.
1117 if (CurSrcPair.SubReg != 0) {
1118 SuitablePair = CurSrcPair;
1119 FoundSuitable = true;
1120 continue;
1121 }
1122
1123 // We found a suitable source, and are done with this chain.
1124 break;
1125 }
1126
1127 // A dead-ended chain ends all exploration
1128 if (Aborted)
1129 break;
1130 } while (!SrcToLook.empty());
1131
1132 if (Aborted) {
1133 // If aborted with an invalid source, restore the suitable so far, if any.
1134 if (!FoundSuitable)
1135 return false;
1136
1137 CurSrcPair = SuitablePair;
1138 RewriteMap.erase(Val: SuitablePair);
1139 }
1140
1141 // If we did not find a more suitable source, there is nothing to optimize.
1142 return CurSrcPair.Reg != Reg;
1143}
1144
1145/// Insert a PHI instruction with incoming edges \p SrcRegs that are
1146/// guaranteed to have the same register class. This is necessary whenever we
1147/// successfully traverse a PHI instruction and find suitable sources coming
1148/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
1149/// suitable to be used in a new COPY instruction.
1150static MachineInstr &insertPHI(MachineRegisterInfo &MRI,
1151 const TargetInstrInfo &TII,
1152 const SmallVectorImpl<RegSubRegPair> &SrcRegs,
1153 MachineInstr &OrigPHI) {
1154 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
1155
1156 const TargetRegisterClass *NewRC = MRI.getRegClass(Reg: SrcRegs[0].Reg);
1157 // NewRC is only correct if no subregisters are involved. findNextSource()
1158 // should have rejected those cases already.
1159 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
1160 Register NewVR = MRI.createVirtualRegister(RegClass: NewRC);
1161 MachineBasicBlock *MBB = OrigPHI.getParent();
1162 MachineInstrBuilder MIB = BuildMI(BB&: *MBB, I: &OrigPHI, MIMD: OrigPHI.getDebugLoc(),
1163 MCID: TII.get(Opcode: TargetOpcode::PHI), DestReg: NewVR);
1164
1165 unsigned MBBOpIdx = 2;
1166 for (const RegSubRegPair &RegPair : SrcRegs) {
1167 MIB.addReg(RegNo: RegPair.Reg, Flags: {}, SubReg: RegPair.SubReg);
1168 MIB.addMBB(MBB: OrigPHI.getOperand(i: MBBOpIdx).getMBB());
1169 // Since we're extended the lifetime of RegPair.Reg, clear the
1170 // kill flags to account for that and make RegPair.Reg reaches
1171 // the new PHI.
1172 MRI.clearKillFlags(Reg: RegPair.Reg);
1173 MBBOpIdx += 2;
1174 }
1175
1176 return *MIB;
1177}
1178
1179/// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1180/// the new source to use for rewrite. If \p HandleMultipleSources is true and
1181/// multiple sources for a given \p Def are found along the way, we found a
1182/// PHI instructions that needs to be rewritten.
1183/// TODO: HandleMultipleSources should be removed once we test PHI handling
1184/// with coalescable copies.
1185static RegSubRegPair
1186getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
1187 RegSubRegPair Def,
1188 const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1189 bool HandleMultipleSources = true) {
1190 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1191 while (true) {
1192 ValueTrackerResult Res = RewriteMap.lookup(Val: LookupSrc);
1193 // If there are no entries on the map, LookupSrc is the new source.
1194 if (!Res.isValid())
1195 return LookupSrc;
1196
1197 // There's only one source for this definition, keep searching...
1198 unsigned NumSrcs = Res.getNumSources();
1199 if (NumSrcs == 1) {
1200 LookupSrc.Reg = Res.getSrcReg(Idx: 0);
1201 LookupSrc.SubReg = Res.getSrcSubReg(Idx: 0);
1202 continue;
1203 }
1204
1205 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1206 if (!HandleMultipleSources)
1207 break;
1208
1209 // Multiple sources, recurse into each source to find a new source
1210 // for it. Then, rewrite the PHI accordingly to its new edges.
1211 SmallVector<RegSubRegPair, 4> NewPHISrcs;
1212 for (unsigned i = 0; i < NumSrcs; ++i) {
1213 RegSubRegPair PHISrc(Res.getSrcReg(Idx: i), Res.getSrcSubReg(Idx: i));
1214 NewPHISrcs.push_back(
1215 Elt: getNewSource(MRI, TII, Def: PHISrc, RewriteMap, HandleMultipleSources));
1216 }
1217
1218 // Build the new PHI node and return its def register as the new source.
1219 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1220 MachineInstr &NewPHI = insertPHI(MRI&: *MRI, TII: *TII, SrcRegs: NewPHISrcs, OrigPHI);
1221 LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1222 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
1223 LLVM_DEBUG(dbgs() << " With: " << NewPHI);
1224 const MachineOperand &MODef = NewPHI.getOperand(i: 0);
1225 return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1226 }
1227
1228 return RegSubRegPair(0, 0);
1229}
1230
1231bool PeepholeOptimizer::optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter) {
1232 bool Changed = false;
1233 // Get the right rewriter for the current copy.
1234 // Rewrite each rewritable source.
1235 RegSubRegPair Dst;
1236 RegSubRegPair TrackPair;
1237 while (CpyRewriter.getNextRewritableSource(Src&: TrackPair, Dst)) {
1238 if (Dst.Reg.isPhysical()) {
1239 // Do not try to find a new source for a physical register.
1240 // So far we do not have any motivating example for doing that.
1241 // Thus, instead of maintaining untested code, we will revisit that if
1242 // that changes at some point.
1243 continue;
1244 }
1245
1246 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg: Dst.Reg);
1247
1248 // Keep track of PHI nodes and its incoming edges when looking for sources.
1249 RewriteMapTy RewriteMap;
1250 // Try to find a more suitable source. If we failed to do so, or get the
1251 // actual source, move to the next source.
1252 if (!findNextSource(DefRC, DefSubReg: Dst.SubReg, RegSubReg: TrackPair, RewriteMap))
1253 continue;
1254
1255 // Get the new source to rewrite. TODO: Only enable handling of multiple
1256 // sources (PHIs) once we have a motivating example and testcases for it.
1257 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def: TrackPair, RewriteMap,
1258 /*HandleMultipleSources=*/false);
1259 assert(TrackPair.Reg != NewSrc.Reg &&
1260 "should not rewrite source to original value");
1261 if (!NewSrc.Reg)
1262 continue;
1263
1264 if (NewSrc.SubReg) {
1265 // Verify the register class supports the subregister index. ARM's
1266 // copy-like queries return register:subreg pairs where the register's
1267 // current class does not directly support the subregister index.
1268 const TargetRegisterClass *RC = MRI->getRegClass(Reg: NewSrc.Reg);
1269 const TargetRegisterClass *WithSubRC =
1270 TRI->getSubClassWithSubReg(RC, Idx: NewSrc.SubReg);
1271 if (!MRI->constrainRegClass(Reg: NewSrc.Reg, RC: WithSubRC))
1272 continue;
1273 Changed = true;
1274 }
1275
1276 // Rewrite source.
1277 if (CpyRewriter.RewriteCurrentSource(NewReg: NewSrc.Reg, NewSubReg: NewSrc.SubReg)) {
1278 // We may have extended the live-range of NewSrc, account for that.
1279 MRI->clearKillFlags(Reg: NewSrc.Reg);
1280 Changed = true;
1281 }
1282 }
1283
1284 // TODO: We could have a clean-up method to tidy the instruction.
1285 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1286 // => v0 = COPY v1
1287 // Currently we haven't seen motivating example for that and we
1288 // want to avoid untested code.
1289 NumRewrittenCopies += Changed;
1290 return Changed;
1291}
1292
1293/// Optimize generic copy instructions to avoid cross register bank copy.
1294/// The optimization looks through a chain of copies and tries to find a source
1295/// that has a compatible register class.
1296/// Two register classes are considered to be compatible if they share the same
1297/// register bank.
1298/// New copies issued by this optimization are register allocator
1299/// friendly. This optimization does not remove any copy as it may
1300/// overconstrain the register allocator, but replaces some operands
1301/// when possible.
1302/// \pre isCoalescableCopy(*MI) is true.
1303/// \return True, when \p MI has been rewritten. False otherwise.
1304bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1305 assert(isCoalescableCopy(MI) && "Invalid argument");
1306 assert(MI.getDesc().getNumDefs() == 1 &&
1307 "Coalescer can understand multiple defs?!");
1308 const MachineOperand &MODef = MI.getOperand(i: 0);
1309 // Do not rewrite physical definitions.
1310 if (MODef.getReg().isPhysical())
1311 return false;
1312
1313 switch (MI.getOpcode()) {
1314 case TargetOpcode::COPY:
1315 return optimizeCoalescableCopyImpl(CpyRewriter: CopyRewriter(MI));
1316 case TargetOpcode::INSERT_SUBREG:
1317 return optimizeCoalescableCopyImpl(CpyRewriter: InsertSubregRewriter(MI));
1318 case TargetOpcode::EXTRACT_SUBREG:
1319 return optimizeCoalescableCopyImpl(CpyRewriter: ExtractSubregRewriter(MI, *TII));
1320 case TargetOpcode::REG_SEQUENCE:
1321 return optimizeCoalescableCopyImpl(CpyRewriter: RegSequenceRewriter(MI));
1322 default:
1323 // Handle uncoalescable copy-like instructions.
1324 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1325 MI.isExtractSubregLike())
1326 return optimizeCoalescableCopyImpl(CpyRewriter: UncoalescableRewriter(MI));
1327 return false;
1328 }
1329}
1330
1331/// Rewrite the source found through \p Def, by using the \p RewriteMap
1332/// and create a new COPY instruction. More info about RewriteMap in
1333/// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1334/// Uncoalescable copies, since they are copy like instructions that aren't
1335/// recognized by the register allocator.
1336MachineInstr &PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1337 RegSubRegPair Def,
1338 RewriteMapTy &RewriteMap) {
1339 assert(!Def.Reg.isPhysical() && "We do not rewrite physical registers");
1340
1341 // Find the new source to use in the COPY rewrite.
1342 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1343
1344 // Insert the COPY.
1345 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg: Def.Reg);
1346 Register NewVReg = MRI->createVirtualRegister(RegClass: DefRC);
1347
1348 if (NewSrc.SubReg) {
1349 const TargetRegisterClass *NewSrcRC = MRI->getRegClass(Reg: NewSrc.Reg);
1350 const TargetRegisterClass *WithSubRC =
1351 TRI->getSubClassWithSubReg(RC: NewSrcRC, Idx: NewSrc.SubReg);
1352
1353 // The new source may not directly support the subregister, but we should be
1354 // able to assume it is constrainable to support the subregister (otherwise
1355 // ValueTracker was lying and reported a useless value).
1356 if (!MRI->constrainRegClass(Reg: NewSrc.Reg, RC: WithSubRC))
1357 llvm_unreachable("replacement register cannot support subregister");
1358 }
1359
1360 MachineInstr *NewCopy =
1361 BuildMI(BB&: *CopyLike.getParent(), I: &CopyLike, MIMD: CopyLike.getDebugLoc(),
1362 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: NewVReg)
1363 .addReg(RegNo: NewSrc.Reg, Flags: {}, SubReg: NewSrc.SubReg);
1364
1365 if (Def.SubReg) {
1366 NewCopy->getOperand(i: 0).setSubReg(Def.SubReg);
1367 NewCopy->getOperand(i: 0).setIsUndef();
1368 }
1369
1370 LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1371 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
1372 LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
1373 MRI->replaceRegWith(FromReg: Def.Reg, ToReg: NewVReg);
1374 MRI->clearKillFlags(Reg: NewVReg);
1375
1376 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1377 // account for that.
1378 MRI->clearKillFlags(Reg: NewSrc.Reg);
1379
1380 return *NewCopy;
1381}
1382
1383/// Optimize copy-like instructions to create
1384/// register coalescer friendly instruction.
1385/// The optimization tries to kill-off the \p MI by looking
1386/// through a chain of copies to find a source that has a compatible
1387/// register class.
1388/// If such a source is found, it replace \p MI by a generic COPY
1389/// operation.
1390/// \pre isUncoalescableCopy(*MI) is true.
1391/// \return True, when \p MI has been optimized. In that case, \p MI has
1392/// been removed from its parent.
1393/// All COPY instructions created, are inserted in \p LocalMIs.
1394bool PeepholeOptimizer::optimizeUncoalescableCopy(
1395 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1396 assert(isUncoalescableCopy(MI) && "Invalid argument");
1397 UncoalescableRewriter CpyRewriter(MI);
1398
1399 // Rewrite each rewritable source by generating new COPYs. This works
1400 // differently from optimizeCoalescableCopy since it first makes sure that all
1401 // definitions can be rewritten.
1402 RewriteMapTy RewriteMap;
1403 RegSubRegPair Src;
1404 RegSubRegPair Def;
1405 SmallVector<RegSubRegPair, 4> RewritePairs;
1406 while (CpyRewriter.getNextRewritableSource(Src, Dst&: Def)) {
1407 // If a physical register is here, this is probably for a good reason.
1408 // Do not rewrite that.
1409 if (Def.Reg.isPhysical())
1410 return false;
1411
1412 // FIXME: Uncoalescable copies are treated differently by
1413 // UncoalescableRewriter, and this probably should not share
1414 // API. getNextRewritableSource really finds rewritable defs.
1415 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg: Def.Reg);
1416
1417 // If we do not know how to rewrite this definition, there is no point
1418 // in trying to kill this instruction.
1419 if (!findNextSource(DefRC, DefSubReg: Def.SubReg, RegSubReg: Def, RewriteMap))
1420 return false;
1421
1422 RewritePairs.push_back(Elt: Def);
1423 }
1424
1425 // The change is possible for all defs, do it.
1426 for (const RegSubRegPair &Def : RewritePairs) {
1427 // Rewrite the "copy" in a way the register coalescer understands.
1428 MachineInstr &NewCopy = rewriteSource(CopyLike&: MI, Def, RewriteMap);
1429 LocalMIs.insert(Ptr: &NewCopy);
1430 }
1431
1432 // MI is now dead.
1433 LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
1434 MI.eraseFromParent();
1435 ++NumUncoalescableCopies;
1436 return true;
1437}
1438
1439/// Check whether MI is a candidate for folding into a later instruction.
1440/// We only fold loads to virtual registers and the virtual register defined
1441/// has a single user.
1442bool PeepholeOptimizer::isLoadFoldable(
1443 MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) {
1444 if (!MI.canFoldAsLoad() || !MI.mayLoad())
1445 return false;
1446 const MCInstrDesc &MCID = MI.getDesc();
1447 if (MCID.getNumDefs() != 1)
1448 return false;
1449
1450 Register Reg = MI.getOperand(i: 0).getReg();
1451 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1452 // loads. It should be checked when processing uses of the load, since
1453 // uses can be removed during peephole.
1454 if (Reg.isVirtual() && !MI.getOperand(i: 0).getSubReg() &&
1455 MRI->hasOneNonDBGUser(RegNo: Reg)) {
1456 FoldAsLoadDefCandidates.insert(V: Reg);
1457 return true;
1458 }
1459 return false;
1460}
1461
1462MachineInstr *
1463PeepholeOptimizer::foldLoadInto(MachineFunction &MF, MachineInstr &MI,
1464 Register FoldReg,
1465 SmallPtrSet<MachineInstr *, 16> &LocalMIs) {
1466 Register Reg = FoldReg;
1467 MachineInstr *DefMI = nullptr;
1468 MachineInstr *CopyMI = nullptr;
1469 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI, FoldAsLoadDefReg&: Reg, DefMI, CopyMI);
1470 if (!FoldMI)
1471 return nullptr;
1472 LLVM_DEBUG(dbgs() << "Replacing: " << MI << " With: " << *FoldMI);
1473 LocalMIs.erase(Ptr: &MI);
1474 LocalMIs.erase(Ptr: DefMI);
1475 LocalMIs.insert(Ptr: FoldMI);
1476 if (CopyMI)
1477 LocalMIs.insert(Ptr: CopyMI);
1478 if (MI.shouldUpdateAdditionalCallInfo())
1479 MF.moveAdditionalCallInfo(Old: &MI, New: FoldMI);
1480 MI.eraseFromParent();
1481 DefMI->eraseFromParent();
1482 MRI->markUsesInDebugValueAsUndef(Reg: FoldReg);
1483 ++NumLoadFold;
1484 return FoldMI;
1485}
1486
1487bool PeepholeOptimizer::isMoveImmediate(
1488 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1489 DenseMap<Register, MachineInstr *> &ImmDefMIs) {
1490 const MCInstrDesc &MCID = MI.getDesc();
1491 if (MCID.getNumDefs() != 1 || !MI.getOperand(i: 0).isReg())
1492 return false;
1493 Register Reg = MI.getOperand(i: 0).getReg();
1494 if (!Reg.isVirtual())
1495 return false;
1496
1497 int64_t ImmVal;
1498 if (!MI.isMoveImmediate() && !TII->getConstValDefinedInReg(MI, Reg, ImmVal))
1499 return false;
1500
1501 ImmDefMIs.insert(KV: std::make_pair(x&: Reg, y: &MI));
1502 ImmDefRegs.insert(V: Reg);
1503 return true;
1504}
1505
1506/// Try folding register operands that are defined by move immediate
1507/// instructions, i.e. a trivial constant folding optimization, if
1508/// and only if the def and use are in the same BB.
1509bool PeepholeOptimizer::foldImmediate(
1510 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1511 DenseMap<Register, MachineInstr *> &ImmDefMIs, bool &Deleted) {
1512 Deleted = false;
1513 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1514 MachineOperand &MO = MI.getOperand(i);
1515 if (!MO.isReg() || MO.isDef())
1516 continue;
1517 Register Reg = MO.getReg();
1518 if (!Reg.isVirtual())
1519 continue;
1520 if (ImmDefRegs.count(V: Reg) == 0)
1521 continue;
1522 auto II = ImmDefMIs.find(Val: Reg);
1523 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1524 if (TII->foldImmediate(UseMI&: MI, DefMI&: *II->second, Reg, MRI)) {
1525 ++NumImmFold;
1526 // foldImmediate can delete ImmDefMI if MI was its only user. If ImmDefMI
1527 // is not deleted, and we happened to get a same MI, we can delete MI and
1528 // replace its users.
1529 if (MRI->getVRegDef(Reg) &&
1530 MI.isIdenticalTo(Other: *II->second, Check: MachineInstr::IgnoreVRegDefs)) {
1531 Register DstReg = MI.getOperand(i: 0).getReg();
1532 if (DstReg.isVirtual() &&
1533 MRI->getRegClass(Reg: DstReg) == MRI->getRegClass(Reg)) {
1534 MRI->replaceRegWith(FromReg: DstReg, ToReg: Reg);
1535 MRI->clearKillFlags(Reg);
1536 MI.eraseFromParent();
1537 Deleted = true;
1538 }
1539 }
1540 return true;
1541 }
1542 }
1543 return false;
1544}
1545
1546// FIXME: This is very simple and misses some cases which should be handled when
1547// motivating examples are found.
1548//
1549// The copy rewriting logic should look at uses as well as defs and be able to
1550// eliminate copies across blocks.
1551//
1552// Later copies that are subregister extracts will also not be eliminated since
1553// only the first copy is considered.
1554//
1555// e.g.
1556// %1 = COPY %0
1557// %2 = COPY %0:sub1
1558//
1559// Should replace %2 uses with %1:sub1
1560bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI) {
1561 assert(MI.isCopy() && "expected a COPY machine instruction");
1562
1563 RegSubRegPair SrcPair;
1564 if (!getCopySrc(MI, SrcPair))
1565 return false;
1566
1567 Register DstReg = MI.getOperand(i: 0).getReg();
1568 if (!DstReg.isVirtual())
1569 return false;
1570
1571 if (CopySrcMIs.insert(KV: std::make_pair(x&: SrcPair, y: &MI)).second) {
1572 // First copy of this reg seen.
1573 return false;
1574 }
1575
1576 MachineInstr *PrevCopy = CopySrcMIs.find(Val: SrcPair)->second;
1577
1578 assert(SrcPair.SubReg == PrevCopy->getOperand(1).getSubReg() &&
1579 "Unexpected mismatching subreg!");
1580
1581 Register PrevDstReg = PrevCopy->getOperand(i: 0).getReg();
1582
1583 // Only replace if the copy register class is the same.
1584 //
1585 // TODO: If we have multiple copies to different register classes, we may want
1586 // to track multiple copies of the same source register.
1587 if (MRI->getRegClass(Reg: DstReg) != MRI->getRegClass(Reg: PrevDstReg))
1588 return false;
1589
1590 MRI->replaceRegWith(FromReg: DstReg, ToReg: PrevDstReg);
1591
1592 // Lifetime of the previous copy has been extended.
1593 MRI->clearKillFlags(Reg: PrevDstReg);
1594 return true;
1595}
1596
1597bool PeepholeOptimizer::isNAPhysCopy(Register Reg) {
1598 return Reg.isPhysical() && !MRI->isAllocatable(PhysReg: Reg);
1599}
1600
1601bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1602 MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) {
1603 assert(MI.isCopy() && "expected a COPY machine instruction");
1604
1605 if (DisableNAPhysCopyOpt)
1606 return false;
1607
1608 Register DstReg = MI.getOperand(i: 0).getReg();
1609 Register SrcReg = MI.getOperand(i: 1).getReg();
1610 if (isNAPhysCopy(Reg: SrcReg) && DstReg.isVirtual()) {
1611 // %vreg = COPY $physreg
1612 // Avoid using a datastructure which can track multiple live non-allocatable
1613 // phys->virt copies since LLVM doesn't seem to do this.
1614 NAPhysToVirtMIs.insert(KV: {SrcReg, &MI});
1615 return false;
1616 }
1617
1618 if (!(SrcReg.isVirtual() && isNAPhysCopy(Reg: DstReg)))
1619 return false;
1620
1621 // $physreg = COPY %vreg
1622 auto PrevCopy = NAPhysToVirtMIs.find(Val: DstReg);
1623 if (PrevCopy == NAPhysToVirtMIs.end()) {
1624 // We can't remove the copy: there was an intervening clobber of the
1625 // non-allocatable physical register after the copy to virtual.
1626 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1627 << MI);
1628 return false;
1629 }
1630
1631 Register PrevDstReg = PrevCopy->second->getOperand(i: 0).getReg();
1632 if (PrevDstReg == SrcReg) {
1633 // Remove the virt->phys copy: we saw the virtual register definition, and
1634 // the non-allocatable physical register's state hasn't changed since then.
1635 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
1636 ++NumNAPhysCopies;
1637 return true;
1638 }
1639
1640 // Potential missed optimization opportunity: we saw a different virtual
1641 // register get a copy of the non-allocatable physical register, and we only
1642 // track one such copy. Avoid getting confused by this new non-allocatable
1643 // physical register definition, and remove it from the tracked copies.
1644 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
1645 NAPhysToVirtMIs.erase(I: PrevCopy);
1646 return false;
1647}
1648
1649/// \bried Returns true if \p MO is a virtual register operand.
1650static bool isVirtualRegisterOperand(MachineOperand &MO) {
1651 return MO.isReg() && MO.getReg().isVirtual();
1652}
1653
1654bool PeepholeOptimizer::findTargetRecurrence(
1655 Register Reg, const SmallSet<Register, 2> &TargetRegs,
1656 RecurrenceCycle &RC) {
1657 // Recurrence found if Reg is in TargetRegs.
1658 if (TargetRegs.count(V: Reg))
1659 return true;
1660
1661 // TODO: Curerntly, we only allow the last instruction of the recurrence
1662 // cycle (the instruction that feeds the PHI instruction) to have more than
1663 // one uses to guarantee that commuting operands does not tie registers
1664 // with overlapping live range. Once we have actual live range info of
1665 // each register, this constraint can be relaxed.
1666 if (!MRI->hasOneNonDBGUse(RegNo: Reg))
1667 return false;
1668
1669 // Give up if the reccurrence chain length is longer than the limit.
1670 if (RC.size() >= MaxRecurrenceChain)
1671 return false;
1672
1673 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(RegNo: Reg));
1674 unsigned Idx = MI.findRegisterUseOperandIdx(Reg, /*TRI=*/nullptr);
1675
1676 // Only interested in recurrences whose instructions have only one def, which
1677 // is a virtual register.
1678 if (MI.getDesc().getNumDefs() != 1)
1679 return false;
1680
1681 MachineOperand &DefOp = MI.getOperand(i: 0);
1682 if (!isVirtualRegisterOperand(MO&: DefOp))
1683 return false;
1684
1685 // Check if def operand of MI is tied to any use operand. We are only
1686 // interested in the case that all the instructions in the recurrence chain
1687 // have there def operand tied with one of the use operand.
1688 unsigned TiedUseIdx;
1689 if (!MI.isRegTiedToUseOperand(DefOpIdx: 0, UseOpIdx: &TiedUseIdx))
1690 return false;
1691
1692 if (Idx == TiedUseIdx) {
1693 RC.push_back(Elt: RecurrenceInstr(&MI));
1694 return findTargetRecurrence(Reg: DefOp.getReg(), TargetRegs, RC);
1695 } else {
1696 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1697 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1698 if (TII->findCommutedOpIndices(MI, SrcOpIdx1&: Idx, SrcOpIdx2&: CommIdx) && CommIdx == TiedUseIdx) {
1699 RC.push_back(Elt: RecurrenceInstr(&MI, Idx, CommIdx));
1700 return findTargetRecurrence(Reg: DefOp.getReg(), TargetRegs, RC);
1701 }
1702 }
1703
1704 return false;
1705}
1706
1707/// Phi instructions will eventually be lowered to copy instructions.
1708/// If phi is in a loop header, a recurrence may formulated around the source
1709/// and destination of the phi. For such case commuting operands of the
1710/// instructions in the recurrence may enable coalescing of the copy instruction
1711/// generated from the phi. For example, if there is a recurrence of
1712///
1713/// LoopHeader:
1714/// %1 = phi(%0, %100)
1715/// LoopLatch:
1716/// %0<def, tied1> = ADD %2<def, tied0>, %1
1717///
1718/// , the fact that %0 and %2 are in the same tied operands set makes
1719/// the coalescing of copy instruction generated from the phi in
1720/// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1721/// %2 have overlapping live range. This introduces additional move
1722/// instruction to the final assembly. However, if we commute %2 and
1723/// %1 of ADD instruction, the redundant move instruction can be
1724/// avoided.
1725bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1726 SmallSet<Register, 2> TargetRegs;
1727 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1728 MachineOperand &MO = PHI.getOperand(i: Idx);
1729 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1730 TargetRegs.insert(V: MO.getReg());
1731 }
1732
1733 bool Changed = false;
1734 RecurrenceCycle RC;
1735 if (findTargetRecurrence(Reg: PHI.getOperand(i: 0).getReg(), TargetRegs, RC)) {
1736 // Commutes operands of instructions in RC if necessary so that the copy to
1737 // be generated from PHI can be coalesced.
1738 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1739 for (auto &RI : RC) {
1740 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1741 auto CP = RI.getCommutePair();
1742 if (CP) {
1743 Changed = true;
1744 TII->commuteInstruction(MI&: *(RI.getMI()), NewMI: false, OpIdx1: (*CP).first,
1745 OpIdx2: (*CP).second);
1746 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1747 }
1748 }
1749 }
1750
1751 return Changed;
1752}
1753
1754PreservedAnalyses
1755PeepholeOptimizerPass::run(MachineFunction &MF,
1756 MachineFunctionAnalysisManager &MFAM) {
1757 MFPropsModifier _(*this, MF);
1758 auto *DT =
1759 Aggressive ? &MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF) : nullptr;
1760 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(IR&: MF);
1761 PeepholeOptimizer Impl(DT, MLI);
1762 bool Changed = Impl.run(MF);
1763 if (!Changed)
1764 return PreservedAnalyses::all();
1765
1766 auto PA = getMachineFunctionPassPreservedAnalyses();
1767 PA.preserveSet<CFGAnalyses>();
1768 return PA;
1769}
1770
1771bool PeepholeOptimizerLegacy::runOnMachineFunction(MachineFunction &MF) {
1772 if (skipFunction(F: MF.getFunction()))
1773 return false;
1774 auto *DT = Aggressive
1775 ? &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree()
1776 : nullptr;
1777 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1778 PeepholeOptimizer Impl(DT, MLI);
1779 return Impl.run(MF);
1780}
1781
1782bool PeepholeOptimizer::run(MachineFunction &MF) {
1783
1784 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1785 LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1786
1787 if (DisablePeephole)
1788 return false;
1789
1790 TII = MF.getSubtarget().getInstrInfo();
1791 TRI = MF.getSubtarget().getRegisterInfo();
1792 MRI = &MF.getRegInfo();
1793 MF.setDelegate(this);
1794
1795 bool Changed = false;
1796
1797 for (MachineBasicBlock &MBB : MF) {
1798 bool SeenMoveImm = false;
1799
1800 // During this forward scan, at some point it needs to answer the question
1801 // "given a pointer to an MI in the current BB, is it located before or
1802 // after the current instruction".
1803 // To perform this, the following set keeps track of the MIs already seen
1804 // during the scan, if a MI is not in the set, it is assumed to be located
1805 // after. Newly created MIs have to be inserted in the set as well.
1806 SmallPtrSet<MachineInstr *, 16> LocalMIs;
1807 SmallSet<Register, 4> ImmDefRegs;
1808 DenseMap<Register, MachineInstr *> ImmDefMIs;
1809 SmallSet<Register, 16> FoldAsLoadDefCandidates;
1810
1811 // Track when a non-allocatable physical register is copied to a virtual
1812 // register so that useless moves can be removed.
1813 //
1814 // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
1815 // without any intervening re-definition of $physreg.
1816 DenseMap<Register, MachineInstr *> NAPhysToVirtMIs;
1817
1818 CopySrcMIs.clear();
1819
1820 bool IsLoopHeader = MLI->isLoopHeader(BB: &MBB);
1821
1822 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1823 MII != MIE;) {
1824 MachineInstr *MI = &*MII;
1825 // We may be erasing MI below, increment MII now.
1826 ++MII;
1827 LocalMIs.insert(Ptr: MI);
1828
1829 // Skip debug instructions. They should not affect this peephole
1830 // optimization.
1831 if (MI->isDebugInstr())
1832 continue;
1833
1834 if (MI->isPosition())
1835 continue;
1836
1837 if (IsLoopHeader && MI->isPHI()) {
1838 if (optimizeRecurrence(PHI&: *MI)) {
1839 Changed = true;
1840 continue;
1841 }
1842 }
1843
1844 if (!MI->isCopy()) {
1845 for (const MachineOperand &MO : MI->operands()) {
1846 // Visit all operands: definitions can be implicit or explicit.
1847 if (MO.isReg()) {
1848 Register Reg = MO.getReg();
1849 if (MO.isDef() && isNAPhysCopy(Reg)) {
1850 const auto &Def = NAPhysToVirtMIs.find(Val: Reg);
1851 if (Def != NAPhysToVirtMIs.end()) {
1852 // A new definition of the non-allocatable physical register
1853 // invalidates previous copies.
1854 LLVM_DEBUG(dbgs()
1855 << "NAPhysCopy: invalidating because of " << *MI);
1856 NAPhysToVirtMIs.erase(I: Def);
1857 }
1858 }
1859 } else if (MO.isRegMask()) {
1860 const uint32_t *RegMask = MO.getRegMask();
1861 NAPhysToVirtMIs.remove_if(Pred: [&](const auto &RegMI) {
1862 if (!MachineOperand::clobbersPhysReg(RegMask, RegMI.first))
1863 return false;
1864 LLVM_DEBUG(dbgs()
1865 << "NAPhysCopy: invalidating because of " << *MI);
1866 return true;
1867 });
1868 }
1869 }
1870 }
1871
1872 if (MI->isImplicitDef() || MI->isKill())
1873 continue;
1874
1875 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1876 // Blow away all non-allocatable physical registers knowledge since we
1877 // don't know what's correct anymore.
1878 //
1879 // FIXME: handle explicit asm clobbers.
1880 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1881 << *MI);
1882 NAPhysToVirtMIs.clear();
1883 }
1884
1885 if (MI->isCompare() && optimizeCmpInstr(MI&: *MI, MF, LocalMIs)) {
1886 Changed = true;
1887 continue;
1888 }
1889
1890 if ((isUncoalescableCopy(MI: *MI) &&
1891 optimizeUncoalescableCopy(MI&: *MI, LocalMIs)) ||
1892 (MI->isSelect() && optimizeSelect(MI&: *MI, LocalMIs))) {
1893 // MI is deleted.
1894 LocalMIs.erase(Ptr: MI);
1895 Changed = true;
1896 continue;
1897 }
1898
1899 if (MI->isConditionalBranch() && optimizeCondBranch(MI&: *MI)) {
1900 Changed = true;
1901 continue;
1902 }
1903
1904 if (isCoalescableCopy(MI: *MI) && optimizeCoalescableCopy(MI&: *MI)) {
1905 // MI is just rewritten.
1906 Changed = true;
1907 continue;
1908 }
1909
1910 if (MI->isCopy() && (foldRedundantCopy(MI&: *MI) ||
1911 foldRedundantNAPhysCopy(MI&: *MI, NAPhysToVirtMIs))) {
1912 LocalMIs.erase(Ptr: MI);
1913 LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
1914 MI->eraseFromParent();
1915 Changed = true;
1916 continue;
1917 }
1918
1919 if (isMoveImmediate(MI&: *MI, ImmDefRegs, ImmDefMIs)) {
1920 SeenMoveImm = true;
1921 } else {
1922 Changed |= optimizeExtInstr(MI&: *MI, MBB, LocalMIs);
1923 // optimizeExtInstr might have created new instructions after MI
1924 // and before the already incremented MII. Adjust MII so that the
1925 // next iteration sees the new instructions.
1926 MII = MI;
1927 ++MII;
1928 if (SeenMoveImm) {
1929 bool Deleted;
1930 Changed |= foldImmediate(MI&: *MI, ImmDefRegs, ImmDefMIs, Deleted);
1931 if (Deleted) {
1932 LocalMIs.erase(Ptr: MI);
1933 continue;
1934 }
1935 }
1936 }
1937
1938 // Check whether MI is a load candidate for folding into a later
1939 // instruction. If MI is not a candidate, check whether we can fold an
1940 // earlier load into MI.
1941 if (!isLoadFoldable(MI&: *MI, FoldAsLoadDefCandidates) &&
1942 !FoldAsLoadDefCandidates.empty()) {
1943
1944 // We visit each operand even after successfully folding a previous
1945 // one. This allows us to fold multiple loads into a single
1946 // instruction. We do assume that optimizeLoadInstr doesn't insert
1947 // foldable uses earlier in the argument list. Since we don't restart
1948 // iteration, we'd miss such cases.
1949 const MCInstrDesc &MIDesc = MI->getDesc();
1950 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands(); ++i) {
1951 const MachineOperand &MOp = MI->getOperand(i);
1952 if (!MOp.isReg())
1953 continue;
1954 Register FoldAsLoadDefReg = MOp.getReg();
1955 if (FoldAsLoadDefCandidates.count(V: FoldAsLoadDefReg)) {
1956 // We need to fold load after optimizeCmpInstr, since
1957 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1958 Register FoldedReg = FoldAsLoadDefReg;
1959 if (MachineInstr *FoldMI =
1960 foldLoadInto(MF, MI&: *MI, FoldReg: FoldAsLoadDefReg, LocalMIs)) {
1961 FoldAsLoadDefCandidates.erase(V: FoldedReg);
1962 // MI is replaced with FoldMI so we can continue trying to fold
1963 Changed = true;
1964 MI = FoldMI;
1965 }
1966 }
1967 }
1968 }
1969
1970 // If we run into an instruction we can't fold across, discard
1971 // the load candidates. Note: We might be able to fold *into* this
1972 // instruction, so this needs to be after the folding logic.
1973 if (MI->isLoadFoldBarrier()) {
1974 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
1975 FoldAsLoadDefCandidates.clear();
1976 }
1977 }
1978 }
1979
1980 MF.resetDelegate(delegate: this);
1981 return Changed;
1982}
1983
1984ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1985 assert(Def->isCopy() && "Invalid definition");
1986 // Copy instruction are supposed to be: Def = Src.
1987 // If someone breaks this assumption, bad things will happen everywhere.
1988 // There may be implicit uses preventing the copy to be moved across
1989 // some target specific register definitions
1990 assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
1991 "Invalid number of operands");
1992 assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
1993 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
1994
1995 // Otherwise, we want the whole source.
1996 const MachineOperand &Src = Def->getOperand(i: 1);
1997 if (Src.isUndef())
1998 return ValueTrackerResult();
1999
2000 Register SrcReg = Src.getReg();
2001 unsigned SubReg = Src.getSubReg();
2002 if (DefSubReg) {
2003 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2004 SubReg = TRI->composeSubRegIndices(a: SubReg, b: DefSubReg);
2005
2006 if (SrcReg.isVirtual()) {
2007 // TODO: Try constraining on rewrite if we can
2008 const TargetRegisterClass *RegRC = MRI.getRegClass(Reg: SrcReg);
2009 if (!TRI->isSubRegValidForRegClass(RC: RegRC, Idx: SubReg))
2010 return ValueTrackerResult();
2011 } else {
2012 if (!TRI->getSubReg(Reg: SrcReg, Idx: SubReg))
2013 return ValueTrackerResult();
2014 }
2015 }
2016
2017 return ValueTrackerResult(SrcReg, SubReg);
2018}
2019
2020ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
2021 assert(Def->isBitcast() && "Invalid definition");
2022
2023 // Bail if there are effects that a plain copy will not expose.
2024 if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
2025 return ValueTrackerResult();
2026
2027 // Bitcasts with more than one def are not supported.
2028 if (Def->getDesc().getNumDefs() != 1)
2029 return ValueTrackerResult();
2030
2031 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
2032
2033 unsigned SrcIdx = Def->getNumOperands();
2034 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
2035 ++OpIdx) {
2036 const MachineOperand &MO = Def->getOperand(i: OpIdx);
2037 if (!MO.isReg() || !MO.getReg())
2038 continue;
2039 // Ignore dead implicit defs.
2040 if (MO.isImplicit() && MO.isDead())
2041 continue;
2042 assert(!MO.isDef() && "We should have skipped all the definitions by now");
2043 if (SrcIdx != EndOpIdx)
2044 // Multiple sources?
2045 return ValueTrackerResult();
2046 SrcIdx = OpIdx;
2047 }
2048
2049 // In some rare case, Def has no input, SrcIdx is out of bound,
2050 // getOperand(SrcIdx) will fail below.
2051 if (SrcIdx >= Def->getNumOperands())
2052 return ValueTrackerResult();
2053
2054 const MachineOperand &DefOp = Def->getOperand(i: DefIdx);
2055
2056 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
2057 // will break the assumed guarantees for the upper bits.
2058 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(Reg: DefOp.getReg())) {
2059 if (UseMI.isSubregToReg())
2060 return ValueTrackerResult();
2061 }
2062
2063 const MachineOperand &Src = Def->getOperand(i: SrcIdx);
2064 if (Src.isUndef())
2065 return ValueTrackerResult();
2066 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
2067}
2068
2069ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
2070 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
2071 "Invalid definition");
2072
2073 assert(!Def->getOperand(DefIdx).getSubReg() && "illegal subregister def");
2074
2075 SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
2076 if (!TII->getRegSequenceInputs(MI: *Def, DefIdx, InputRegs&: RegSeqInputRegs))
2077 return ValueTrackerResult();
2078
2079 // We are looking at:
2080 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
2081 //
2082 // Check if one of the operands exactly defines the subreg we are interested
2083 // in.
2084 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2085 if (RegSeqInput.SubIdx == DefSubReg)
2086 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
2087 }
2088
2089 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2090
2091 // If we did not find an exact match, see if we can do a composition to
2092 // extract a sub-subregister.
2093 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2094 LaneBitmask DefMask = TRI->getSubRegIndexLaneMask(SubIdx: DefSubReg);
2095 LaneBitmask ThisOpRegMask = TRI->getSubRegIndexLaneMask(SubIdx: RegSeqInput.SubIdx);
2096
2097 // Check that this extract reads a subset of this single reg_sequence input.
2098 //
2099 // FIXME: We should be able to filter this in terms of the indexes directly
2100 // without checking the lanemasks.
2101 if ((DefMask & ThisOpRegMask) != DefMask)
2102 continue;
2103
2104 unsigned ReverseDefCompose =
2105 TRI->reverseComposeSubRegIndices(a: RegSeqInput.SubIdx, b: DefSubReg);
2106 if (!ReverseDefCompose)
2107 continue;
2108
2109 unsigned ComposedDefInSrcReg1 =
2110 TRI->composeSubRegIndices(a: RegSeqInput.SubReg, b: ReverseDefCompose);
2111
2112 // TODO: We should be able to defer checking if the result register class
2113 // supports the index to continue looking for a rewritable source.
2114 //
2115 // TODO: Should we modify the register class to support the index?
2116 const TargetRegisterClass *SrcRC = MRI.getRegClass(Reg: RegSeqInput.Reg);
2117 if (!TRI->isSubRegValidForRegClass(RC: SrcRC, Idx: ComposedDefInSrcReg1))
2118 return ValueTrackerResult();
2119
2120 return ValueTrackerResult(RegSeqInput.Reg, ComposedDefInSrcReg1);
2121 }
2122
2123 // If the subreg we are tracking is super-defined by another subreg,
2124 // we could follow this value. However, this would require to compose
2125 // the subreg and we do not do that for now.
2126 return ValueTrackerResult();
2127}
2128
2129ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
2130 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
2131 "Invalid definition");
2132 assert(!Def->getOperand(DefIdx).getSubReg() && "no subreg defs in SSA");
2133
2134 RegSubRegPair BaseReg;
2135 RegSubRegPairAndIdx InsertedReg;
2136 if (!TII->getInsertSubregInputs(MI: *Def, DefIdx, BaseReg, InsertedReg))
2137 return ValueTrackerResult();
2138
2139 // We are looking at:
2140 // Def = INSERT_SUBREG v0, v1, sub1
2141 // There are two cases:
2142 // 1. DefSubReg == sub1, get v1.
2143 // 2. DefSubReg != sub1, the value may be available through v0.
2144
2145 // #1 Check if the inserted register matches the required sub index.
2146 if (InsertedReg.SubIdx == DefSubReg) {
2147 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
2148 }
2149 // #2 Otherwise, if the sub register we are looking for is not partial
2150 // defined by the inserted element, we can look through the main
2151 // register (v0).
2152 const MachineOperand &MODef = Def->getOperand(i: DefIdx);
2153 // If the result register (Def) and the base register (v0) do not
2154 // have the same register class or if we have to compose
2155 // subregisters, bail out.
2156 if (MRI.getRegClass(Reg: MODef.getReg()) != MRI.getRegClass(Reg: BaseReg.Reg) ||
2157 BaseReg.SubReg)
2158 return ValueTrackerResult();
2159
2160 // Get the TRI and check if the inserted sub-register overlaps with the
2161 // sub-register we are tracking.
2162 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2163 if ((TRI->getSubRegIndexLaneMask(SubIdx: DefSubReg) &
2164 TRI->getSubRegIndexLaneMask(SubIdx: InsertedReg.SubIdx))
2165 .any())
2166 return ValueTrackerResult();
2167 // At this point, the value is available in v0 via the same subreg
2168 // we used for Def.
2169 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
2170}
2171
2172ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
2173 assert((Def->isExtractSubreg() || Def->isExtractSubregLike()) &&
2174 "Invalid definition");
2175 // We are looking at:
2176 // Def = EXTRACT_SUBREG v0, sub0
2177
2178 // Bail if we have to compose sub registers.
2179 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2180 if (DefSubReg)
2181 return ValueTrackerResult();
2182
2183 RegSubRegPairAndIdx ExtractSubregInputReg;
2184 if (!TII->getExtractSubregInputs(MI: *Def, DefIdx, InputReg&: ExtractSubregInputReg))
2185 return ValueTrackerResult();
2186
2187 // Bail if we have to compose sub registers.
2188 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2189 if (ExtractSubregInputReg.SubReg)
2190 return ValueTrackerResult();
2191 // Otherwise, the value is available in the v0.sub0.
2192 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2193 ExtractSubregInputReg.SubIdx);
2194}
2195
2196ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2197 assert(Def->isSubregToReg() && "Invalid definition");
2198 // We are looking at:
2199 // Def = SUBREG_TO_REG v0, sub0
2200
2201 // Bail if we have to compose sub registers.
2202 // If DefSubReg != sub0, we would have to check that all the bits
2203 // we track are included in sub0 and if yes, we would have to
2204 // determine the right subreg in v0.
2205 if (DefSubReg != Def->getOperand(i: 2).getImm())
2206 return ValueTrackerResult();
2207 // Bail if we have to compose sub registers.
2208 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2209 if (Def->getOperand(i: 1).getSubReg())
2210 return ValueTrackerResult();
2211
2212 return ValueTrackerResult(Def->getOperand(i: 1).getReg(),
2213 Def->getOperand(i: 2).getImm());
2214}
2215
2216/// Explore each PHI incoming operand and return its sources.
2217ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2218 assert(Def->isPHI() && "Invalid definition");
2219 ValueTrackerResult Res;
2220
2221 // Return all register sources for PHI instructions.
2222 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2223 const MachineOperand &MO = Def->getOperand(i);
2224 assert(MO.isReg() && "Invalid PHI instruction");
2225 // We have no code to deal with undef operands. They shouldn't happen in
2226 // normal programs anyway.
2227 if (MO.isUndef())
2228 return ValueTrackerResult();
2229 Res.addSource(SrcReg: MO.getReg(), SrcSubReg: MO.getSubReg());
2230 }
2231
2232 return Res;
2233}
2234
2235ValueTrackerResult ValueTracker::getNextSourceImpl() {
2236 assert(Def && "This method needs a valid definition");
2237
2238 assert(((Def->getOperand(DefIdx).isDef() &&
2239 (DefIdx < Def->getDesc().getNumDefs() ||
2240 Def->getDesc().isVariadic())) ||
2241 Def->getOperand(DefIdx).isImplicit()) &&
2242 "Invalid DefIdx");
2243 if (Def->isCopy())
2244 return getNextSourceFromCopy();
2245 if (Def->isBitcast())
2246 return getNextSourceFromBitcast();
2247 // All the remaining cases involve "complex" instructions.
2248 // Bail if we did not ask for the advanced tracking.
2249 if (DisableAdvCopyOpt)
2250 return ValueTrackerResult();
2251 if (Def->isRegSequence() || Def->isRegSequenceLike())
2252 return getNextSourceFromRegSequence();
2253 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2254 return getNextSourceFromInsertSubreg();
2255 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2256 return getNextSourceFromExtractSubreg();
2257 if (Def->isSubregToReg())
2258 return getNextSourceFromSubregToReg();
2259 if (Def->isPHI())
2260 return getNextSourceFromPHI();
2261 return ValueTrackerResult();
2262}
2263
2264ValueTrackerResult ValueTracker::getNextSource() {
2265 // If we reach a point where we cannot move up in the use-def chain,
2266 // there is nothing we can get.
2267 if (!Def)
2268 return ValueTrackerResult();
2269
2270 ValueTrackerResult Res = getNextSourceImpl();
2271 if (Res.isValid()) {
2272 // Update definition, definition index, and subregister for the
2273 // next call of getNextSource.
2274 // Update the current register.
2275 bool OneRegSrc = Res.getNumSources() == 1;
2276 if (OneRegSrc)
2277 Reg = Res.getSrcReg(Idx: 0);
2278 // Update the result before moving up in the use-def chain
2279 // with the instruction containing the last found sources.
2280 Res.setInst(Def);
2281
2282 // If we can still move up in the use-def chain, move to the next
2283 // definition.
2284 if (!Reg.isPhysical() && OneRegSrc) {
2285 MachineRegisterInfo::def_iterator DI = MRI.def_begin(RegNo: Reg);
2286 if (DI != MRI.def_end()) {
2287 Def = DI->getParent();
2288 DefIdx = DI.getOperandNo();
2289 DefSubReg = Res.getSrcSubReg(Idx: 0);
2290 } else {
2291 Def = nullptr;
2292 }
2293 return Res;
2294 }
2295 }
2296 // If we end up here, this means we will not be able to find another source
2297 // for the next iteration. Make sure any new call to getNextSource bails out
2298 // early by cutting the use-def chain.
2299 Def = nullptr;
2300 return Res;
2301}
2302