Coverage Report

Created: 2019-07-24 05:18

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