1
//===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This file implements the machine instruction level pre-register allocation
11
// live interval splitting pass. It finds live interval barriers, i.e.
12
// instructions which will kill all physical registers in certain register
13
// classes, and split all live intervals which cross the barrier.
15
//===----------------------------------------------------------------------===//
17
#define DEBUG_TYPE "pre-alloc-split"
18
#include "VirtRegMap.h"
19
#include "llvm/CodeGen/CalcSpillWeights.h"
20
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
21
#include "llvm/CodeGen/LiveStackAnalysis.h"
22
#include "llvm/CodeGen/MachineDominators.h"
23
#include "llvm/CodeGen/MachineFrameInfo.h"
24
#include "llvm/CodeGen/MachineFunctionPass.h"
25
#include "llvm/CodeGen/MachineLoopInfo.h"
26
#include "llvm/CodeGen/MachineRegisterInfo.h"
27
#include "llvm/CodeGen/Passes.h"
28
#include "llvm/CodeGen/RegisterCoalescer.h"
29
#include "llvm/Target/TargetInstrInfo.h"
30
#include "llvm/Target/TargetMachine.h"
31
#include "llvm/Target/TargetOptions.h"
32
#include "llvm/Target/TargetRegisterInfo.h"
33
#include "llvm/Support/CommandLine.h"
34
#include "llvm/Support/Debug.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/ADT/DenseMap.h"
37
#include "llvm/ADT/DepthFirstIterator.h"
38
#include "llvm/ADT/SmallPtrSet.h"
39
#include "llvm/ADT/Statistic.h"
42
static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
43
static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1),
45
static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1),
48
STATISTIC(NumSplits, "Number of intervals split");
49
STATISTIC(NumRemats, "Number of intervals split by rematerialization");
50
STATISTIC(NumFolds, "Number of intervals split with spill folding");
51
STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
52
STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
53
STATISTIC(NumDeadSpills, "Number of dead spills removed");
56
class PreAllocSplitting : public MachineFunctionPass {
57
MachineFunction *CurrMF;
58
const TargetMachine *TM;
59
const TargetInstrInfo *TII;
60
const TargetRegisterInfo* TRI;
61
MachineFrameInfo *MFI;
62
MachineRegisterInfo *MRI;
68
// Barrier - Current barrier being processed.
69
MachineInstr *Barrier;
71
// BarrierMBB - Basic block where the barrier resides in.
72
MachineBasicBlock *BarrierMBB;
74
// Barrier - Current barrier index.
77
// CurrLI - Current live interval being split.
80
// CurrSLI - Current stack slot live interval.
81
LiveInterval *CurrSLI;
83
// CurrSValNo - Current val# for the stack slot live interval.
86
// IntervalSSMap - A map from live interval to spill slots.
87
DenseMap<unsigned, int> IntervalSSMap;
89
// Def2SpillMap - A map from a def instruction index to spill index.
90
DenseMap<SlotIndex, SlotIndex> Def2SpillMap;
95
: MachineFunctionPass(ID) {}
97
virtual bool runOnMachineFunction(MachineFunction &MF);
99
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100
AU.setPreservesCFG();
101
AU.addRequired<SlotIndexes>();
102
AU.addPreserved<SlotIndexes>();
103
AU.addRequired<LiveIntervals>();
104
AU.addPreserved<LiveIntervals>();
105
AU.addRequired<LiveStacks>();
106
AU.addPreserved<LiveStacks>();
107
AU.addPreserved<RegisterCoalescer>();
108
AU.addPreserved<CalculateSpillWeights>();
110
AU.addPreservedID(StrongPHIEliminationID);
112
AU.addPreservedID(PHIEliminationID);
113
AU.addRequired<MachineDominatorTree>();
114
AU.addRequired<MachineLoopInfo>();
115
AU.addRequired<VirtRegMap>();
116
AU.addPreserved<MachineDominatorTree>();
117
AU.addPreserved<MachineLoopInfo>();
118
AU.addPreserved<VirtRegMap>();
119
MachineFunctionPass::getAnalysisUsage(AU);
122
virtual void releaseMemory() {
123
IntervalSSMap.clear();
124
Def2SpillMap.clear();
127
virtual const char *getPassName() const {
128
return "Pre-Register Allocaton Live Interval Splitting";
131
/// print - Implement the dump method.
132
virtual void print(raw_ostream &O, const Module* M = 0) const {
139
MachineBasicBlock::iterator
140
findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
141
SmallPtrSet<MachineInstr*, 4>&);
143
MachineBasicBlock::iterator
144
findRestorePoint(MachineBasicBlock*, MachineInstr*, SlotIndex,
145
SmallPtrSet<MachineInstr*, 4>&);
147
int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
149
bool IsAvailableInStack(MachineBasicBlock*, unsigned,
150
SlotIndex, SlotIndex,
151
SlotIndex&, int&) const;
153
void UpdateSpillSlotInterval(VNInfo*, SlotIndex, SlotIndex);
155
bool SplitRegLiveInterval(LiveInterval*);
157
bool SplitRegLiveIntervals(const TargetRegisterClass **,
158
SmallPtrSet<LiveInterval*, 8>&);
160
bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
161
MachineBasicBlock* BarrierMBB);
162
bool Rematerialize(unsigned vreg, VNInfo* ValNo,
164
MachineBasicBlock::iterator RestorePt,
165
SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
166
MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
168
MachineInstr* Barrier,
169
MachineBasicBlock* MBB,
171
SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
172
MachineInstr* FoldRestore(unsigned vreg,
173
const TargetRegisterClass* RC,
174
MachineInstr* Barrier,
175
MachineBasicBlock* MBB,
177
SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
178
void RenumberValno(VNInfo* VN);
179
void ReconstructLiveInterval(LiveInterval* LI);
180
bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
181
unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
182
unsigned Reg, int FrameIndex, bool& TwoAddr);
183
VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
184
MachineBasicBlock* MBB, LiveInterval* LI,
185
SmallPtrSet<MachineInstr*, 4>& Visited,
186
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
187
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
188
DenseMap<MachineInstr*, VNInfo*>& NewVNs,
189
DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
190
DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
191
bool IsTopLevel, bool IsIntraBlock);
192
VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
193
MachineBasicBlock* MBB, LiveInterval* LI,
194
SmallPtrSet<MachineInstr*, 4>& Visited,
195
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
196
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
197
DenseMap<MachineInstr*, VNInfo*>& NewVNs,
198
DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
199
DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
200
bool IsTopLevel, bool IsIntraBlock);
202
} // end anonymous namespace
204
char PreAllocSplitting::ID = 0;
206
INITIALIZE_PASS(PreAllocSplitting, "pre-alloc-splitting",
207
"Pre-Register Allocation Live Interval Splitting",
210
char &llvm::PreAllocSplittingID = PreAllocSplitting::ID;
212
/// findSpillPoint - Find a gap as far away from the given MI that's suitable
213
/// for spilling the current live interval. The index must be before any
214
/// defs and uses of the live interval register in the mbb. Return begin() if
216
MachineBasicBlock::iterator
217
PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
219
SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
220
MachineBasicBlock::iterator Pt = MBB->begin();
222
MachineBasicBlock::iterator MII = MI;
223
MachineBasicBlock::iterator EndPt = DefMI
224
? MachineBasicBlock::iterator(DefMI) : MBB->begin();
226
while (MII != EndPt && !RefsInMBB.count(MII) &&
227
MII->getOpcode() != TRI->getCallFrameSetupOpcode())
229
if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
231
while (MII != EndPt && !RefsInMBB.count(MII)) {
232
// We can't insert the spill between the barrier (a call), and its
233
// corresponding call frame setup.
234
if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
235
while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
246
if (RefsInMBB.count(MII))
256
/// findRestorePoint - Find a gap in the instruction index map that's suitable
257
/// for restoring the current live interval value. The index must be before any
258
/// uses of the live interval register in the mbb. Return end() if none is
260
MachineBasicBlock::iterator
261
PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
263
SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
264
// FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
265
// begin index accordingly.
266
MachineBasicBlock::iterator Pt = MBB->end();
267
MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
269
// We start at the call, so walk forward until we find the call frame teardown
270
// since we can't insert restores before that. Bail if we encounter a use
272
MachineBasicBlock::iterator MII = MI;
273
if (MII == EndPt) return Pt;
275
while (MII != EndPt && !RefsInMBB.count(MII) &&
276
MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
278
if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
281
// FIXME: Limit the number of instructions to examine to reduce
283
while (MII != EndPt) {
284
SlotIndex Index = LIs->getInstructionIndex(MII);
288
// We can't insert a restore between the barrier (a call) and its
289
// corresponding call frame teardown.
290
if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
292
if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
294
} while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
299
if (RefsInMBB.count(MII))
308
/// CreateSpillStackSlot - Create a stack slot for the live interval being
309
/// split. If the live interval was previously split, just reuse the same
311
int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
312
const TargetRegisterClass *RC) {
314
DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
315
if (I != IntervalSSMap.end()) {
318
SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
319
IntervalSSMap[Reg] = SS;
322
// Create live interval for stack slot.
323
CurrSLI = &LSs->getOrCreateInterval(SS, RC);
324
if (CurrSLI->hasAtLeastOneValue())
325
CurrSValNo = CurrSLI->getValNumInfo(0);
327
CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
328
LSs->getVNInfoAllocator());
332
/// IsAvailableInStack - Return true if register is available in a split stack
333
/// slot at the specified index.
335
PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
336
unsigned Reg, SlotIndex DefIndex,
337
SlotIndex RestoreIndex,
338
SlotIndex &SpillIndex,
343
DenseMap<unsigned, int>::const_iterator I = IntervalSSMap.find(Reg);
344
if (I == IntervalSSMap.end())
346
DenseMap<SlotIndex, SlotIndex>::const_iterator
347
II = Def2SpillMap.find(DefIndex);
348
if (II == Def2SpillMap.end())
351
// If last spill of def is in the same mbb as barrier mbb (where restore will
352
// be), make sure it's not below the intended restore index.
353
// FIXME: Undo the previous spill?
354
assert(LIs->getMBBFromIndex(II->second) == DefMBB);
355
if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
359
SpillIndex = II->second;
363
/// UpdateSpillSlotInterval - Given the specified val# of the register live
364
/// interval being split, and the spill and restore indicies, update the live
365
/// interval of the spill stack slot.
367
PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, SlotIndex SpillIndex,
368
SlotIndex RestoreIndex) {
369
assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
370
"Expect restore in the barrier mbb");
372
MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
373
if (MBB == BarrierMBB) {
374
// Intra-block spill + restore. We are done.
375
LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
376
CurrSLI->addRange(SLR);
380
SmallPtrSet<MachineBasicBlock*, 4> Processed;
381
SlotIndex EndIdx = LIs->getMBBEndIdx(MBB);
382
LiveRange SLR(SpillIndex, EndIdx, CurrSValNo);
383
CurrSLI->addRange(SLR);
384
Processed.insert(MBB);
386
// Start from the spill mbb, figure out the extend of the spill slot's
388
SmallVector<MachineBasicBlock*, 4> WorkList;
389
const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
390
if (LR->end > EndIdx)
391
// If live range extend beyond end of mbb, add successors to work list.
392
for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
393
SE = MBB->succ_end(); SI != SE; ++SI)
394
WorkList.push_back(*SI);
396
while (!WorkList.empty()) {
397
MachineBasicBlock *MBB = WorkList.back();
399
if (Processed.count(MBB))
401
SlotIndex Idx = LIs->getMBBStartIdx(MBB);
402
LR = CurrLI->getLiveRangeContaining(Idx);
403
if (LR && LR->valno == ValNo) {
404
EndIdx = LIs->getMBBEndIdx(MBB);
405
if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
406
// Spill slot live interval stops at the restore.
407
LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
408
CurrSLI->addRange(SLR);
409
} else if (LR->end > EndIdx) {
410
// Live range extends beyond end of mbb, process successors.
411
LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
412
CurrSLI->addRange(SLR);
413
for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
414
SE = MBB->succ_end(); SI != SE; ++SI)
415
WorkList.push_back(*SI);
417
LiveRange SLR(Idx, LR->end, CurrSValNo);
418
CurrSLI->addRange(SLR);
420
Processed.insert(MBB);
425
/// PerformPHIConstruction - From properly set up use and def lists, use a PHI
426
/// construction algorithm to compute the ranges and valnos for an interval.
428
PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
429
MachineBasicBlock* MBB, LiveInterval* LI,
430
SmallPtrSet<MachineInstr*, 4>& Visited,
431
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
432
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
433
DenseMap<MachineInstr*, VNInfo*>& NewVNs,
434
DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
435
DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
436
bool IsTopLevel, bool IsIntraBlock) {
437
// Return memoized result if it's available.
438
if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
440
else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
442
else if (!IsIntraBlock && LiveOut.count(MBB))
445
// Check if our block contains any uses or defs.
446
bool ContainsDefs = Defs.count(MBB);
447
bool ContainsUses = Uses.count(MBB);
451
// Enumerate the cases of use/def contaning blocks.
452
if (!ContainsDefs && !ContainsUses) {
453
return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
454
NewVNs, LiveOut, Phis,
455
IsTopLevel, IsIntraBlock);
456
} else if (ContainsDefs && !ContainsUses) {
457
SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
459
// Search for the def in this block. If we don't find it before the
460
// instruction we care about, go to the fallback case. Note that that
461
// should never happen: this cannot be intrablock, so use should
462
// always be an end() iterator.
463
assert(UseI == MBB->end() && "No use marked in intrablock");
465
MachineBasicBlock::iterator Walker = UseI;
467
while (Walker != MBB->begin()) {
468
if (BlockDefs.count(Walker))
473
// Once we've found it, extend its VNInfo to our instruction.
474
SlotIndex DefIndex = LIs->getInstructionIndex(Walker);
475
DefIndex = DefIndex.getDefIndex();
476
SlotIndex EndIndex = LIs->getMBBEndIdx(MBB);
478
RetVNI = NewVNs[Walker];
479
LI->addRange(LiveRange(DefIndex, EndIndex, RetVNI));
480
} else if (!ContainsDefs && ContainsUses) {
481
SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
483
// Search for the use in this block that precedes the instruction we care
484
// about, going to the fallback case if we don't find it.
485
MachineBasicBlock::iterator Walker = UseI;
487
while (Walker != MBB->begin()) {
489
if (BlockUses.count(Walker)) {
496
return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
497
Uses, NewVNs, LiveOut, Phis,
498
IsTopLevel, IsIntraBlock);
500
SlotIndex UseIndex = LIs->getInstructionIndex(Walker);
501
UseIndex = UseIndex.getUseIndex();
504
EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
506
EndIndex = LIs->getMBBEndIdx(MBB);
508
// Now, recursively phi construct the VNInfo for the use we found,
509
// and then extend it to include the instruction we care about
510
RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
511
NewVNs, LiveOut, Phis, false, true);
513
LI->addRange(LiveRange(UseIndex, EndIndex, RetVNI));
515
// FIXME: Need to set kills properly for inter-block stuff.
516
} else if (ContainsDefs && ContainsUses) {
517
SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
518
SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
520
// This case is basically a merging of the two preceding case, with the
521
// special note that checking for defs must take precedence over checking
522
// for uses, because of two-address instructions.
523
MachineBasicBlock::iterator Walker = UseI;
524
bool foundDef = false;
525
bool foundUse = false;
526
while (Walker != MBB->begin()) {
528
if (BlockDefs.count(Walker)) {
531
} else if (BlockUses.count(Walker)) {
537
if (!foundDef && !foundUse)
538
return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
539
Uses, NewVNs, LiveOut, Phis,
540
IsTopLevel, IsIntraBlock);
542
SlotIndex StartIndex = LIs->getInstructionIndex(Walker);
543
StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
546
EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
548
EndIndex = LIs->getMBBEndIdx(MBB);
551
RetVNI = NewVNs[Walker];
553
RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
554
NewVNs, LiveOut, Phis, false, true);
556
LI->addRange(LiveRange(StartIndex, EndIndex, RetVNI));
559
// Memoize results so we don't have to recompute them.
560
if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
562
if (!NewVNs.count(UseI))
563
NewVNs[UseI] = RetVNI;
564
Visited.insert(UseI);
570
/// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
573
PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
574
MachineBasicBlock* MBB, LiveInterval* LI,
575
SmallPtrSet<MachineInstr*, 4>& Visited,
576
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
577
DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
578
DenseMap<MachineInstr*, VNInfo*>& NewVNs,
579
DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
580
DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
581
bool IsTopLevel, bool IsIntraBlock) {
582
// NOTE: Because this is the fallback case from other cases, we do NOT
583
// assume that we are not intrablock here.
584
if (Phis.count(MBB)) return Phis[MBB];
586
SlotIndex StartIndex = LIs->getMBBStartIdx(MBB);
587
VNInfo *RetVNI = Phis[MBB] =
588
LI->getNextValue(SlotIndex(), /*FIXME*/ 0, false,
589
LIs->getVNInfoAllocator());
591
if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
593
// If there are no uses or defs between our starting point and the
594
// beginning of the block, then recursive perform phi construction
595
// on our predecessors.
596
DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
597
for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
598
PE = MBB->pred_end(); PI != PE; ++PI) {
599
VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
600
Visited, Defs, Uses, NewVNs,
601
LiveOut, Phis, false, false);
603
IncomingVNs[*PI] = Incoming;
606
if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
607
VNInfo* OldVN = RetVNI;
608
VNInfo* NewVN = IncomingVNs.begin()->second;
609
VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
610
if (MergedVN == OldVN) std::swap(OldVN, NewVN);
612
for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
613
LOE = LiveOut.end(); LOI != LOE; ++LOI)
614
if (LOI->second == OldVN)
615
LOI->second = MergedVN;
616
for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
617
NVE = NewVNs.end(); NVI != NVE; ++NVI)
618
if (NVI->second == OldVN)
619
NVI->second = MergedVN;
620
for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
621
PE = Phis.end(); PI != PE; ++PI)
622
if (PI->second == OldVN)
623
PI->second = MergedVN;
626
// Otherwise, merge the incoming VNInfos with a phi join. Create a new
627
// VNInfo to represent the joined value.
628
for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
629
IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
630
I->second->setHasPHIKill(true);
636
EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
638
EndIndex = LIs->getMBBEndIdx(MBB);
639
LI->addRange(LiveRange(StartIndex, EndIndex, RetVNI));
641
// Memoize results so we don't have to recompute them.
643
LiveOut[MBB] = RetVNI;
645
if (!NewVNs.count(UseI))
646
NewVNs[UseI] = RetVNI;
647
Visited.insert(UseI);
653
/// ReconstructLiveInterval - Recompute a live interval from scratch.
654
void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
655
VNInfo::Allocator& Alloc = LIs->getVNInfoAllocator();
657
// Clear the old ranges and valnos;
660
// Cache the uses and defs of the register
661
typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
664
// Keep track of the new VNs we're creating.
665
DenseMap<MachineInstr*, VNInfo*> NewVNs;
666
SmallPtrSet<VNInfo*, 2> PhiVNs;
668
// Cache defs, and create a new VNInfo for each def.
669
for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
670
DE = MRI->def_end(); DI != DE; ++DI) {
671
Defs[(*DI).getParent()].insert(&*DI);
673
SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
674
DefIdx = DefIdx.getDefIndex();
676
assert(!DI->isPHI() && "PHI instr in code during pre-alloc splitting.");
677
VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
679
// If the def is a move, set the copy field.
680
if (DI->isCopyLike() && DI->getOperand(0).getReg() == LI->reg)
681
NewVN->setCopy(&*DI);
683
NewVNs[&*DI] = NewVN;
686
// Cache uses as a separate pass from actually processing them.
687
for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
688
UE = MRI->use_end(); UI != UE; ++UI)
689
Uses[(*UI).getParent()].insert(&*UI);
691
// Now, actually process every use and use a phi construction algorithm
692
// to walk from it to its reaching definitions, building VNInfos along
694
DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
695
DenseMap<MachineBasicBlock*, VNInfo*> Phis;
696
SmallPtrSet<MachineInstr*, 4> Visited;
697
for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
698
UE = MRI->use_end(); UI != UE; ++UI) {
699
PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
700
Uses, NewVNs, LiveOut, Phis, true, true);
703
// Add ranges for dead defs
704
for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
705
DE = MRI->def_end(); DI != DE; ++DI) {
706
SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
707
DefIdx = DefIdx.getDefIndex();
709
if (LI->liveAt(DefIdx)) continue;
711
VNInfo* DeadVN = NewVNs[&*DI];
712
LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
716
/// RenumberValno - Split the given valno out into a new vreg, allowing it to
717
/// be allocated to a different register. This function creates a new vreg,
718
/// copies the valno and its live ranges over to the new vreg's interval,
719
/// removes them from the old interval, and rewrites all uses and defs of
720
/// the original reg to the new vreg within those ranges.
721
void PreAllocSplitting::RenumberValno(VNInfo* VN) {
722
SmallVector<VNInfo*, 4> Stack;
723
SmallVector<VNInfo*, 4> VNsToCopy;
726
// Walk through and copy the valno we care about, and any other valnos
727
// that are two-address redefinitions of the one we care about. These
728
// will need to be rewritten as well. We also check for safety of the
729
// renumbering here, by making sure that none of the valno involved has
731
while (!Stack.empty()) {
732
VNInfo* OldVN = Stack.back();
735
// Bail out if we ever encounter a valno that has a PHI kill. We can't
737
if (OldVN->hasPHIKill()) return;
739
VNsToCopy.push_back(OldVN);
741
// Locate two-address redefinitions
742
for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(CurrLI->reg),
743
DE = MRI->def_end(); DI != DE; ++DI) {
744
if (!DI->isRegTiedToUseOperand(DI.getOperandNo())) continue;
745
SlotIndex DefIdx = LIs->getInstructionIndex(&*DI).getDefIndex();
746
VNInfo* NextVN = CurrLI->findDefinedVNInfoForRegInt(DefIdx);
747
if (std::find(VNsToCopy.begin(), VNsToCopy.end(), NextVN) !=
749
Stack.push_back(NextVN);
753
// Create the new vreg
754
unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
756
// Create the new live interval
757
LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
759
for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
760
VNsToCopy.end(); OI != OE; ++OI) {
763
// Copy the valno over
764
VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
765
NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
767
// Remove the valno from the old interval
768
CurrLI->removeValNo(OldVN);
771
// Rewrite defs and uses. This is done in two stages to avoid invalidating
773
SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
775
for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
776
E = MRI->reg_end(); I != E; ++I) {
777
MachineOperand& MO = I.getOperand();
778
SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
780
if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
781
(MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
782
OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
785
for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
786
OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
787
MachineInstr* Inst = I->first;
788
unsigned OpIdx = I->second;
789
MachineOperand& MO = Inst->getOperand(OpIdx);
793
// Grow the VirtRegMap, since we've created a new vreg.
796
// The renumbered vreg shares a stack slot with the old register.
797
if (IntervalSSMap.count(CurrLI->reg))
798
IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
803
bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
805
MachineBasicBlock::iterator RestorePt,
806
SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
807
MachineBasicBlock& MBB = *RestorePt->getParent();
809
MachineBasicBlock::iterator KillPt = BarrierMBB->end();
810
if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
811
KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
813
KillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
815
if (KillPt == DefMI->getParent()->end())
818
TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI, *TRI);
819
SlotIndex RematIdx = LIs->InsertMachineInstrInMaps(prior(RestorePt));
821
ReconstructLiveInterval(CurrLI);
822
RematIdx = RematIdx.getDefIndex();
823
RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
830
MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
831
const TargetRegisterClass* RC,
833
MachineInstr* Barrier,
834
MachineBasicBlock* MBB,
836
SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
837
// Go top down if RefsInMBB is empty.
838
if (RefsInMBB.empty())
841
MachineBasicBlock::iterator FoldPt = Barrier;
842
while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
843
!RefsInMBB.count(FoldPt))
846
int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg);
850
SmallVector<unsigned, 1> Ops;
851
Ops.push_back(OpIdx);
853
if (!TII->canFoldMemoryOperand(FoldPt, Ops))
856
DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
857
if (I != IntervalSSMap.end()) {
860
SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
863
MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
866
LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
867
FoldPt->eraseFromParent();
870
IntervalSSMap[vreg] = SS;
871
CurrSLI = &LSs->getOrCreateInterval(SS, RC);
872
if (CurrSLI->hasAtLeastOneValue())
873
CurrSValNo = CurrSLI->getValNumInfo(0);
875
CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
876
LSs->getVNInfoAllocator());
882
MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
883
const TargetRegisterClass* RC,
884
MachineInstr* Barrier,
885
MachineBasicBlock* MBB,
887
SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
888
if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
891
// Go top down if RefsInMBB is empty.
892
if (RefsInMBB.empty())
895
// Can't fold a restore between a call stack setup and teardown.
896
MachineBasicBlock::iterator FoldPt = Barrier;
898
// Advance from barrier to call frame teardown.
899
while (FoldPt != MBB->getFirstTerminator() &&
900
FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
901
if (RefsInMBB.count(FoldPt))
907
if (FoldPt == MBB->getFirstTerminator())
912
// Now find the restore point.
913
while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
914
if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
915
while (FoldPt != MBB->getFirstTerminator() &&
916
FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
917
if (RefsInMBB.count(FoldPt))
923
if (FoldPt == MBB->getFirstTerminator())
930
if (FoldPt == MBB->getFirstTerminator())
933
int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
937
SmallVector<unsigned, 1> Ops;
938
Ops.push_back(OpIdx);
940
if (!TII->canFoldMemoryOperand(FoldPt, Ops))
943
MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
946
LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
947
FoldPt->eraseFromParent();
954
/// SplitRegLiveInterval - Split (spill and restore) the given live interval
955
/// so it would not cross the barrier that's being processed. Shrink wrap
956
/// (minimize) the live interval to the last uses.
957
bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
958
DEBUG(dbgs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
963
// Find live range where current interval cross the barrier.
964
LiveInterval::iterator LR =
965
CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
966
VNInfo *ValNo = LR->valno;
968
assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
970
MachineInstr *DefMI = ValNo->isDefAccurate()
971
? LIs->getInstructionFromIndex(ValNo->def) : NULL;
973
// If this would create a new join point, do not split.
974
if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
975
DEBUG(dbgs() << "FAILED (would create a new join point).\n");
979
// Find all references in the barrier mbb.
980
SmallPtrSet<MachineInstr*, 4> RefsInMBB;
981
for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
982
E = MRI->reg_end(); I != E; ++I) {
983
MachineInstr *RefMI = &*I;
984
if (RefMI->getParent() == BarrierMBB)
985
RefsInMBB.insert(RefMI);
988
// Find a point to restore the value after the barrier.
989
MachineBasicBlock::iterator RestorePt =
990
findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB);
991
if (RestorePt == BarrierMBB->end()) {
992
DEBUG(dbgs() << "FAILED (could not find a suitable restore point).\n");
996
if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
997
if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt, RefsInMBB)) {
998
DEBUG(dbgs() << "success (remat).\n");
1002
// Add a spill either before the barrier or after the definition.
1003
MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1004
const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1005
SlotIndex SpillIndex;
1006
MachineInstr *SpillMI = NULL;
1008
if (!ValNo->isDefAccurate()) {
1009
// If we don't know where the def is we must split just before the barrier.
1010
if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1011
BarrierMBB, SS, RefsInMBB))) {
1012
SpillIndex = LIs->getInstructionIndex(SpillMI);
1014
MachineBasicBlock::iterator SpillPt =
1015
findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
1016
if (SpillPt == BarrierMBB->begin()) {
1017
DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1018
return false; // No gap to insert spill.
1022
SS = CreateSpillStackSlot(CurrLI->reg, RC);
1023
TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC,
1025
SpillMI = prior(SpillPt);
1026
SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1028
} else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1029
LIs->getZeroIndex(), SpillIndex, SS)) {
1030
// If it's already split, just restore the value. There is no need to spill
1033
DEBUG(dbgs() << "FAILED (def is dead).\n");
1034
return false; // Def is dead. Do nothing.
1037
if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1038
BarrierMBB, SS, RefsInMBB))) {
1039
SpillIndex = LIs->getInstructionIndex(SpillMI);
1041
// Check if it's possible to insert a spill after the def MI.
1042
MachineBasicBlock::iterator SpillPt;
1043
if (DefMBB == BarrierMBB) {
1044
// Add spill after the def and the last use before the barrier.
1045
SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1047
if (SpillPt == DefMBB->begin()) {
1048
DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1049
return false; // No gap to insert spill.
1052
SpillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
1053
if (SpillPt == DefMBB->end()) {
1054
DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1055
return false; // No gap to insert spill.
1059
SS = CreateSpillStackSlot(CurrLI->reg, RC);
1060
TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC,
1062
SpillMI = prior(SpillPt);
1063
SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1067
// Remember def instruction index to spill index mapping.
1068
if (DefMI && SpillMI)
1069
Def2SpillMap[ValNo->def] = SpillIndex;
1072
bool FoldedRestore = false;
1073
SlotIndex RestoreIndex;
1074
if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1075
BarrierMBB, SS, RefsInMBB)) {
1077
RestoreIndex = LIs->getInstructionIndex(RestorePt);
1078
FoldedRestore = true;
1080
TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC, TRI);
1081
MachineInstr *LoadMI = prior(RestorePt);
1082
RestoreIndex = LIs->InsertMachineInstrInMaps(LoadMI);
1085
// Update spill stack slot live interval.
1086
UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1087
RestoreIndex.getDefIndex());
1089
ReconstructLiveInterval(CurrLI);
1091
if (!FoldedRestore) {
1092
SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1093
RestoreIdx = RestoreIdx.getDefIndex();
1094
RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1098
DEBUG(dbgs() << "success.\n");
1102
/// SplitRegLiveIntervals - Split all register live intervals that cross the
1103
/// barrier that's being processed.
1105
PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1106
SmallPtrSet<LiveInterval*, 8>& Split) {
1107
// First find all the virtual registers whose live intervals are intercepted
1108
// by the current barrier.
1109
SmallVector<LiveInterval*, 8> Intervals;
1110
for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1111
// FIXME: If it's not safe to move any instruction that defines the barrier
1112
// register class, then it means there are some special dependencies which
1113
// codegen is not modelling. Ignore these barriers for now.
1114
if (!TII->isSafeToMoveRegClassDefs(*RC))
1116
const std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1117
for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1118
unsigned Reg = VRs[i];
1119
if (!LIs->hasInterval(Reg))
1121
LiveInterval *LI = &LIs->getInterval(Reg);
1122
if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1123
// Virtual register live interval is intercepted by the barrier. We
1124
// should split and shrink wrap its interval if possible.
1125
Intervals.push_back(LI);
1129
// Process the affected live intervals.
1130
bool Change = false;
1131
while (!Intervals.empty()) {
1132
if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1134
LiveInterval *LI = Intervals.back();
1135
Intervals.pop_back();
1136
bool result = SplitRegLiveInterval(LI);
1137
if (result) Split.insert(LI);
1144
unsigned PreAllocSplitting::getNumberOfNonSpills(
1145
SmallPtrSet<MachineInstr*, 4>& MIs,
1146
unsigned Reg, int FrameIndex,
1147
bool& FeedsTwoAddr) {
1148
unsigned NonSpills = 0;
1149
for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1151
int StoreFrameIndex;
1152
unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1153
if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1156
int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1157
if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1158
FeedsTwoAddr = true;
1164
/// removeDeadSpills - After doing splitting, filter through all intervals we've
1165
/// split, and see if any of the spills are unnecessary. If so, remove them.
1166
bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1167
bool changed = false;
1169
// Walk over all of the live intervals that were touched by the splitter,
1170
// and see if we can do any DCE and/or folding.
1171
for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1172
LE = split.end(); LI != LE; ++LI) {
1173
DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1175
// First, collect all the uses of the vreg, and sort them by their
1176
// reaching definition (VNInfo).
1177
for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1178
UE = MRI->use_end(); UI != UE; ++UI) {
1179
SlotIndex index = LIs->getInstructionIndex(&*UI);
1180
index = index.getUseIndex();
1182
const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1183
VNUseCount[LR->valno].insert(&*UI);
1186
// Now, take the definitions (VNInfo's) one at a time and try to DCE
1187
// and/or fold them away.
1188
for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1189
VE = (*LI)->vni_end(); VI != VE; ++VI) {
1191
if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1194
VNInfo* CurrVN = *VI;
1196
// We don't currently try to handle definitions with PHI kills, because
1197
// it would involve processing more than one VNInfo at once.
1198
if (CurrVN->hasPHIKill()) continue;
1200
// We also don't try to handle the results of PHI joins, since there's
1201
// no defining instruction to analyze.
1202
if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1204
// We're only interested in eliminating cruft introduced by the splitter,
1205
// is of the form load-use or load-use-store. First, check that the
1206
// definition is a load, and remember what stack slot we loaded it from.
1207
MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1209
if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1211
// If the definition has no uses at all, just DCE it.
1212
if (VNUseCount[CurrVN].size() == 0) {
1213
LIs->RemoveMachineInstrFromMaps(DefMI);
1214
(*LI)->removeValNo(CurrVN);
1215
DefMI->eraseFromParent();
1216
VNUseCount.erase(CurrVN);
1222
// Second, get the number of non-store uses of the definition, as well as
1223
// a flag indicating whether it feeds into a later two-address definition.
1224
bool FeedsTwoAddr = false;
1225
unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1226
(*LI)->reg, FrameIndex,
1229
// If there's one non-store use and it doesn't feed a two-addr, then
1230
// this is a load-use-store case that we can try to fold.
1231
if (NonSpillCount == 1 && !FeedsTwoAddr) {
1232
// Start by finding the non-store use MachineInstr.
1233
SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1234
int StoreFrameIndex;
1235
unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1236
while (UI != VNUseCount[CurrVN].end() &&
1237
(StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1239
if (UI != VNUseCount[CurrVN].end())
1240
StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1242
if (UI == VNUseCount[CurrVN].end()) continue;
1244
MachineInstr* use = *UI;
1246
// Attempt to fold it away!
1247
int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1248
if (OpIdx == -1) continue;
1249
SmallVector<unsigned, 1> Ops;
1250
Ops.push_back(OpIdx);
1251
if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1253
MachineInstr* NewMI = TII->foldMemoryOperand(use, Ops, FrameIndex);
1255
if (!NewMI) continue;
1257
// Update relevant analyses.
1258
LIs->RemoveMachineInstrFromMaps(DefMI);
1259
LIs->ReplaceMachineInstrInMaps(use, NewMI);
1260
(*LI)->removeValNo(CurrVN);
1262
DefMI->eraseFromParent();
1263
use->eraseFromParent();
1264
VNUseCount[CurrVN].erase(use);
1266
// Remove deleted instructions. Note that we need to remove them from
1267
// the VNInfo->use map as well, just to be safe.
1268
for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1269
VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1271
for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1272
VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1274
if (VNI->first != CurrVN)
1275
VNI->second.erase(*II);
1276
LIs->RemoveMachineInstrFromMaps(*II);
1277
(*II)->eraseFromParent();
1280
VNUseCount.erase(CurrVN);
1282
for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1283
VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1284
if (VI->second.erase(use))
1285
VI->second.insert(NewMI);
1292
// If there's more than one non-store instruction, we can't profitably
1293
// fold it, so bail.
1294
if (NonSpillCount) continue;
1296
// Otherwise, this is a load-store case, so DCE them.
1297
for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1298
VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1300
LIs->RemoveMachineInstrFromMaps(*UI);
1301
(*UI)->eraseFromParent();
1304
VNUseCount.erase(CurrVN);
1306
LIs->RemoveMachineInstrFromMaps(DefMI);
1307
(*LI)->removeValNo(CurrVN);
1308
DefMI->eraseFromParent();
1317
bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1318
MachineBasicBlock* DefMBB,
1319
MachineBasicBlock* BarrierMBB) {
1320
if (DefMBB == BarrierMBB)
1323
if (LR->valno->hasPHIKill())
1326
SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1327
if (LR->end < MBBEnd)
1330
MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1331
if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1334
MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1335
SmallPtrSet<MachineBasicBlock*, 4> Visited;
1336
typedef std::pair<MachineBasicBlock*,
1337
MachineBasicBlock::succ_iterator> ItPair;
1338
SmallVector<ItPair, 4> Stack;
1339
Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1341
while (!Stack.empty()) {
1342
ItPair P = Stack.back();
1345
MachineBasicBlock* PredMBB = P.first;
1346
MachineBasicBlock::succ_iterator S = P.second;
1348
if (S == PredMBB->succ_end())
1350
else if (Visited.count(*S)) {
1351
Stack.push_back(std::make_pair(PredMBB, ++S));
1354
Stack.push_back(std::make_pair(PredMBB, S+1));
1356
MachineBasicBlock* MBB = *S;
1357
Visited.insert(MBB);
1359
if (MBB == BarrierMBB)
1362
MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1363
MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1364
MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1366
if (MDTN == DefMDTN)
1368
else if (MDTN == BarrierMDTN)
1370
MDTN = MDTN->getIDom();
1373
MBBEnd = LIs->getMBBEndIdx(MBB);
1374
if (LR->end > MBBEnd)
1375
Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1382
bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1384
TM = &MF.getTarget();
1385
TRI = TM->getRegisterInfo();
1386
TII = TM->getInstrInfo();
1387
MFI = MF.getFrameInfo();
1388
MRI = &MF.getRegInfo();
1389
SIs = &getAnalysis<SlotIndexes>();
1390
LIs = &getAnalysis<LiveIntervals>();
1391
LSs = &getAnalysis<LiveStacks>();
1392
VRM = &getAnalysis<VirtRegMap>();
1394
bool MadeChange = false;
1396
// Make sure blocks are numbered in order.
1397
MF.RenumberBlocks();
1399
MachineBasicBlock *Entry = MF.begin();
1400
SmallPtrSet<MachineBasicBlock*,16> Visited;
1402
SmallPtrSet<LiveInterval*, 8> Split;
1404
for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1405
DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1408
for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1409
E = BarrierMBB->end(); I != E; ++I) {
1411
const TargetRegisterClass **BarrierRCs =
1412
Barrier->getDesc().getRegClassBarriers();
1415
BarrierIdx = LIs->getInstructionIndex(Barrier);
1416
MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1420
MadeChange |= removeDeadSpills(Split);