Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/MachineSink.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MachineSink.cpp - Sinking for machine instructions -----------------===//
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
// This pass moves instructions into successor blocks when possible, so that
10
// they aren't executed on paths where their results aren't needed.
11
//
12
// This pass is not intended to be a replacement or a complete alternative
13
// for an LLVM-IR-level sinking pass. It is only designed to sink simple
14
// constructs that are not exposed before lowering and instruction selection.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "llvm/ADT/SetVector.h"
19
#include "llvm/ADT/SmallSet.h"
20
#include "llvm/ADT/SmallVector.h"
21
#include "llvm/ADT/SparseBitVector.h"
22
#include "llvm/ADT/Statistic.h"
23
#include "llvm/Analysis/AliasAnalysis.h"
24
#include "llvm/CodeGen/MachineBasicBlock.h"
25
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27
#include "llvm/CodeGen/MachineDominators.h"
28
#include "llvm/CodeGen/MachineFunction.h"
29
#include "llvm/CodeGen/MachineFunctionPass.h"
30
#include "llvm/CodeGen/MachineInstr.h"
31
#include "llvm/CodeGen/MachineLoopInfo.h"
32
#include "llvm/CodeGen/MachineOperand.h"
33
#include "llvm/CodeGen/MachinePostDominators.h"
34
#include "llvm/CodeGen/MachineRegisterInfo.h"
35
#include "llvm/CodeGen/TargetInstrInfo.h"
36
#include "llvm/CodeGen/TargetRegisterInfo.h"
37
#include "llvm/CodeGen/TargetSubtargetInfo.h"
38
#include "llvm/IR/BasicBlock.h"
39
#include "llvm/IR/LLVMContext.h"
40
#include "llvm/IR/DebugInfoMetadata.h"
41
#include "llvm/Pass.h"
42
#include "llvm/Support/BranchProbability.h"
43
#include "llvm/Support/CommandLine.h"
44
#include "llvm/Support/Debug.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <algorithm>
47
#include <cassert>
48
#include <cstdint>
49
#include <map>
50
#include <utility>
51
#include <vector>
52
53
using namespace llvm;
54
55
#define DEBUG_TYPE "machine-sink"
56
57
static cl::opt<bool>
58
SplitEdges("machine-sink-split",
59
           cl::desc("Split critical edges during machine sinking"),
60
           cl::init(true), cl::Hidden);
61
62
static cl::opt<bool>
63
UseBlockFreqInfo("machine-sink-bfi",
64
           cl::desc("Use block frequency info to find successors to sink"),
65
           cl::init(true), cl::Hidden);
66
67
static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
68
    "machine-sink-split-probability-threshold",
69
    cl::desc(
70
        "Percentage threshold for splitting single-instruction critical edge. "
71
        "If the branch threshold is higher than this threshold, we allow "
72
        "speculative execution of up to 1 instruction to avoid branching to "
73
        "splitted critical edge"),
74
    cl::init(40), cl::Hidden);
75
76
STATISTIC(NumSunk,      "Number of machine instructions sunk");
77
STATISTIC(NumSplit,     "Number of critical edges split");
78
STATISTIC(NumCoalesces, "Number of copies coalesced");
79
STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
80
81
namespace {
82
83
  class MachineSinking : public MachineFunctionPass {
84
    const TargetInstrInfo *TII;
85
    const TargetRegisterInfo *TRI;
86
    MachineRegisterInfo  *MRI;     // Machine register information
87
    MachineDominatorTree *DT;      // Machine dominator tree
88
    MachinePostDominatorTree *PDT; // Machine post dominator tree
89
    MachineLoopInfo *LI;
90
    const MachineBlockFrequencyInfo *MBFI;
91
    const MachineBranchProbabilityInfo *MBPI;
92
    AliasAnalysis *AA;
93
94
    // Remember which edges have been considered for breaking.
95
    SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
96
    CEBCandidates;
97
    // Remember which edges we are about to split.
98
    // This is different from CEBCandidates since those edges
99
    // will be split.
100
    SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
101
102
    SparseBitVector<> RegsToClearKillFlags;
103
104
    using AllSuccsCache =
105
        std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
106
107
  public:
108
    static char ID; // Pass identification
109
110
34.5k
    MachineSinking() : MachineFunctionPass(ID) {
111
34.5k
      initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
112
34.5k
    }
113
114
    bool runOnMachineFunction(MachineFunction &MF) override;
115
116
34.2k
    void getAnalysisUsage(AnalysisUsage &AU) const override {
117
34.2k
      AU.setPreservesCFG();
118
34.2k
      MachineFunctionPass::getAnalysisUsage(AU);
119
34.2k
      AU.addRequired<AAResultsWrapperPass>();
120
34.2k
      AU.addRequired<MachineDominatorTree>();
121
34.2k
      AU.addRequired<MachinePostDominatorTree>();
122
34.2k
      AU.addRequired<MachineLoopInfo>();
123
34.2k
      AU.addRequired<MachineBranchProbabilityInfo>();
124
34.2k
      AU.addPreserved<MachineDominatorTree>();
125
34.2k
      AU.addPreserved<MachinePostDominatorTree>();
126
34.2k
      AU.addPreserved<MachineLoopInfo>();
127
34.2k
      if (UseBlockFreqInfo)
128
34.2k
        AU.addRequired<MachineBlockFrequencyInfo>();
129
34.2k
    }
130
131
489k
    void releaseMemory() override {
132
489k
      CEBCandidates.clear();
133
489k
    }
134
135
  private:
136
    bool ProcessBlock(MachineBasicBlock &MBB);
137
    bool isWorthBreakingCriticalEdge(MachineInstr &MI,
138
                                     MachineBasicBlock *From,
139
                                     MachineBasicBlock *To);
140
141
    /// Postpone the splitting of the given critical
142
    /// edge (\p From, \p To).
143
    ///
144
    /// We do not split the edges on the fly. Indeed, this invalidates
145
    /// the dominance information and thus triggers a lot of updates
146
    /// of that information underneath.
147
    /// Instead, we postpone all the splits after each iteration of
148
    /// the main loop. That way, the information is at least valid
149
    /// for the lifetime of an iteration.
150
    ///
151
    /// \return True if the edge is marked as toSplit, false otherwise.
152
    /// False can be returned if, for instance, this is not profitable.
153
    bool PostponeSplitCriticalEdge(MachineInstr &MI,
154
                                   MachineBasicBlock *From,
155
                                   MachineBasicBlock *To,
156
                                   bool BreakPHIEdge);
157
    bool SinkInstruction(MachineInstr &MI, bool &SawStore,
158
159
                         AllSuccsCache &AllSuccessors);
160
    bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
161
                                 MachineBasicBlock *DefMBB,
162
                                 bool &BreakPHIEdge, bool &LocalUse) const;
163
    MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
164
               bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
165
    bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
166
                              MachineBasicBlock *MBB,
167
                              MachineBasicBlock *SuccToSinkTo,
168
                              AllSuccsCache &AllSuccessors);
169
170
    bool PerformTrivialForwardCoalescing(MachineInstr &MI,
171
                                         MachineBasicBlock *MBB);
172
173
    SmallVector<MachineBasicBlock *, 4> &
174
    GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
175
                           AllSuccsCache &AllSuccessors) const;
176
  };
177
178
} // end anonymous namespace
179
180
char MachineSinking::ID = 0;
181
182
char &llvm::MachineSinkingID = MachineSinking::ID;
183
184
42.3k
INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
185
42.3k
                      "Machine code sinking", false, false)
186
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
187
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
188
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
189
42.3k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
190
42.3k
INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
191
                    "Machine code sinking", false, false)
192
193
bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
194
27.9M
                                                     MachineBasicBlock *MBB) {
195
27.9M
  if (!MI.isCopy())
196
22.7M
    return false;
197
5.15M
198
5.15M
  unsigned SrcReg = MI.getOperand(1).getReg();
199
5.15M
  unsigned DstReg = MI.getOperand(0).getReg();
200
5.15M
  if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
201
5.15M
      
!TargetRegisterInfo::isVirtualRegister(DstReg)3.66M
||
202
5.15M
      
!MRI->hasOneNonDBGUse(SrcReg)1.48M
)
203
4.59M
    return false;
204
560k
205
560k
  const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
206
560k
  const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
207
560k
  if (SRC != DRC)
208
479k
    return false;
209
81.5k
210
81.5k
  MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
211
81.5k
  if (DefMI->isCopyLike())
212
69.4k
    return false;
213
12.0k
  LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
214
12.0k
  LLVM_DEBUG(dbgs() << "*** to: " << MI);
215
12.0k
  MRI->replaceRegWith(DstReg, SrcReg);
216
12.0k
  MI.eraseFromParent();
217
12.0k
218
12.0k
  // Conservatively, clear any kill flags, since it's possible that they are no
219
12.0k
  // longer correct.
220
12.0k
  MRI->clearKillFlags(SrcReg);
221
12.0k
222
12.0k
  ++NumCoalesces;
223
12.0k
  return true;
224
12.0k
}
225
226
/// AllUsesDominatedByBlock - Return true if all uses of the specified register
227
/// occur in blocks dominated by the specified block. If any use is in the
228
/// definition block, then return false since it is never legal to move def
229
/// after uses.
230
bool
231
MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
232
                                        MachineBasicBlock *MBB,
233
                                        MachineBasicBlock *DefMBB,
234
                                        bool &BreakPHIEdge,
235
17.8M
                                        bool &LocalUse) const {
236
17.8M
  assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
237
17.8M
         "Only makes sense for vregs");
238
17.8M
239
17.8M
  // Ignore debug uses because debug info doesn't affect the code.
240
17.8M
  if (MRI->use_nodbg_empty(Reg))
241
576k
    return true;
242
17.2M
243
17.2M
  // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
244
17.2M
  // into and they are all PHI nodes. In this case, machine-sink must break
245
17.2M
  // the critical edge first. e.g.
246
17.2M
  //
247
17.2M
  // %bb.1: derived from LLVM BB %bb4.preheader
248
17.2M
  //   Predecessors according to CFG: %bb.0
249
17.2M
  //     ...
250
17.2M
  //     %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
251
17.2M
  //     ...
252
17.2M
  //     JE_4 <%bb.37>, implicit %eflags
253
17.2M
  //   Successors according to CFG: %bb.37 %bb.2
254
17.2M
  //
255
17.2M
  // %bb.2: derived from LLVM BB %bb.nph
256
17.2M
  //   Predecessors according to CFG: %bb.0 %bb.1
257
17.2M
  //     %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
258
17.2M
  BreakPHIEdge = true;
259
17.5M
  for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
260
17.5M
    MachineInstr *UseInst = MO.getParent();
261
17.5M
    unsigned OpNo = &MO - &UseInst->getOperand(0);
262
17.5M
    MachineBasicBlock *UseBlock = UseInst->getParent();
263
17.5M
    if (!(UseBlock == MBB && 
UseInst->isPHI()2.99M
&&
264
17.5M
          
UseInst->getOperand(OpNo+1).getMBB() == DefMBB961k
)) {
265
16.6M
      BreakPHIEdge = false;
266
16.6M
      break;
267
16.6M
    }
268
17.5M
  }
269
17.2M
  if (BreakPHIEdge)
270
531k
    return true;
271
16.6M
272
23.4M
  
for (MachineOperand &MO : MRI->use_nodbg_operands(Reg))16.6M
{
273
23.4M
    // Determine the block of the use.
274
23.4M
    MachineInstr *UseInst = MO.getParent();
275
23.4M
    unsigned OpNo = &MO - &UseInst->getOperand(0);
276
23.4M
    MachineBasicBlock *UseBlock = UseInst->getParent();
277
23.4M
    if (UseInst->isPHI()) {
278
2.32M
      // PHI nodes use the operand in the predecessor block, not the block with
279
2.32M
      // the PHI.
280
2.32M
      UseBlock = UseInst->getOperand(OpNo+1).getMBB();
281
21.1M
    } else if (UseBlock == DefMBB) {
282
7.44M
      LocalUse = true;
283
7.44M
      return false;
284
7.44M
    }
285
16.0M
286
16.0M
    // Check that it dominates.
287
16.0M
    if (!DT->dominates(MBB, UseBlock))
288
5.52M
      return false;
289
16.0M
  }
290
16.6M
291
16.6M
  
return true3.71M
;
292
16.6M
}
293
294
489k
bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
295
489k
  if (skipFunction(MF.getFunction()))
296
270
    return false;
297
489k
298
489k
  LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
299
489k
300
489k
  TII = MF.getSubtarget().getInstrInfo();
301
489k
  TRI = MF.getSubtarget().getRegisterInfo();
302
489k
  MRI = &MF.getRegInfo();
303
489k
  DT = &getAnalysis<MachineDominatorTree>();
304
489k
  PDT = &getAnalysis<MachinePostDominatorTree>();
305
489k
  LI = &getAnalysis<MachineLoopInfo>();
306
489k
  MBFI = UseBlockFreqInfo ? 
&getAnalysis<MachineBlockFrequencyInfo>()489k
:
nullptr1
;
307
489k
  MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
308
489k
  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
309
489k
310
489k
  bool EverMadeChange = false;
311
489k
312
624k
  while (
true624k
) {
313
624k
    bool MadeChange = false;
314
624k
315
624k
    // Process all basic blocks.
316
624k
    CEBCandidates.clear();
317
624k
    ToSplit.clear();
318
624k
    for (auto &MBB: MF)
319
5.75M
      MadeChange |= ProcessBlock(MBB);
320
624k
321
624k
    // If we have anything we marked as toSplit, split it now.
322
624k
    for (auto &Pair : ToSplit) {
323
90.4k
      auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
324
90.4k
      if (NewSucc != nullptr) {
325
89.4k
        LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
326
89.4k
                          << printMBBReference(*Pair.first) << " -- "
327
89.4k
                          << printMBBReference(*NewSucc) << " -- "
328
89.4k
                          << printMBBReference(*Pair.second) << '\n');
329
89.4k
        MadeChange = true;
330
89.4k
        ++NumSplit;
331
89.4k
      } else
332
90.4k
        LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
333
90.4k
    }
334
624k
    // If this iteration over the code changed anything, keep iterating.
335
624k
    if (!MadeChange) 
break489k
;
336
134k
    EverMadeChange = true;
337
134k
  }
338
489k
339
489k
  // Now clear any kill flags for recorded registers.
340
489k
  for (auto I : RegsToClearKillFlags)
341
409k
    MRI->clearKillFlags(I);
342
489k
  RegsToClearKillFlags.clear();
343
489k
344
489k
  return EverMadeChange;
345
489k
}
346
347
5.75M
bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
348
5.75M
  // Can't sink anything out of a block that has less than two successors.
349
5.75M
  if (MBB.succ_size() <= 1 || 
MBB.empty()2.95M
)
return false2.80M
;
350
2.95M
351
2.95M
  // Don't bother sinking code out of unreachable blocks. In addition to being
352
2.95M
  // unprofitable, it can also lead to infinite looping, because in an
353
2.95M
  // unreachable loop there may be nowhere to stop.
354
2.95M
  if (!DT->isReachableFromEntry(&MBB)) 
return false0
;
355
2.95M
356
2.95M
  bool MadeChange = false;
357
2.95M
358
2.95M
  // Cache all successors, sorted by frequency info and loop depth.
359
2.95M
  AllSuccsCache AllSuccessors;
360
2.95M
361
2.95M
  // Walk the basic block bottom-up.  Remember if we saw a store.
362
2.95M
  MachineBasicBlock::iterator I = MBB.end();
363
2.95M
  --I;
364
2.95M
  bool ProcessedBegin, SawStore = false;
365
27.9M
  do {
366
27.9M
    MachineInstr &MI = *I;  // The instruction to sink.
367
27.9M
368
27.9M
    // Predecrement I (if it's not begin) so that it isn't invalidated by
369
27.9M
    // sinking.
370
27.9M
    ProcessedBegin = I == MBB.begin();
371
27.9M
    if (!ProcessedBegin)
372
24.9M
      --I;
373
27.9M
374
27.9M
    if (MI.isDebugInstr())
375
524
      continue;
376
27.9M
377
27.9M
    bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
378
27.9M
    if (Joined) {
379
12.0k
      MadeChange = true;
380
12.0k
      continue;
381
12.0k
    }
382
27.9M
383
27.9M
    if (SinkInstruction(MI, SawStore, AllSuccessors)) {
384
2.89M
      ++NumSunk;
385
2.89M
      MadeChange = true;
386
2.89M
    }
387
27.9M
388
27.9M
    // If we just processed the first instruction in the block, we're done.
389
27.9M
  } while (!ProcessedBegin);
390
2.95M
391
2.95M
  return MadeChange;
392
2.95M
}
393
394
bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
395
                                                 MachineBasicBlock *From,
396
356k
                                                 MachineBasicBlock *To) {
397
356k
  // FIXME: Need much better heuristics.
398
356k
399
356k
  // If the pass has already considered breaking this edge (during this pass
400
356k
  // through the function), then let's go ahead and break it. This means
401
356k
  // sinking multiple "cheap" instructions into the same block.
402
356k
  if (!CEBCandidates.insert(std::make_pair(From, To)).second)
403
100k
    return true;
404
256k
405
256k
  if (!MI.isCopy() && 
!TII->isAsCheapAsAMove(MI)139k
)
406
70.2k
    return true;
407
185k
408
185k
  if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
409
185k
      BranchProbability(SplitEdgeProbabilityThreshold, 100))
410
24.6k
    return true;
411
161k
412
161k
  // MI is cheap, we probably don't want to break the critical edge for it.
413
161k
  // However, if this would allow some definitions of its source operands
414
161k
  // to be sunk then it's probably worth it.
415
484k
  
for (unsigned i = 0, e = MI.getNumOperands(); 161k
i != e;
++i323k
) {
416
350k
    const MachineOperand &MO = MI.getOperand(i);
417
350k
    if (!MO.isReg() || 
!MO.isUse()303k
)
418
209k
      continue;
419
141k
    unsigned Reg = MO.getReg();
420
141k
    if (Reg == 0)
421
30
      continue;
422
140k
423
140k
    // We don't move live definitions of physical registers,
424
140k
    // so sinking their uses won't enable any opportunities.
425
140k
    if (TargetRegisterInfo::isPhysicalRegister(Reg))
426
41
      continue;
427
140k
428
140k
    // If this instruction is the only user of a virtual register,
429
140k
    // check if breaking the edge will enable sinking
430
140k
    // both this instruction and the defining instruction.
431
140k
    if (MRI->hasOneNonDBGUse(Reg)) {
432
36.5k
      // If the definition resides in same MBB,
433
36.5k
      // claim it's likely we can sink these together.
434
36.5k
      // If definition resides elsewhere, we aren't
435
36.5k
      // blocking it from being sunk so don't break the edge.
436
36.5k
      MachineInstr *DefMI = MRI->getVRegDef(Reg);
437
36.5k
      if (DefMI->getParent() == MI.getParent())
438
26.6k
        return true;
439
36.5k
    }
440
140k
  }
441
161k
442
161k
  
return false134k
;
443
161k
}
444
445
bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
446
                                               MachineBasicBlock *FromBB,
447
                                               MachineBasicBlock *ToBB,
448
356k
                                               bool BreakPHIEdge) {
449
356k
  if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
450
134k
    return false;
451
222k
452
222k
  // Avoid breaking back edge. From == To means backedge for single BB loop.
453
222k
  if (!SplitEdges || FromBB == ToBB)
454
0
    return false;
455
222k
456
222k
  // Check for backedges of more "complex" loops.
457
222k
  if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
458
222k
      
LI->isLoopHeader(ToBB)214k
)
459
47.5k
    return false;
460
174k
461
174k
  // It's not always legal to break critical edges and sink the computation
462
174k
  // to the edge.
463
174k
  //
464
174k
  // %bb.1:
465
174k
  // v1024
466
174k
  // Beq %bb.3
467
174k
  // <fallthrough>
468
174k
  // %bb.2:
469
174k
  // ... no uses of v1024
470
174k
  // <fallthrough>
471
174k
  // %bb.3:
472
174k
  // ...
473
174k
  //       = v1024
474
174k
  //
475
174k
  // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
476
174k
  //
477
174k
  // %bb.1:
478
174k
  // ...
479
174k
  // Bne %bb.2
480
174k
  // %bb.4:
481
174k
  // v1024 =
482
174k
  // B %bb.3
483
174k
  // %bb.2:
484
174k
  // ... no uses of v1024
485
174k
  // <fallthrough>
486
174k
  // %bb.3:
487
174k
  // ...
488
174k
  //       = v1024
489
174k
  //
490
174k
  // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
491
174k
  // flow. We need to ensure the new basic block where the computation is
492
174k
  // sunk to dominates all the uses.
493
174k
  // It's only legal to break critical edge and sink the computation to the
494
174k
  // new block if all the predecessors of "To", except for "From", are
495
174k
  // not dominated by "From". Given SSA property, this means these
496
174k
  // predecessors are dominated by "To".
497
174k
  //
498
174k
  // There is no need to do this check if all the uses are PHI nodes. PHI
499
174k
  // sources are only defined on the specific predecessor edges.
500
174k
  if (!BreakPHIEdge) {
501
79.8k
    for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
502
160k
           E = ToBB->pred_end(); PI != E; 
++PI81.0k
) {
503
160k
      if (*PI == FromBB)
504
76.5k
        continue;
505
84.2k
      if (!DT->dominates(ToBB, *PI))
506
79.7k
        return false;
507
84.2k
    }
508
79.8k
  }
509
174k
510
174k
  ToSplit.insert(std::make_pair(FromBB, ToBB));
511
94.7k
512
94.7k
  return true;
513
174k
}
514
515
/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
516
bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
517
                                          MachineBasicBlock *MBB,
518
                                          MachineBasicBlock *SuccToSinkTo,
519
4.82M
                                          AllSuccsCache &AllSuccessors) {
520
4.82M
  assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
521
4.82M
522
4.82M
  if (MBB == SuccToSinkTo)
523
311k
    return false;
524
4.51M
525
4.51M
  // It is profitable if SuccToSinkTo does not post dominate current block.
526
4.51M
  if (!PDT->dominates(SuccToSinkTo, MBB))
527
3.57M
    return true;
528
936k
529
936k
  // It is profitable to sink an instruction from a deeper loop to a shallower
530
936k
  // loop, even if the latter post-dominates the former (PR21115).
531
936k
  if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
532
101k
    return true;
533
834k
534
834k
  // Check if only use in post dominated block is PHI instruction.
535
834k
  bool NonPHIUse = false;
536
1.84M
  for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
537
1.84M
    MachineBasicBlock *UseBlock = UseInst.getParent();
538
1.84M
    if (UseBlock == SuccToSinkTo && 
!UseInst.isPHI()404k
)
539
318k
      NonPHIUse = true;
540
1.84M
  }
541
834k
  if (!NonPHIUse)
542
556k
    return true;
543
278k
544
278k
  // If SuccToSinkTo post dominates then also it may be profitable if MI
545
278k
  // can further profitably sinked into another block in next round.
546
278k
  bool BreakPHIEdge = false;
547
278k
  // FIXME - If finding successor is compile time expensive then cache results.
548
278k
  if (MachineBasicBlock *MBB2 =
549
0
          FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
550
0
    return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
551
278k
552
278k
  // If SuccToSinkTo is final destination and it is a post dominator of current
553
278k
  // block then it is not profitable to sink MI into SuccToSinkTo block.
554
278k
  return false;
555
278k
}
556
557
/// Get the sorted sequence of successors for this MachineBasicBlock, possibly
558
/// computing it if it was not already cached.
559
SmallVector<MachineBasicBlock *, 4> &
560
MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
561
13.0M
                                       AllSuccsCache &AllSuccessors) const {
562
13.0M
  // Do we have the sorted successors in cache ?
563
13.0M
  auto Succs = AllSuccessors.find(MBB);
564
13.0M
  if (Succs != AllSuccessors.end())
565
10.3M
    return Succs->second;
566
2.74M
567
2.74M
  SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
568
2.74M
                                               MBB->succ_end());
569
2.74M
570
2.74M
  // Handle cases where sinking can happen but where the sink point isn't a
571
2.74M
  // successor. For example:
572
2.74M
  //
573
2.74M
  //   x = computation
574
2.74M
  //   if () {} else {}
575
2.74M
  //   use x
576
2.74M
  //
577
2.74M
  const std::vector<MachineDomTreeNode *> &Children =
578
2.74M
    DT->getNode(MBB)->getChildren();
579
2.74M
  for (const auto &DTChild : Children)
580
4.29M
    // DomTree children of MBB that have MBB as immediate dominator are added.
581
4.29M
    if (DTChild->getIDom()->getBlock() == MI.getParent() &&
582
4.29M
        // Skip MBBs already added to the AllSuccs vector above.
583
4.29M
        
!MBB->isSuccessor(DTChild->getBlock())4.05M
)
584
341k
      AllSuccs.push_back(DTChild->getBlock());
585
2.74M
586
2.74M
  // Sort Successors according to their loop depth or block frequency info.
587
2.74M
  llvm::stable_sort(
588
3.19M
      AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
589
3.19M
        uint64_t LHSFreq = MBFI ? 
MBFI->getBlockFreq(L).getFrequency()3.19M
:
03
;
590
3.19M
        uint64_t RHSFreq = MBFI ? 
MBFI->getBlockFreq(R).getFrequency()3.19M
:
03
;
591
3.19M
        bool HasBlockFreq = LHSFreq != 0 && 
RHSFreq != 03.16M
;
592
3.19M
        return HasBlockFreq ? 
LHSFreq < RHSFreq3.03M
593
3.19M
                            : 
LI->getLoopDepth(L) < LI->getLoopDepth(R)151k
;
594
3.19M
      });
595
2.74M
596
2.74M
  auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
597
2.74M
598
2.74M
  return it.first->second;
599
2.74M
}
600
601
/// FindSuccToSinkTo - Find a successor to sink this instruction to.
602
MachineBasicBlock *
603
MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
604
                                 bool &BreakPHIEdge,
605
16.7M
                                 AllSuccsCache &AllSuccessors) {
606
16.7M
  assert (MBB && "Invalid MachineBasicBlock!");
607
16.7M
608
16.7M
  // Loop over all the operands of the specified instruction.  If there is
609
16.7M
  // anything we can't handle, bail out.
610
16.7M
611
16.7M
  // SuccToSinkTo - This is the successor to sink this instruction to, once we
612
16.7M
  // decide.
613
16.7M
  MachineBasicBlock *SuccToSinkTo = nullptr;
614
30.4M
  for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i13.6M
) {
615
27.2M
    const MachineOperand &MO = MI.getOperand(i);
616
27.2M
    if (!MO.isReg()) 
continue5.31M
; // Ignore non-register operands.
617
21.8M
618
21.8M
    unsigned Reg = MO.getReg();
619
21.8M
    if (Reg == 0) 
continue301k
;
620
21.5M
621
21.5M
    if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
622
5.45M
      if (MO.isUse()) {
623
666k
        // If the physreg has no defs anywhere, it's just an ambient register
624
666k
        // and we can freely move its uses. Alternatively, if it's allocatable,
625
666k
        // it could get allocated to something with a def during allocation.
626
666k
        if (!MRI->isConstantPhysReg(Reg))
627
595k
          return nullptr;
628
4.79M
      } else if (!MO.isDead()) {
629
4.07M
        // A def that isn't dead. We can't move it.
630
4.07M
        return nullptr;
631
4.07M
      }
632
16.1M
    } else {
633
16.1M
      // Virtual register uses are always safe to sink.
634
16.1M
      if (MO.isUse()) 
continue3.05M
;
635
13.0M
636
13.0M
      // If it's not safe to move defs of the register class, then abort.
637
13.0M
      if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
638
3.85k
        return nullptr;
639
13.0M
640
13.0M
      // Virtual register defs can only be sunk if all their uses are in blocks
641
13.0M
      // dominated by one of the successors.
642
13.0M
      if (SuccToSinkTo) {
643
622
        // If a previous operand picked a block to sink to, then this operand
644
622
        // must be sinkable to the same block.
645
622
        bool LocalUse = false;
646
622
        if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
647
622
                                     BreakPHIEdge, LocalUse))
648
551
          return nullptr;
649
71
650
71
        continue;
651
71
      }
652
13.0M
653
13.0M
      // Otherwise, we should look at all the successors and decide which one
654
13.0M
      // we should sink to. If we have reliable block frequency information
655
13.0M
      // (frequency != 0) available, give successors with smaller frequencies
656
13.0M
      // higher priority, otherwise prioritize smaller loop depths.
657
13.0M
      for (MachineBasicBlock *SuccBlock :
658
17.7M
           GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
659
17.7M
        bool LocalUse = false;
660
17.7M
        if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
661
17.7M
                                    BreakPHIEdge, LocalUse)) {
662
4.82M
          SuccToSinkTo = SuccBlock;
663
4.82M
          break;
664
4.82M
        }
665
12.9M
        if (LocalUse)
666
7.44M
          // Def is used locally, it's never safe to move this def.
667
7.44M
          return nullptr;
668
12.9M
      }
669
13.0M
670
13.0M
      // If we couldn't find a block to sink to, ignore this instruction.
671
13.0M
      
if (5.61M
!SuccToSinkTo5.61M
)
672
794k
        return nullptr;
673
4.82M
      if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
674
590k
        return nullptr;
675
4.82M
    }
676
21.5M
  }
677
16.7M
678
16.7M
  // It is not possible to sink an instruction into its own block.  This can
679
16.7M
  // happen with loops.
680
16.7M
  
if (3.25M
MBB == SuccToSinkTo3.25M
)
681
0
    return nullptr;
682
3.25M
683
3.25M
  // It's not safe to sink instructions to EH landing pad. Control flow into
684
3.25M
  // landing pad is implicitly defined.
685
3.25M
  if (SuccToSinkTo && 
SuccToSinkTo->isEHPad()3.25M
)
686
2.98k
    return nullptr;
687
3.25M
688
3.25M
  return SuccToSinkTo;
689
3.25M
}
690
691
/// Return true if MI is likely to be usable as a memory operation by the
692
/// implicit null check optimization.
693
///
694
/// This is a "best effort" heuristic, and should not be relied upon for
695
/// correctness.  This returning true does not guarantee that the implicit null
696
/// check optimization is legal over MI, and this returning false does not
697
/// guarantee MI cannot possibly be used to do a null check.
698
static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
699
                                             const TargetInstrInfo *TII,
700
16.4M
                                             const TargetRegisterInfo *TRI) {
701
16.4M
  using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
702
16.4M
703
16.4M
  auto *MBB = MI.getParent();
704
16.4M
  if (MBB->pred_size() != 1)
705
8.85M
    return false;
706
7.62M
707
7.62M
  auto *PredMBB = *MBB->pred_begin();
708
7.62M
  auto *PredBB = PredMBB->getBasicBlock();
709
7.62M
710
7.62M
  // Frontends that don't use implicit null checks have no reason to emit
711
7.62M
  // branches with make.implicit metadata, and this function should always
712
7.62M
  // return false for them.
713
7.62M
  if (!PredBB ||
714
7.62M
      
!PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit)7.62M
)
715
7.62M
    return false;
716
7
717
7
  const MachineOperand *BaseOp;
718
7
  int64_t Offset;
719
7
  if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
720
5
    return false;
721
2
722
2
  if (!BaseOp->isReg())
723
0
    return false;
724
2
725
2
  if (!(MI.mayLoad() && !MI.isPredicable()))
726
0
    return false;
727
2
728
2
  MachineBranchPredicate MBP;
729
2
  if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
730
0
    return false;
731
2
732
2
  return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
733
2
         (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
734
2
          
MBP.Predicate == MachineBranchPredicate::PRED_EQ1
) &&
735
2
         MBP.LHS.getReg() == BaseOp->getReg();
736
2
}
737
738
/// Sink an instruction and its associated debug instructions. If the debug
739
/// instructions to be sunk are already known, they can be provided in DbgVals.
740
static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
741
                        MachineBasicBlock::iterator InsertPos,
742
2.98M
                        SmallVectorImpl<MachineInstr *> *DbgVals = nullptr) {
743
2.98M
  // If debug values are provided use those, otherwise call collectDebugValues.
744
2.98M
  SmallVector<MachineInstr *, 2> DbgValuesToSink;
745
2.98M
  if (DbgVals)
746
93.5k
    DbgValuesToSink.insert(DbgValuesToSink.begin(),
747
93.5k
                           DbgVals->begin(), DbgVals->end());
748
2.89M
  else
749
2.89M
    MI.collectDebugValues(DbgValuesToSink);
750
2.98M
751
2.98M
  // If we cannot find a location to use (merge with), then we erase the debug
752
2.98M
  // location to prevent debug-info driven tools from potentially reporting
753
2.98M
  // wrong location information.
754
2.98M
  if (!SuccToSinkTo.empty() && 
InsertPos != SuccToSinkTo.end()2.97M
)
755
2.97M
    MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
756
2.97M
                                                 InsertPos->getDebugLoc()));
757
13.1k
  else
758
13.1k
    MI.setDebugLoc(DebugLoc());
759
2.98M
760
2.98M
  // Move the instruction.
761
2.98M
  MachineBasicBlock *ParentBlock = MI.getParent();
762
2.98M
  SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
763
2.98M
                      ++MachineBasicBlock::iterator(MI));
764
2.98M
765
2.98M
  // Move previously adjacent debug value instructions to the insert position.
766
2.98M
  for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
767
2.98M
                                                 DBE = DbgValuesToSink.end();
768
2.98M
       DBI != DBE; 
++DBI15
) {
769
15
    MachineInstr *DbgMI = *DBI;
770
15
    SuccToSinkTo.splice(InsertPos, ParentBlock, DbgMI,
771
15
                        ++MachineBasicBlock::iterator(DbgMI));
772
15
  }
773
2.98M
}
774
775
/// SinkInstruction - Determine whether it is safe to sink the specified machine
776
/// instruction out of its current block into a successor.
777
bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
778
27.9M
                                     AllSuccsCache &AllSuccessors) {
779
27.9M
  // Don't sink instructions that the target prefers not to sink.
780
27.9M
  if (!TII->shouldSink(MI))
781
196
    return false;
782
27.9M
783
27.9M
  // Check if it's safe to move the instruction.
784
27.9M
  if (!MI.isSafeToMove(AA, SawStore))
785
11.4M
    return false;
786
16.4M
787
16.4M
  // Convergent operations may not be made control-dependent on additional
788
16.4M
  // values.
789
16.4M
  if (MI.isConvergent())
790
731
    return false;
791
16.4M
792
16.4M
  // Don't break implicit null checks.  This is a performance heuristic, and not
793
16.4M
  // required for correctness.
794
16.4M
  if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
795
2
    return false;
796
16.4M
797
16.4M
  // FIXME: This should include support for sinking instructions within the
798
16.4M
  // block they are currently in to shorten the live ranges.  We often get
799
16.4M
  // instructions sunk into the top of a large block, but it would be better to
800
16.4M
  // also sink them down before their first use in the block.  This xform has to
801
16.4M
  // be careful not to *increase* register pressure though, e.g. sinking
802
16.4M
  // "x = y + z" down if it kills y and z would increase the live ranges of y
803
16.4M
  // and z and only shrink the live range of x.
804
16.4M
805
16.4M
  bool BreakPHIEdge = false;
806
16.4M
  MachineBasicBlock *ParentBlock = MI.getParent();
807
16.4M
  MachineBasicBlock *SuccToSinkTo =
808
16.4M
      FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
809
16.4M
810
16.4M
  // If there are no outputs, it must have side-effects.
811
16.4M
  if (!SuccToSinkTo)
812
13.2M
    return false;
813
3.25M
814
3.25M
  // If the instruction to move defines a dead physical register which is live
815
3.25M
  // when leaving the basic block, don't move it because it could turn into a
816
3.25M
  // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
817
11.8M
  
for (unsigned I = 0, E = MI.getNumOperands(); 3.25M
I != E;
++I8.61M
) {
818
8.61M
    const MachineOperand &MO = MI.getOperand(I);
819
8.61M
    if (!MO.isReg()) 
continue3.71M
;
820
4.90M
    unsigned Reg = MO.getReg();
821
4.90M
    if (Reg == 0 || 
!TargetRegisterInfo::isPhysicalRegister(Reg)4.85M
)
continue4.83M
;
822
62.1k
    if (SuccToSinkTo->isLiveIn(Reg))
823
318
      return false;
824
62.1k
  }
825
3.25M
826
3.25M
  
LLVM_DEBUG3.25M
(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
827
3.25M
828
3.25M
  // If the block has multiple predecessors, this is a critical edge.
829
3.25M
  // Decide if we can sink along it or need to break the edge.
830
3.25M
  if (SuccToSinkTo->pred_size() > 1) {
831
848k
    // We cannot sink a load across a critical edge - there may be stores in
832
848k
    // other code paths.
833
848k
    bool TryBreak = false;
834
848k
    bool store = true;
835
848k
    if (!MI.isSafeToMove(AA, store)) {
836
76.3k
      LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
837
76.3k
      TryBreak = true;
838
76.3k
    }
839
848k
840
848k
    // We don't want to sink across a critical edge if we don't dominate the
841
848k
    // successor. We could be introducing calculations to new code paths.
842
848k
    if (!TryBreak && 
!DT->dominates(ParentBlock, SuccToSinkTo)772k
) {
843
220k
      LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
844
220k
      TryBreak = true;
845
220k
    }
846
848k
847
848k
    // Don't sink instructions into a loop.
848
848k
    if (!TryBreak && 
LI->isLoopHeader(SuccToSinkTo)552k
) {
849
4.88k
      LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
850
4.88k
      TryBreak = true;
851
4.88k
    }
852
848k
853
848k
    // Otherwise we are OK with sinking along a critical edge.
854
848k
    if (!TryBreak)
855
848k
      LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
856
848k
    else {
857
301k
      // Mark this edge as to be split.
858
301k
      // If the edge can actually be split, the next iteration of the main loop
859
301k
      // will sink MI in the newly created block.
860
301k
      bool Status =
861
301k
        PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
862
301k
      if (!Status)
863
301k
        LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
864
301k
                             "break critical edge\n");
865
301k
      // The instruction will not be sunk this time.
866
301k
      return false;
867
301k
    }
868
2.94M
  }
869
2.94M
870
2.94M
  if (BreakPHIEdge) {
871
54.8k
    // BreakPHIEdge is true if all the uses are in the successor MBB being
872
54.8k
    // sunken into and they are all PHI nodes. In this case, machine-sink must
873
54.8k
    // break the critical edge first.
874
54.8k
    bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
875
54.8k
                                            SuccToSinkTo, BreakPHIEdge);
876
54.8k
    if (!Status)
877
54.8k
      LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
878
54.8k
                           "break critical edge\n");
879
54.8k
    // The instruction will not be sunk this time.
880
54.8k
    return false;
881
54.8k
  }
882
2.89M
883
2.89M
  // Determine where to insert into. Skip phi nodes.
884
2.89M
  MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
885
3.20M
  while (InsertPos != SuccToSinkTo->end() && 
InsertPos->isPHI()3.19M
)
886
308k
    ++InsertPos;
887
2.89M
888
2.89M
  performSink(MI, *SuccToSinkTo, InsertPos);
889
2.89M
890
2.89M
  // Conservatively, clear any kill flags, since it's possible that they are no
891
2.89M
  // longer correct.
892
2.89M
  // Note that we have to clear the kill flags for any register this instruction
893
2.89M
  // uses as we may sink over another instruction which currently kills the
894
2.89M
  // used registers.
895
7.66M
  for (MachineOperand &MO : MI.operands()) {
896
7.66M
    if (MO.isReg() && 
MO.isUse()4.18M
)
897
1.26M
      RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
898
7.66M
  }
899
2.89M
900
2.89M
  return true;
901
2.89M
}
902
903
//===----------------------------------------------------------------------===//
904
// This pass is not intended to be a replacement or a complete alternative
905
// for the pre-ra machine sink pass. It is only designed to sink COPY
906
// instructions which should be handled after RA.
907
//
908
// This pass sinks COPY instructions into a successor block, if the COPY is not
909
// used in the current block and the COPY is live-in to a single successor
910
// (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
911
// copy on paths where their results aren't needed.  This also exposes
912
// additional opportunites for dead copy elimination and shrink wrapping.
913
//
914
// These copies were either not handled by or are inserted after the MachineSink
915
// pass. As an example of the former case, the MachineSink pass cannot sink
916
// COPY instructions with allocatable source registers; for AArch64 these type
917
// of copy instructions are frequently used to move function parameters (PhyReg)
918
// into virtual registers in the entry block.
919
//
920
// For the machine IR below, this pass will sink %w19 in the entry into its
921
// successor (%bb.1) because %w19 is only live-in in %bb.1.
922
// %bb.0:
923
//   %wzr = SUBSWri %w1, 1
924
//   %w19 = COPY %w0
925
//   Bcc 11, %bb.2
926
// %bb.1:
927
//   Live Ins: %w19
928
//   BL @fun
929
//   %w0 = ADDWrr %w0, %w19
930
//   RET %w0
931
// %bb.2:
932
//   %w0 = COPY %wzr
933
//   RET %w0
934
// As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
935
// able to see %bb.0 as a candidate.
936
//===----------------------------------------------------------------------===//
937
namespace {
938
939
class PostRAMachineSinking : public MachineFunctionPass {
940
public:
941
  bool runOnMachineFunction(MachineFunction &MF) override;
942
943
  static char ID;
944
33.8k
  PostRAMachineSinking() : MachineFunctionPass(ID) {}
945
518k
  StringRef getPassName() const override { return "PostRA Machine Sink"; }
946
947
33.6k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
948
33.6k
    AU.setPreservesCFG();
949
33.6k
    MachineFunctionPass::getAnalysisUsage(AU);
950
33.6k
  }
951
952
33.6k
  MachineFunctionProperties getRequiredProperties() const override {
953
33.6k
    return MachineFunctionProperties().set(
954
33.6k
        MachineFunctionProperties::Property::NoVRegs);
955
33.6k
  }
956
957
private:
958
  /// Track which register units have been modified and used.
959
  LiveRegUnits ModifiedRegUnits, UsedRegUnits;
960
961
  /// Track DBG_VALUEs of (unmodified) register units.
962
  DenseMap<unsigned, TinyPtrVector<MachineInstr*>> SeenDbgInstrs;
963
964
  /// Sink Copy instructions unused in the same block close to their uses in
965
  /// successors.
966
  bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
967
                     const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
968
};
969
} // namespace
970
971
char PostRAMachineSinking::ID = 0;
972
char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
973
974
INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
975
                "PostRA Machine Sink", false, false)
976
977
static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
978
348k
                                  const TargetRegisterInfo *TRI) {
979
348k
  LiveRegUnits LiveInRegUnits(*TRI);
980
348k
  LiveInRegUnits.addLiveIns(MBB);
981
348k
  return !LiveInRegUnits.available(Reg);
982
348k
}
983
984
static MachineBasicBlock *
985
getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
986
                      const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
987
181k
                      unsigned Reg, const TargetRegisterInfo *TRI) {
988
181k
  // Try to find a single sinkable successor in which Reg is live-in.
989
181k
  MachineBasicBlock *BB = nullptr;
990
251k
  for (auto *SI : SinkableBBs) {
991
251k
    if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
992
192k
      // If BB is set here, Reg is live-in to at least two sinkable successors,
993
192k
      // so quit.
994
192k
      if (BB)
995
25.7k
        return nullptr;
996
166k
      BB = SI;
997
166k
    }
998
251k
  }
999
181k
  // Reg is not live-in to any sinkable successors.
1000
181k
  
if (155k
!BB155k
)
1001
15.2k
    return nullptr;
1002
140k
1003
140k
  // Check if any register aliased with Reg is live-in in other successors.
1004
265k
  
for (auto *SI : CurBB.successors())140k
{
1005
265k
    if (!SinkableBBs.count(SI) && 
aliasWithRegsInLiveIn(*SI, Reg, TRI)97.6k
)
1006
39.7k
      return nullptr;
1007
265k
  }
1008
140k
  
return BB100k
;
1009
140k
}
1010
1011
static MachineBasicBlock *
1012
getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1013
                      const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1014
                      ArrayRef<unsigned> DefedRegsInCopy,
1015
174k
                      const TargetRegisterInfo *TRI) {
1016
174k
  MachineBasicBlock *SingleBB = nullptr;
1017
181k
  for (auto DefReg : DefedRegsInCopy) {
1018
181k
    MachineBasicBlock *BB =
1019
181k
        getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1020
181k
    if (!BB || 
(100k
SingleBB100k
&&
SingleBB != BB7.34k
))
1021
80.8k
      return nullptr;
1022
100k
    SingleBB = BB;
1023
100k
  }
1024
174k
  
return SingleBB93.5k
;
1025
174k
}
1026
1027
static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1028
                           SmallVectorImpl<unsigned> &UsedOpsInCopy,
1029
                           LiveRegUnits &UsedRegUnits,
1030
93.5k
                           const TargetRegisterInfo *TRI) {
1031
93.5k
  for (auto U : UsedOpsInCopy) {
1032
93.5k
    MachineOperand &MO = MI->getOperand(U);
1033
93.5k
    unsigned SrcReg = MO.getReg();
1034
93.5k
    if (!UsedRegUnits.available(SrcReg)) {
1035
45.3k
      MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1036
163k
      for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1037
163k
        if (UI.killsRegister(SrcReg, TRI)) {
1038
134
          UI.clearRegisterKills(SrcReg, TRI);
1039
134
          MO.setIsKill(true);
1040
134
          break;
1041
134
        }
1042
163k
      }
1043
45.3k
    }
1044
93.5k
  }
1045
93.5k
}
1046
1047
static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1048
                         SmallVectorImpl<unsigned> &UsedOpsInCopy,
1049
93.5k
                         SmallVectorImpl<unsigned> &DefedRegsInCopy) {
1050
93.5k
  MachineFunction &MF = *SuccBB->getParent();
1051
93.5k
  const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1052
93.5k
  for (unsigned DefReg : DefedRegsInCopy)
1053
334k
    
for (MCSubRegIterator S(DefReg, TRI, true); 100k
S.isValid();
++S233k
)
1054
233k
      SuccBB->removeLiveIn(*S);
1055
93.5k
  for (auto U : UsedOpsInCopy) {
1056
93.5k
    unsigned Reg = MI->getOperand(U).getReg();
1057
93.5k
    if (!SuccBB->isLiveIn(Reg))
1058
92.9k
      SuccBB->addLiveIn(Reg);
1059
93.5k
  }
1060
93.5k
}
1061
1062
static bool hasRegisterDependency(MachineInstr *MI,
1063
                                  SmallVectorImpl<unsigned> &UsedOpsInCopy,
1064
                                  SmallVectorImpl<unsigned> &DefedRegsInCopy,
1065
                                  LiveRegUnits &ModifiedRegUnits,
1066
253k
                                  LiveRegUnits &UsedRegUnits) {
1067
253k
  bool HasRegDependency = false;
1068
631k
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; 
++i378k
) {
1069
456k
    MachineOperand &MO = MI->getOperand(i);
1070
456k
    if (!MO.isReg())
1071
175
      continue;
1072
456k
    unsigned Reg = MO.getReg();
1073
456k
    if (!Reg)
1074
86
      continue;
1075
456k
    if (MO.isDef()) {
1076
265k
      if (!ModifiedRegUnits.available(Reg) || 
!UsedRegUnits.available(Reg)231k
) {
1077
62.5k
        HasRegDependency = true;
1078
62.5k
        break;
1079
62.5k
      }
1080
203k
      DefedRegsInCopy.push_back(Reg);
1081
203k
1082
203k
      // FIXME: instead of isUse(), readsReg() would be a better fix here,
1083
203k
      // For example, we can ignore modifications in reg with undef. However,
1084
203k
      // it's not perfectly clear if skipping the internal read is safe in all
1085
203k
      // other targets.
1086
203k
    } else 
if (190k
MO.isUse()190k
) {
1087
190k
      if (!ModifiedRegUnits.available(Reg)) {
1088
15.9k
        HasRegDependency = true;
1089
15.9k
        break;
1090
15.9k
      }
1091
174k
      UsedOpsInCopy.push_back(i);
1092
174k
    }
1093
456k
  }
1094
253k
  return HasRegDependency;
1095
253k
}
1096
1097
bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1098
                                         MachineFunction &MF,
1099
                                         const TargetRegisterInfo *TRI,
1100
2.82M
                                         const TargetInstrInfo *TII) {
1101
2.82M
  SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
1102
2.82M
  // FIXME: For now, we sink only to a successor which has a single predecessor
1103
2.82M
  // so that we can directly sink COPY instructions to the successor without
1104
2.82M
  // adding any new block or branch instruction.
1105
2.82M
  for (MachineBasicBlock *SI : CurBB.successors())
1106
3.46M
    if (!SI->livein_empty() && 
SI->pred_size() == 13.20M
)
1107
1.47M
      SinkableBBs.insert(SI);
1108
2.82M
1109
2.82M
  if (SinkableBBs.empty())
1110
1.74M
    return false;
1111
1.07M
1112
1.07M
  bool Changed = false;
1113
1.07M
1114
1.07M
  // Track which registers have been modified and used between the end of the
1115
1.07M
  // block and the current instruction.
1116
1.07M
  ModifiedRegUnits.clear();
1117
1.07M
  UsedRegUnits.clear();
1118
1.07M
  SeenDbgInstrs.clear();
1119
1.07M
1120
6.08M
  for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
1121
5.25M
    MachineInstr *MI = &*I;
1122
5.25M
    ++I;
1123
5.25M
1124
5.25M
    // Track the operand index for use in Copy.
1125
5.25M
    SmallVector<unsigned, 2> UsedOpsInCopy;
1126
5.25M
    // Track the register number defed in Copy.
1127
5.25M
    SmallVector<unsigned, 2> DefedRegsInCopy;
1128
5.25M
1129
5.25M
    // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1130
5.25M
    // for DBG_VALUEs later, record them when they're encountered.
1131
5.25M
    if (MI->isDebugValue()) {
1132
119
      auto &MO = MI->getOperand(0);
1133
119
      if (MO.isReg() && 
TRI->isPhysicalRegister(MO.getReg())109
) {
1134
95
        // Bail if we can already tell the sink would be rejected, rather
1135
95
        // than needlessly accumulating lots of DBG_VALUEs.
1136
95
        if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1137
95
                                  ModifiedRegUnits, UsedRegUnits))
1138
8
          continue;
1139
87
1140
87
        // Record debug use of this register.
1141
87
        SeenDbgInstrs[MO.getReg()].push_back(MI);
1142
87
      }
1143
119
      
continue111
;
1144
5.25M
    }
1145
5.25M
1146
5.25M
    if (MI->isDebugInstr())
1147
0
      continue;
1148
5.25M
1149
5.25M
    // Do not move any instruction across function call.
1150
5.25M
    if (MI->isCall())
1151
250k
      return false;
1152
5.00M
1153
5.00M
    if (!MI->isCopy() || 
!MI->getOperand(0).isRenamable()254k
) {
1154
4.75M
      LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1155
4.75M
                                        TRI);
1156
4.75M
      continue;
1157
4.75M
    }
1158
252k
1159
252k
    // Don't sink the COPY if it would violate a register dependency.
1160
252k
    if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1161
252k
                              ModifiedRegUnits, UsedRegUnits)) {
1162
78.4k
      LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1163
78.4k
                                        TRI);
1164
78.4k
      continue;
1165
78.4k
    }
1166
174k
    assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1167
174k
           "Unexpect SrcReg or DefReg");
1168
174k
    MachineBasicBlock *SuccBB =
1169
174k
        getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
1170
174k
    // Don't sink if we cannot find a single sinkable successor in which Reg
1171
174k
    // is live-in.
1172
174k
    if (!SuccBB) {
1173
80.8k
      LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1174
80.8k
                                        TRI);
1175
80.8k
      continue;
1176
80.8k
    }
1177
93.5k
    assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1178
93.5k
           "Unexpected predecessor");
1179
93.5k
1180
93.5k
    // Collect DBG_VALUEs that must sink with this copy.
1181
93.5k
    SmallVector<MachineInstr *, 4> DbgValsToSink;
1182
194k
    for (auto &MO : MI->operands()) {
1183
194k
      if (!MO.isReg() || !MO.isDef())
1184
93.5k
        continue;
1185
100k
      unsigned reg = MO.getReg();
1186
100k
      for (auto *MI : SeenDbgInstrs.lookup(reg))
1187
2
        DbgValsToSink.push_back(MI);
1188
100k
    }
1189
93.5k
1190
93.5k
    // Clear the kill flag if SrcReg is killed between MI and the end of the
1191
93.5k
    // block.
1192
93.5k
    clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
1193
93.5k
    MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
1194
93.5k
    performSink(*MI, *SuccBB, InsertPos, &DbgValsToSink);
1195
93.5k
    updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
1196
93.5k
1197
93.5k
    Changed = true;
1198
93.5k
    ++NumPostRACopySink;
1199
93.5k
  }
1200
1.07M
  
return Changed826k
;
1201
1.07M
}
1202
1203
484k
bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
1204
484k
  if (skipFunction(MF.getFunction()))
1205
251
    return false;
1206
484k
1207
484k
  bool Changed = false;
1208
484k
  const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1209
484k
  const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1210
484k
1211
484k
  ModifiedRegUnits.init(*TRI);
1212
484k
  UsedRegUnits.init(*TRI);
1213
484k
  for (auto &BB : MF)
1214
2.82M
    Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1215
484k
1216
484k
  return Changed;
1217
484k
}