Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/VirtRegMap.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
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 file implements the VirtRegMap class.
10
//
11
// It also contains implementations of the Spiller interface, which, given a
12
// virtual register map and a machine function, eliminates all virtual
13
// references by replacing them with physical register references - adding spill
14
// code as necessary.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "llvm/CodeGen/VirtRegMap.h"
19
#include "LiveDebugVariables.h"
20
#include "llvm/ADT/SmallVector.h"
21
#include "llvm/ADT/Statistic.h"
22
#include "llvm/CodeGen/LiveInterval.h"
23
#include "llvm/CodeGen/LiveIntervals.h"
24
#include "llvm/CodeGen/LiveStacks.h"
25
#include "llvm/CodeGen/MachineBasicBlock.h"
26
#include "llvm/CodeGen/MachineFrameInfo.h"
27
#include "llvm/CodeGen/MachineFunction.h"
28
#include "llvm/CodeGen/MachineFunctionPass.h"
29
#include "llvm/CodeGen/MachineInstr.h"
30
#include "llvm/CodeGen/MachineOperand.h"
31
#include "llvm/CodeGen/MachineRegisterInfo.h"
32
#include "llvm/CodeGen/SlotIndexes.h"
33
#include "llvm/CodeGen/TargetInstrInfo.h"
34
#include "llvm/CodeGen/TargetOpcodes.h"
35
#include "llvm/CodeGen/TargetRegisterInfo.h"
36
#include "llvm/CodeGen/TargetSubtargetInfo.h"
37
#include "llvm/Config/llvm-config.h"
38
#include "llvm/MC/LaneBitmask.h"
39
#include "llvm/Pass.h"
40
#include "llvm/Support/Compiler.h"
41
#include "llvm/Support/Debug.h"
42
#include "llvm/Support/raw_ostream.h"
43
#include <cassert>
44
#include <iterator>
45
#include <utility>
46
47
using namespace llvm;
48
49
#define DEBUG_TYPE "regalloc"
50
51
STATISTIC(NumSpillSlots, "Number of spill slots allocated");
52
STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
53
54
//===----------------------------------------------------------------------===//
55
//  VirtRegMap implementation
56
//===----------------------------------------------------------------------===//
57
58
char VirtRegMap::ID = 0;
59
60
INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
61
62
509k
bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
63
509k
  MRI = &mf.getRegInfo();
64
509k
  TII = mf.getSubtarget().getInstrInfo();
65
509k
  TRI = mf.getSubtarget().getRegisterInfo();
66
509k
  MF = &mf;
67
509k
68
509k
  Virt2PhysMap.clear();
69
509k
  Virt2StackSlotMap.clear();
70
509k
  Virt2SplitMap.clear();
71
509k
72
509k
  grow();
73
509k
  return false;
74
509k
}
75
76
1.95M
void VirtRegMap::grow() {
77
1.95M
  unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
78
1.95M
  Virt2PhysMap.resize(NumRegs);
79
1.95M
  Virt2StackSlotMap.resize(NumRegs);
80
1.95M
  Virt2SplitMap.resize(NumRegs);
81
1.95M
}
82
83
8.39M
void VirtRegMap::assignVirt2Phys(unsigned virtReg, MCPhysReg physReg) {
84
8.39M
  assert(TargetRegisterInfo::isVirtualRegister(virtReg) &&
85
8.39M
         TargetRegisterInfo::isPhysicalRegister(physReg));
86
8.39M
  assert(Virt2PhysMap[virtReg] == NO_PHYS_REG &&
87
8.39M
         "attempt to assign physical register to already mapped "
88
8.39M
         "virtual register");
89
8.39M
  assert(!getRegInfo().isReserved(physReg) &&
90
8.39M
         "Attempt to map virtReg to a reserved physReg");
91
8.39M
  Virt2PhysMap[virtReg] = physReg;
92
8.39M
}
93
94
121k
unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
95
121k
  unsigned Size = TRI->getSpillSize(*RC);
96
121k
  unsigned Align = TRI->getSpillAlignment(*RC);
97
121k
  int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Align);
98
121k
  ++NumSpillSlots;
99
121k
  return SS;
100
121k
}
101
102
11.9M
bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
103
11.9M
  unsigned Hint = MRI->getSimpleHint(VirtReg);
104
11.9M
  if (!Hint)
105
7.13M
    return false;
106
4.81M
  if (TargetRegisterInfo::isVirtualRegister(Hint))
107
1.12M
    Hint = getPhys(Hint);
108
4.81M
  return getPhys(VirtReg) == Hint;
109
4.81M
}
110
111
8.81M
bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
112
8.81M
  std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
113
8.81M
  if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
114
3.18M
    return true;
115
5.62M
  if (TargetRegisterInfo::isVirtualRegister(Hint.second))
116
679k
    return hasPhys(Hint.second);
117
4.94M
  return false;
118
4.94M
}
119
120
121k
int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
121
121k
  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
122
121k
  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
123
121k
         "attempt to assign stack slot to already spilled register");
124
121k
  const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
125
121k
  return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
126
121k
}
127
128
82.1k
void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
129
82.1k
  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
130
82.1k
  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
131
82.1k
         "attempt to assign stack slot to already spilled register");
132
82.1k
  assert((SS >= 0 ||
133
82.1k
          (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
134
82.1k
         "illegal fixed frame index");
135
82.1k
  Virt2StackSlotMap[virtReg] = SS;
136
82.1k
}
137
138
0
void VirtRegMap::print(raw_ostream &OS, const Module*) const {
139
0
  OS << "********** REGISTER MAP **********\n";
140
0
  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
141
0
    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
142
0
    if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
143
0
      OS << '[' << printReg(Reg, TRI) << " -> "
144
0
         << printReg(Virt2PhysMap[Reg], TRI) << "] "
145
0
         << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
146
0
    }
147
0
  }
148
0
149
0
  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
150
0
    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
151
0
    if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
152
0
      OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
153
0
         << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
154
0
    }
155
0
  }
156
0
  OS << '\n';
157
0
}
158
159
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160
LLVM_DUMP_METHOD void VirtRegMap::dump() const {
161
  print(dbgs());
162
}
163
#endif
164
165
//===----------------------------------------------------------------------===//
166
//                              VirtRegRewriter
167
//===----------------------------------------------------------------------===//
168
//
169
// The VirtRegRewriter is the last of the register allocator passes.
170
// It rewrites virtual registers to physical registers as specified in the
171
// VirtRegMap analysis. It also updates live-in information on basic blocks
172
// according to LiveIntervals.
173
//
174
namespace {
175
176
class VirtRegRewriter : public MachineFunctionPass {
177
  MachineFunction *MF;
178
  const TargetRegisterInfo *TRI;
179
  const TargetInstrInfo *TII;
180
  MachineRegisterInfo *MRI;
181
  SlotIndexes *Indexes;
182
  LiveIntervals *LIS;
183
  VirtRegMap *VRM;
184
185
  void rewrite();
186
  void addMBBLiveIns();
187
  bool readsUndefSubreg(const MachineOperand &MO) const;
188
  void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
189
  void handleIdentityCopy(MachineInstr &MI) const;
190
  void expandCopyBundle(MachineInstr &MI) const;
191
  bool subRegLiveThrough(const MachineInstr &MI, unsigned SuperPhysReg) const;
192
193
public:
194
  static char ID;
195
196
33.8k
  VirtRegRewriter() : MachineFunctionPass(ID) {}
197
198
  void getAnalysisUsage(AnalysisUsage &AU) const override;
199
200
  bool runOnMachineFunction(MachineFunction&) override;
201
202
33.6k
  MachineFunctionProperties getSetProperties() const override {
203
33.6k
    return MachineFunctionProperties().set(
204
33.6k
        MachineFunctionProperties::Property::NoVRegs);
205
33.6k
  }
206
};
207
208
} // end anonymous namespace
209
210
char VirtRegRewriter::ID = 0;
211
212
char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
213
214
42.3k
INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
215
42.3k
                      "Virtual Register Rewriter", false, false)
216
42.3k
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
217
42.3k
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
218
42.3k
INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
219
42.3k
INITIALIZE_PASS_DEPENDENCY(LiveStacks)
220
42.3k
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
221
42.3k
INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
222
                    "Virtual Register Rewriter", false, false)
223
224
33.6k
void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
225
33.6k
  AU.setPreservesCFG();
226
33.6k
  AU.addRequired<LiveIntervals>();
227
33.6k
  AU.addRequired<SlotIndexes>();
228
33.6k
  AU.addPreserved<SlotIndexes>();
229
33.6k
  AU.addRequired<LiveDebugVariables>();
230
33.6k
  AU.addRequired<LiveStacks>();
231
33.6k
  AU.addPreserved<LiveStacks>();
232
33.6k
  AU.addRequired<VirtRegMap>();
233
33.6k
  MachineFunctionPass::getAnalysisUsage(AU);
234
33.6k
}
235
236
484k
bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
237
484k
  MF = &fn;
238
484k
  TRI = MF->getSubtarget().getRegisterInfo();
239
484k
  TII = MF->getSubtarget().getInstrInfo();
240
484k
  MRI = &MF->getRegInfo();
241
484k
  Indexes = &getAnalysis<SlotIndexes>();
242
484k
  LIS = &getAnalysis<LiveIntervals>();
243
484k
  VRM = &getAnalysis<VirtRegMap>();
244
484k
  LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
245
484k
                    << "********** Function: " << MF->getName() << '\n');
246
484k
  LLVM_DEBUG(VRM->dump());
247
484k
248
484k
  // Add kill flags while we still have virtual registers.
249
484k
  LIS->addKillFlags(VRM);
250
484k
251
484k
  // Live-in lists on basic blocks are required for physregs.
252
484k
  addMBBLiveIns();
253
484k
254
484k
  // Rewrite virtual registers.
255
484k
  rewrite();
256
484k
257
484k
  // Write out new DBG_VALUE instructions.
258
484k
  getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
259
484k
260
484k
  // All machine operands and other references to virtual registers have been
261
484k
  // replaced. Remove the virtual registers and release all the transient data.
262
484k
  VRM->clearAllVirt();
263
484k
  MRI->clearVirtRegs();
264
484k
  return true;
265
484k
}
266
267
void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
268
1.57k
                                             unsigned PhysReg) const {
269
1.57k
  assert(!LI.empty());
270
1.57k
  assert(LI.hasSubRanges());
271
1.57k
272
1.57k
  using SubRangeIteratorPair =
273
1.57k
      std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
274
1.57k
275
1.57k
  SmallVector<SubRangeIteratorPair, 4> SubRanges;
276
1.57k
  SlotIndex First;
277
1.57k
  SlotIndex Last;
278
4.49k
  for (const LiveInterval::SubRange &SR : LI.subranges()) {
279
4.49k
    SubRanges.push_back(std::make_pair(&SR, SR.begin()));
280
4.49k
    if (!First.isValid() || 
SR.segments.front().start < First2.92k
)
281
2.18k
      First = SR.segments.front().start;
282
4.49k
    if (!Last.isValid() || 
SR.segments.back().end > Last2.92k
)
283
1.86k
      Last = SR.segments.back().end;
284
4.49k
  }
285
1.57k
286
1.57k
  // Check all mbb start positions between First and Last while
287
1.57k
  // simulatenously advancing an iterator for each subrange.
288
1.57k
  for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
289
5.96k
       MBBI != Indexes->MBBIndexEnd() && 
MBBI->first <= Last4.82k
;
++MBBI4.39k
) {
290
4.39k
    SlotIndex MBBBegin = MBBI->first;
291
4.39k
    // Advance all subrange iterators so that their end position is just
292
4.39k
    // behind MBBBegin (or the iterator is at the end).
293
4.39k
    LaneBitmask LaneMask;
294
12.9k
    for (auto &RangeIterPair : SubRanges) {
295
12.9k
      const LiveInterval::SubRange *SR = RangeIterPair.first;
296
12.9k
      LiveInterval::const_iterator &SRI = RangeIterPair.second;
297
16.9k
      while (SRI != SR->end() && 
SRI->end <= MBBBegin15.0k
)
298
4.05k
        ++SRI;
299
12.9k
      if (SRI == SR->end())
300
1.91k
        continue;
301
11.0k
      if (SRI->start <= MBBBegin)
302
8.00k
        LaneMask |= SR->LaneMask;
303
11.0k
    }
304
4.39k
    if (LaneMask.none())
305
583
      continue;
306
3.81k
    MachineBasicBlock *MBB = MBBI->second;
307
3.81k
    MBB->addLiveIn(PhysReg, LaneMask);
308
3.81k
  }
309
1.57k
}
310
311
// Compute MBB live-in lists from virtual register live ranges and their
312
// assignments.
313
484k
void VirtRegRewriter::addMBBLiveIns() {
314
19.1M
  for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; 
++Idx18.6M
) {
315
18.6M
    unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
316
18.6M
    if (MRI->reg_nodbg_empty(VirtReg))
317
10.8M
      continue;
318
7.82M
    LiveInterval &LI = LIS->getInterval(VirtReg);
319
7.82M
    if (LI.empty() || 
LIS->intervalIsInOneMBB(LI)7.81M
)
320
6.10M
      continue;
321
1.71M
    // This is a virtual register that is live across basic blocks. Its
322
1.71M
    // assigned PhysReg must be marked as live-in to those blocks.
323
1.71M
    unsigned PhysReg = VRM->getPhys(VirtReg);
324
1.71M
    assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
325
1.71M
326
1.71M
    if (LI.hasSubRanges()) {
327
1.57k
      addLiveInsForSubRanges(LI, PhysReg);
328
1.71M
    } else {
329
1.71M
      // Go over MBB begin positions and see if we have segments covering them.
330
1.71M
      // The following works because segments and the MBBIndex list are both
331
1.71M
      // sorted by slot indexes.
332
1.71M
      SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
333
5.42M
      for (const auto &Seg : LI) {
334
5.42M
        I = Indexes->advanceMBBIndex(I, Seg.start);
335
18.5M
        for (; I != Indexes->MBBIndexEnd() && 
I->first < Seg.end18.2M
;
++I13.0M
) {
336
13.0M
          MachineBasicBlock *MBB = I->second;
337
13.0M
          MBB->addLiveIn(PhysReg);
338
13.0M
        }
339
5.42M
      }
340
1.71M
    }
341
1.71M
  }
342
484k
343
484k
  // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
344
484k
  // each MBB's LiveIns set before calling addLiveIn on them.
345
484k
  for (MachineBasicBlock &MBB : *MF)
346
2.82M
    MBB.sortUniqueLiveIns();
347
484k
}
348
349
/// Returns true if the given machine operand \p MO only reads undefined lanes.
350
/// The function only works for use operands with a subregister set.
351
117k
bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
352
117k
  // Shortcut if the operand is already marked undef.
353
117k
  if (MO.isUndef())
354
81
    return true;
355
117k
356
117k
  unsigned Reg = MO.getReg();
357
117k
  const LiveInterval &LI = LIS->getInterval(Reg);
358
117k
  const MachineInstr &MI = *MO.getParent();
359
117k
  SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
360
117k
  // This code is only meant to handle reading undefined subregisters which
361
117k
  // we couldn't properly detect before.
362
117k
  assert(LI.liveAt(BaseIndex) &&
363
117k
         "Reads of completely dead register should be marked undef already");
364
117k
  unsigned SubRegIdx = MO.getSubReg();
365
117k
  assert(SubRegIdx != 0 && LI.hasSubRanges());
366
117k
  LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
367
117k
  // See if any of the relevant subregister liveranges is defined at this point.
368
301k
  for (const LiveInterval::SubRange &SR : LI.subranges()) {
369
301k
    if ((SR.LaneMask & UseMask).any() && 
SR.liveAt(BaseIndex)117k
)
370
117k
      return false;
371
301k
  }
372
117k
  
return true0
;
373
117k
}
374
375
22.4M
void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) const {
376
22.4M
  if (!MI.isIdentityCopy())
377
19.7M
    return;
378
2.69M
  LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
379
2.69M
  ++NumIdCopies;
380
2.69M
381
2.69M
  // Copies like:
382
2.69M
  //    %r0 = COPY undef %r0
383
2.69M
  //    %al = COPY %al, implicit-def %eax
384
2.69M
  // give us additional liveness information: The target (super-)register
385
2.69M
  // must not be valid before this point. Replace the COPY with a KILL
386
2.69M
  // instruction to maintain this information.
387
2.69M
  if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
388
41.9k
    MI.setDesc(TII->get(TargetOpcode::KILL));
389
41.9k
    LLVM_DEBUG(dbgs() << "  replace by: " << MI);
390
41.9k
    return;
391
41.9k
  }
392
2.65M
393
2.65M
  if (Indexes)
394
2.65M
    Indexes->removeSingleMachineInstrFromMaps(MI);
395
2.65M
  MI.eraseFromBundle();
396
2.65M
  LLVM_DEBUG(dbgs() << "  deleted.\n");
397
2.65M
}
398
399
/// The liverange splitting logic sometimes produces bundles of copies when
400
/// subregisters are involved. Expand these into a sequence of copy instructions
401
/// after processing the last in the bundle. Does not update LiveIntervals
402
/// which we shouldn't need for this instruction anymore.
403
22.4M
void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
404
22.4M
  if (!MI.isCopy())
405
17.2M
    return;
406
5.23M
407
5.23M
  if (MI.isBundledWithPred() && 
!MI.isBundledWithSucc()7
) {
408
6
    SmallVector<MachineInstr *, 2> MIs({&MI});
409
6
410
6
    // Only do this when the complete bundle is made out of COPYs.
411
6
    MachineBasicBlock &MBB = *MI.getParent();
412
6
    for (MachineBasicBlock::reverse_instr_iterator I =
413
6
         std::next(MI.getReverseIterator()), E = MBB.instr_rend();
414
13
         I != E && I->isBundledWithSucc(); 
++I7
) {
415
7
      if (!I->isCopy())
416
0
        return;
417
7
      MIs.push_back(&*I);
418
7
    }
419
6
    MachineInstr *FirstMI = MIs.back();
420
6
421
6
    auto anyRegsAlias = [](const MachineInstr *Dst,
422
6
                           ArrayRef<MachineInstr *> Srcs,
423
13
                           const TargetRegisterInfo *TRI) {
424
13
      for (const MachineInstr *Src : Srcs)
425
21
        if (Src != Dst)
426
11
          if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
427
11
                               Src->getOperand(1).getReg()))
428
4
            return true;
429
13
      
return false9
;
430
13
    };
431
6
432
6
    // If any of the destination registers in the bundle of copies alias any of
433
6
    // the source registers, try to schedule the instructions to avoid any
434
6
    // clobbering.
435
11
    for (int E = MIs.size(), PrevE = E; E > 1; 
PrevE = E5
) {
436
19
      for (int I = E; I--; )
437
13
        if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) {
438
9
          if (I + 1 != E)
439
3
            std::swap(MIs[I], MIs[E - 1]);
440
9
          --E;
441
9
        }
442
6
      if (PrevE == E) {
443
1
        MF->getFunction().getContext().emitError(
444
1
            "register rewriting failed: cycle in copy bundle");
445
1
        break;
446
1
      }
447
6
    }
448
6
449
6
    MachineInstr *BundleStart = FirstMI;
450
13
    for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
451
13
      // If instruction is in the middle of the bundle, move it before the
452
13
      // bundle starts, otherwise, just unbundle it. When we get to the last
453
13
      // instruction, the bundle will have been completely undone.
454
13
      if (BundledMI != BundleStart) {
455
3
        BundledMI->removeFromBundle();
456
3
        MBB.insert(FirstMI, BundledMI);
457
10
      } else if (BundledMI->isBundledWithSucc()) {
458
4
        BundledMI->unbundleFromSucc();
459
4
        BundleStart = &*std::next(BundledMI->getIterator());
460
4
      }
461
13
462
13
      if (Indexes && BundledMI != FirstMI)
463
7
        Indexes->insertMachineInstrInMaps(*BundledMI);
464
13
    }
465
6
  }
466
5.23M
}
467
468
/// Check whether (part of) \p SuperPhysReg is live through \p MI.
469
/// \pre \p MI defines a subregister of a virtual register that
470
/// has been assigned to \p SuperPhysReg.
471
bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
472
390k
                                        unsigned SuperPhysReg) const {
473
390k
  SlotIndex MIIndex = LIS->getInstructionIndex(MI);
474
390k
  SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
475
390k
  SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
476
862k
  for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); 
++Unit472k
) {
477
472k
    const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
478
472k
    // If the regunit is live both before and after MI,
479
472k
    // we assume it is live through.
480
472k
    // Generally speaking, this is not true, because something like
481
472k
    // "RU = op RU" would match that description.
482
472k
    // However, we know that we are trying to assess whether
483
472k
    // a def of a virtual reg, vreg, is live at the same time of RU.
484
472k
    // If we are in the "RU = op RU" situation, that means that vreg
485
472k
    // is defined at the same time as RU (i.e., "vreg, RU = op RU").
486
472k
    // Thus, vreg and RU interferes and vreg cannot be assigned to
487
472k
    // SuperPhysReg. Therefore, this situation cannot happen.
488
472k
    if (UnitRange.liveAt(AfterMIDefs) && 
UnitRange.liveAt(BeforeMIUses)578
)
489
578
      return true;
490
472k
  }
491
390k
  
return false390k
;
492
390k
}
493
494
484k
void VirtRegRewriter::rewrite() {
495
484k
  bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
496
484k
  SmallVector<unsigned, 8> SuperDeads;
497
484k
  SmallVector<unsigned, 8> SuperDefs;
498
484k
  SmallVector<unsigned, 8> SuperKills;
499
484k
500
484k
  for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
501
3.30M
       MBBI != MBBE; 
++MBBI2.82M
) {
502
2.82M
    LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
503
2.82M
    for (MachineBasicBlock::instr_iterator
504
25.2M
           MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
505
22.4M
      MachineInstr *MI = &*MII;
506
22.4M
      ++MII;
507
22.4M
508
22.4M
      for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
509
96.6M
           MOE = MI->operands_end(); MOI != MOE; 
++MOI74.1M
) {
510
74.1M
        MachineOperand &MO = *MOI;
511
74.1M
512
74.1M
        // Make sure MRI knows about registers clobbered by regmasks.
513
74.1M
        if (MO.isRegMask())
514
1.50M
          MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
515
74.1M
516
74.1M
        if (!MO.isReg() || 
!TargetRegisterInfo::isVirtualRegister(MO.getReg())49.4M
)
517
50.8M
          continue;
518
23.2M
        unsigned VirtReg = MO.getReg();
519
23.2M
        unsigned PhysReg = VRM->getPhys(VirtReg);
520
23.2M
        assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
521
23.2M
               "Instruction uses unmapped VirtReg");
522
23.2M
        assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
523
23.2M
524
23.2M
        // Preserve semantics of sub-register operands.
525
23.2M
        unsigned SubReg = MO.getSubReg();
526
23.2M
        if (SubReg != 0) {
527
1.18M
          if (NoSubRegLiveness || 
!MRI->shouldTrackSubRegLiveness(VirtReg)260k
) {
528
922k
            // A virtual register kill refers to the whole register, so we may
529
922k
            // have to add implicit killed operands for the super-register.  A
530
922k
            // partial redef always kills and redefines the super-register.
531
922k
            if ((MO.readsReg() && 
(531k
MO.isDef()531k
||
MO.isKill()491k
)) ||
532
922k
                
(649k
MO.isDef()649k
&&
subRegLiveThrough(*MI, PhysReg)390k
))
533
272k
              SuperKills.push_back(PhysReg);
534
922k
535
922k
            if (MO.isDef()) {
536
430k
              // Also add implicit defs for the super-register.
537
430k
              if (MO.isDead())
538
294
                SuperDeads.push_back(PhysReg);
539
430k
              else
540
430k
                SuperDefs.push_back(PhysReg);
541
430k
            }
542
922k
          } else {
543
260k
            if (MO.isUse()) {
544
117k
              if (readsUndefSubreg(MO))
545
81
                // We need to add an <undef> flag if the subregister is
546
81
                // completely undefined (and we are not adding super-register
547
81
                // defs).
548
81
                MO.setIsUndef(true);
549
143k
            } else if (!MO.isDead()) {
550
143k
              assert(MO.isDef());
551
143k
            }
552
260k
          }
553
1.18M
554
1.18M
          // The def undef and def internal flags only make sense for
555
1.18M
          // sub-register defs, and we are substituting a full physreg.  An
556
1.18M
          // implicit killed operand from the SuperKills list will represent the
557
1.18M
          // partial read of the super-register.
558
1.18M
          if (MO.isDef()) {
559
574k
            MO.setIsUndef(false);
560
574k
            MO.setIsInternalRead(false);
561
574k
          }
562
1.18M
563
1.18M
          // PhysReg operands cannot have subregister indexes.
564
1.18M
          PhysReg = TRI->getSubReg(PhysReg, SubReg);
565
1.18M
          assert(PhysReg && "Invalid SubReg for physical register");
566
1.18M
          MO.setSubReg(0);
567
1.18M
        }
568
23.2M
        // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
569
23.2M
        // we need the inlining here.
570
23.2M
        MO.setReg(PhysReg);
571
23.2M
        MO.setIsRenamable(true);
572
23.2M
      }
573
22.4M
574
22.4M
      // Add any missing super-register kills after rewriting the whole
575
22.4M
      // instruction.
576
22.7M
      while (!SuperKills.empty())
577
272k
        MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
578
22.4M
579
22.4M
      while (!SuperDeads.empty())
580
294
        MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
581
22.4M
582
22.8M
      while (!SuperDefs.empty())
583
430k
        MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
584
22.4M
585
22.4M
      LLVM_DEBUG(dbgs() << "> " << *MI);
586
22.4M
587
22.4M
      expandCopyBundle(*MI);
588
22.4M
589
22.4M
      // We can remove identity copies right now.
590
22.4M
      handleIdentityCopy(*MI);
591
22.4M
    }
592
2.82M
  }
593
484k
}